text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
30 July 2009 16:21 [Source: ICIS news] By Nigel Davis ?xml:namespace> Dow CEO Andrew Liveris was equally downbeat: “Our 2009 operating plan does not count material improvements in market conditions for the remainder of the year," he said. Both, in effect, are telling it like it is. “In our view, the “The economic outlook for the rest of 2009 appears to be stabilising with strong growth in Asia Pacific, especially But BASF board member, Martin Brudermuller, made the strong point that the company does not expect a further increase in business in The chemicals giant has seen stronger chemicals volumes but thinks demand is firmly rooted in government infrastructure and other stimulus related projects. As those lose steam, it is not certain that underlying demand will be maintained. Through this results season, so much is being made of sequential volume gains and sales lifted by stronger pricing that a central message is being lost. It was stressed by BASF earlier on Thursday and by Bock in a conference call. BASF, the broadest based chemicals manufacturer, expects global chemicals output to fall by 8% this year. This means that by the year end production will be back up to 2005 levels. The industry will have lost three years of growth. It is a question then of how swiftly business returns and in what markets. A bounce back currently seems hardly likely. Companies must expect to struggle to gain additional volumes. They will gain those volumes through broadened portfolios: both in terms of products and geography. As customer industries emerge from recession they will be seeking out improved offerings and new products. Often they will be seeking those offerings either from, or in, new geographies. Producers militate against the worst impacts of the downturn through a relentless focus on costs and productivity. They reacted swiftly to the onset of the recession in manufacturing by running output down and reining in costs of every kind. Like their counterparts in other sectors, and especially major customers in construction, automobiles, and electronics they will only bring capacities back on stream cautiously when the time is right. The downturn is prompting further chemical industry restructuring, both Dow and BASF talked about their styrenics businesses on Thursday. Dow said it had put aromatics and styrenics into a new unit that it would be prepared to sell. Output generally is still severely depressed. BASF said it was operating at just above 60% of global production capacity in the second half – it had been operating at just below 60% in the first three months of the year. Normally the company would be running at 80% or more.. This all adds to the lack of visibility for companies struggling to gain momentum coming off the bottom of the downturn. Financial analysts and others are poring over the current slew of results looking here and there for signs of a gain. Certainly, there is some encouragement to be had. Dow has shown sequential volume gains in its electronic and speciality materials, coatings and infrastructure and performance systems segments and basic plastics volumes were higher. At BASF the volume declines in chemicals and plastics were not as bad in the second quarter as they had been in the first. The company, however, is finding the going hard as it integrates businesses from Ciba Specialty Chemicals. Company specific issues aside, the reports from the two major broad based chemicals players on Thursday, as well as those from the two largest makers of petrochemicals – ExxonMobil and Shell – show that output remains depressed and suggest that recovery could take time. The outlook remains extremely difficult. For more on BASF, Dow, ExxonMobil Chemical.
http://www.icis.com/Articles/2009/07/30/9236351/insight+reality+hits+home+as+majors+look+to+second.html
CC-MAIN-2013-20
refinedweb
609
52.8
EBooks - Fiction, Nonfiction 1000s of them ~ Index ToMy MotherWho Has Been My Constant Help My FatherWho Was Proud Of Me AndMy Little Brother,These Two Long Asleep On The Hill At Carney— This Book Is Lovingly InscribedV. E. R. CHAPTER I THE VENTURERS CHAPTER II THE SPRING CHAPTER III NEW HOMES CHAPTER IV THE STRANGER FROM CIVILISATION CHAPTER V NOR'WESTERS CHAPTER VI SPRING TRADE CHAPTER VII FOREST NEWS CHAPTER VIII FIRST DAWN CHAPTER IX GOLD FIRE CHAPTER X THE SASKATOON CHAPTER XI LEAVEN AT WORK CHAPTER XII THE NAKONKIRHIRINONS CHAPTER XIII "A SKIN FOR A SKIN" CHAPTER XIV FELLOW CAPTIVES CHAPTER XV LONG TRAIL CHAPTER XVI TRAVEL CHAPTER XVII THE COMPELLING POWER CHAPTER XVIII "I AM A STONE TO YOUR FOOT, MA'AMSELLE" CHAPTER XIX THE HUDSON'S BAY BRIGADE CHAPTER XX THE WOLF AND THE CARIBOU CHAPTER XXI TIGHTENED SCREWS CHAPTER XXII "CHOOSE, WHITE WOMAN!" CHAPTER XXIII THE PAINTED POST CHAPTER XXIV THE STONE TO THE FOOT OF LOVE CHAPTER XXV ANSWERED PRAYERS CHAPTER XXVI SANCTUARY CHAPTER XXVII RETURN CHAPTER XXVIII THE OLD DREAM ONCE MORE CHAPTER XXIX BITTER ALOES CHAPTER XXX THE LAND OF THE WHISPERING HILLS CHAPTER I THE VENTURERS "Mercy!" to him there swam a mist of tears and the heart of the little maid tore at her breast in anguish. The smile slipped swiftly from the factor's face, leaving it grave. "Where, little one?" he asked. "Beyond the palisade. But hurry, M'sieu,—for the love of God!" At the great gate in the eastern wall he paused and looked either way. To the southward all was peaceful. An aged Indian of the Assiniboines squatted at the water's edge mending the broken bottom of a skin canoe, and two voyageurs, gay in the matter of sash and crimson cap, lay lazily beneath a drowsing tree. To the northward there flashed into McElroy's vision one of those pictures a man sees but few times and never forgets, a picture startling in its clear-cut strength. Against the mellow background of the weather-beaten stockade that surrounded the post there stood two figures, a man and a woman, and between the two there crouched with snarling lips and flaming eyes a huge grey dog. Tall he was, that man, tall and broad of shoulder, but the head of the woman, shining like blue-black satin in the morning sun, was level with his brows. She leaned a trifle forward and her eyes held fast to his passion- flooded face. It was evident that she had but just reached the spot from the fact that the club, arrested in its upward swing, still was poised in the air. They. "Of a surety," she said slowly, and there was a subtle tone in her deep-throated voice that made the blood stir vaguely within the factor's veins, "does M'sieu have so many strangers passing through his gates that he is at loss to place each one?" And with that word she turned deliberately away, walked down toward the gate, and entered the stockade. McElroy watched her go, until the last glint of her sober dress, plain and clinging easily to the magnificent shoulders that swung slightly with her free walk, had passed from view. And not alone he, for the two voyageurs alike gazed after her, this new-comer from the farther ways of civilisation who dared the brute DesCaut and struck like a man. Then the factor bent above the little Francette. "Sh!" he said gently, "little one, let go. The dog is dead, poor beast. Come away." But the maid would not give up the battered body, and with the audacity of her beauty and life-long spoiling, besought the young factor for help. "There is yet life, M'sieu. See! The breath lifts in his sides. Is there naught to be done when one sleeps, so? He is so strong at the sledges and he did not whimper,—no, not once,—when DesCaut was beating him to death. Is there nothing, M'sieu?" Very pretty she was in her pleading, the little Francette, with her misty eyes and the frank tears on her cheeks; and McElroy went to the river and filled his cap with water. This he poured into the open jaws and sopped over the blood-clotted head, wetting the limp feet and watching for the life she so bravely proclaimed. And presently it was there, twitching a battered muscle; lifting the side with its broken ribs, fluttering the lids over the fierce eyes; for this was Loup, the fiercest husky this side of the Athabasca. With pity McElroy gathered up the great dog, staggering under the load, for it was that of a big-framed man, and entered the post, the little maid at has side. Near the gate a running crowd met them, for the tale had spread apace and wondering eyes looked on. Down to the southern wall where lived the family of Francette they went, and the factor laid Loup in the shade of the cabin. "If he lives, little one, he shall be yours," said he, "for he is worth a tender hand. We'll try its power." And as he turned away he caught a glimpse of the tall stranger looking at them from a distance. Small it was and crowded, this little trading post of the great Hudson's Bay Company in that year of 1796, and a goodly stream of beaver found its way through it to the mighty outside world. Squatted alone on the shores of the Assiniboine, shouldering back the wilderness with the spirit of the conqueror, it faced the rising sun with its square stockade, strong and well built, log by log, its great, brass-studded gate in the eastern centre, its four bastions rising at its corners. Here. When release was very welcome. The somewhat fickle stream of the Assiniboine had loosed its locks of ice and rolled and gurgled, full to its low banks, as if the late summer would not see it shrunk to a lazy thread, refusing sometimes even the shallow canoes and barely licking the parched lips of the land. In gay attire the maids of De Seviere ventured beyond the gates to stray a little way into the forest and come back laden with tiny green sprays of the golden trailer, with wee white blossoms and now and again a great swelling bud of the gorgeous purple flower of the death plant. "Bien! It is of a drollness, mes cheries," laughed Tessa Bibye one day, stopping at the cabin by the south wall; "how Francette does but sit in the shade and nurse that half-dead wolf. Is it by chance because of the owner, or that hand which carried it here, Francette? Look for the man behind Francette's devotion ever!" Whereat there was a laugh and crinkling of pretty dark eyes at the little maid's."." A swift change had fallen into the depth of her golden voice, a subtle wistfulness that sang with weird pathos, and the eyes raised toward the western rim of the forest were suddenly far and sombre. "Forgive!" said her sister gently; "I had forgot. I know the dream, but is it not better that we rest and gain new strength for another season? Here might well be home, here on this pretty river. We have come a mighty length already. What could be fairer, cherie,—even though we leave another to win to the untracked West." A small spasm drew across the features of Maren, a twitching of the full lips. "Faint heart of you," she said sadly. "Oh, Marie, 'tis your voice has ever held us back. They would prod faster but for you. Is there no glory within you, no daring, no dreams of conquest? Bien! But I could go alone. This dallying stiffles the breath in me!" She put up a hand and tore open the garment at her throat, taking a deep breath of the sunlit air. "But it is poverty that must be reckoned with. By spring again we may be better equipped than ever." So rode up the hope that was ever in her. "Yes," sighed Marie, "as the good God wills." But she glanced wistfully around the new cabin, to be her own for the length of the four seasons. And who should say what might not happen in four seasons? She wondered fretfully what fate had fashioned the glorious creature beside her in the form of Love itself to put within the soul of the restless conqueror. Never had she known Maren, though they two had come from the same lap. Presently Maren looked down at her, and the shimmering smile, like light across dark waters, had again returned. "Nay," she said gently, "fret not. It is spring-and you have at last a home." True, it was spring. Did not each breath of the south wind tell it, each flute-like call from the budding forest without the post, each burst of song from some hot-blooded youth with his red cap perched on the back of his head, his gay sash knotted jauntily? It stirred the heart in the breast of Maren Le Moyne, but not with the thought of love. It called to her as she stood at night alone under the stars, with her head lifted as if to drink the keen, sweet darkness; called to her from far-distant plains of blowing grass, virgin of man's foot; from rushing rivers, bare of canoe and raft; from high hills, smiling, sweet and fair, up to the cloudless sky—and always it called from the West. Spring was here and cast its largess at her feet,—fate held back her eager hand. A year she must wait, a year in which to win those necessaries of the long trail, without which all would fail. Travel, even by so primitive a method as canoe and foot, must demand its toll of salvage. At Rainy Lake they had been held by thieving Indians and a great part of their provisions taken from them, leaving them to make their way in comparative poverty to the next post of De Seviere. Further progress that year was impossible. Therefore, the contract of the trappers with the factor. And Maren Le Moyne—venturer of the venturers, flame of fire among them, urger, inspirer, and moral leader, a living pillar before them in her eagerness—must needs curb her soul in bonds of patience and wait at Fort de Seviere for another spring. Close beside her in her visions and her high hope, her courage and her eagerness, stood that leader of the little band, Prix Laroux. Fed by her fire, touched by her enthusiasm, the man was the mouth piece for the woman's force, the masculine expression of that undying hope of conquest which had drawn the small party together and set it forth on the perilous venture of pushing toward the unknown West to find for itself an ideal holding. Back at Grand Portage the girl had listened from her late childhood to tales of the wilderness told at her father's cabin by voyageurs and trappers, by returning wanderers and stray Indians smoking the peace- pipe at his hearth. Long before she had reached the stature of woman she had sat on her stool beside that jovial old man, her father, grimy from his forge, and drunk the tales wide-eyed, to creep away and watch the stars, to dream of those dashing streams and to clinch her hands for that she was not born a man. And then when she was fifteen had come the day when the tales had at last kindled to flame the parent fire of that wildness in her which slept unsuspected in the breast of the blacksmith, then old as the way of life runs, and he had closed his cabin and his forge, given his two motherless girls to the wife of Jacques Baptiste, joined a party going into the wilderness, and gone out of their lives. Eleven years had passed with its varied life, at Grand Portage and he had never returned,—only vague rumors that had sunk in tears the head of gentle Marie, the younger of the two sisters, and lifted with sympathetic understanding that of Maren the elder. Why not? She had asked herself in the starlit nights of those years, why not? All their lives he had been a good father to them, taking the place of the mother dead since she could just remember, speeding with tap and stroke of his humble craft those luckier ones who streamed through the stirring headquarters of Grand Portage at the mouth of Pigeon River each season, going into that untracked region of romance and dreams where the call of his still sturdy manhood had beckoned him,—how long none might know. And at last he had heeded, laid down the staid, the sane, and followed the will-o'-the-wisp of conquest and adventure that took the current by his door. Never had Maren chided him,—never for one moment held against him the desertion of his children.. So tenderly had the two maids grown in the love of the family that Marie had, but at the start of the great journey, married young Henri Baptiste. Marie was all for a home and some black-eyed babies, but she clung to Maren as she had ever done,—and now, in her twenty-sixth year, Maren had risen to the call as her father had done before her, and lifted her face, rapt as some pagan Priestess', toward that mystic West,—bound for the Land of the Whispering Hills, whence had come that old, vague rumour, lured alike by love of the unknown and shy, unspoken longing for the father whose heart must be the pattern of her own. And in her train, swept together by that fire within her, touched into flame by her ever-mounting hope, her courage, and her magnetism, went that small band of men and women, all young, all of adventurous blood, all daring the odds that let reluctantly a woman into the wilderness. Yet it has been ever women who have conquered the wilderness, for until they trod the trace the men had cut it still remained a wilderness. So she leaned in the door of Marie's new home, this taut-strung Maren Le Moyne, and gazed away above the rim of the budding forest, and her spirit was as a chaffing steed held into quiet by a hand it knows its master. For a year she must endure the strain,—then, as the good God willed, the leap forward, the wild breath in her nostrils, the forging into the unknown. "Ah, yes!" she said again, "it is the spring." "Bon jour," she nodded, unsmiling, as a slim youth swung jauntily up the hard-beaten way between the cabins. "Eh!" said Marie, alert, "and who is that lord-high-mighty, with his red cheeks and his airs, Maren? You know, as it is always, every man in the post already. It is not so with the women, I'll wager. For instance, who lives in the tiny house there by the south bastion?" "I know not," answered Maren, as though she humoured a child, and taking the last question first; "as for the youth, 'tis young Marc Dupre, and one of a sturdy nature. I like his spirit, though all I know of it is what sparkles from his roguish eyes. A fighter,—one to dare for love of chance." Marie looked quickly up, ever ready to pounce on the first gleam of aught that might ripen into a love interest, but she saw Maren's eyes, cool and shining, watching the swaggering figure with a look that measured its slim strength, its suggestion of reserve, its gay joy of life, and naught else. "A pretty fellow," she said, with a touch of disappointment. Each and every man went by Maren just so,—eliciting only that interest which had to do apart from the personal. But the black eyes of Marc Dupre had softened a bit under their daring as he approached the factory. "Holy Mother!" he whispered to himself; "what a woman! No maid, but a WOMAN—for whose word one would fillip the face of Satan. She is fire—and, if I am sure, all men are tow." CHAPTER." "Thank you, Jean," said McElroy; "I will prepare for the meeting." The trapper touched his cap and passed. "Ah," smiled the factor to himself, "I like this bustle of passage. It is good after the winter's housing, and who knows? There may be those among the strangers who bring word from Hudson Bay." He turned briskly back and gave word to Jack de Lancy and his wife Rette to cook a great meal, also to see that the store-room was cleared sufficiently by the more orderly packing back of the goods to allow of five canoe-loads of men sleeping upon the floor. Then he passed down the main way, out of the gate in the warm sun and took his place at the landing to look eagerly down stream for the first coming of the strangers. Not far from the enthusiasm of boyhood was this young factor of Fort de Seviere. And within the hour, as Jean had said, they came, rounding the distant bend in an even distanced string, long narrow craft, each bearing the regular complement of five men, a bowman, a steersman, and three middlemen whose paddles shone like crystal as they sank and lifted evenly. Strangers they were in very truth, as McElroy saw at the first glance. Never had they been bred in the wilderness, these men, unless it were the two guides in the first and fourth canoe, picked out readily by their swarthy skins, their crimson caps, and their rugged litheness. Fairer, all, were the rest, paler of skin, more loose of muscle, shown by the very way they bent to their work. Their garments, too, as they drew nearer brought a smile to the watcher's lips, a smile of memory. Those coats, brave in their gilt braid, had assuredly come across seas. Thus might one behold them on the Strand. Ah! These were, without doubt, part of the fall ship's load of adventurers come to the new continent filled with the fire of achievement and excitement that brought so many youths over seas. They had, most like, come down from the great bay by way of God's Lake and the house there, traversed the length of Winnipeg, come along the river at the southern end, and at last turned westward into the Assiniboine. A long rest they would no doubt take at Fort de Seviere, and there would be news of the outside world. McElroy was at the water's very edge as the first canoe of the string curved gracefully in and cut slimly up to the landing. "Welcome, M'sieurs," called the factor of Fort de Seviere, using unconsciously the speech of the region, which had become his own in five years, "in to the right a bit,—so! Well done!" The word was not so sincere as he would have made it, for the bowman, jumping out into the knee-deep water to keep the boat from touching bottom, had floundered like an ox, thereby proving his newness at the business. On the face of the swarthy Canuck guide who sat in the stern there was a weary contempt. "Friends, M'sieurs?" called McElroy tardily, scarcely deeming such precaution necessary, yet giving the hail from force of habit. They looked for the most part Scottish, these men, save here and there among them one who might be anything of the motley that came across each year. In the first canoe a figure had risen and stood tall and straight among the bales of goods with which the craft was seen to be close packed from bow to stern, a figure striking in its lack of kinship to its surroundings, yet commanding in its beauty. Garments of cloth, of a gay blue shade and much adorned with trimming of gold braid, fitted close to the slender form of the man. His limbs from the knee were encased in leggings made, most evidently, in some leather shop, while tilted on his splendid head he wore a hat of so wide a brim that no sunlight touched either face or throat, while from beneath this covering there fell to his shoulder long curls of hair that shone like silk. This, evidently, was the leader of the party. "Friends," he said, "bound for the west and the country of the Saskatchewan." For all his appearance he spoke with the accent of the French, and for a moment McElroy looked closely at him. "Of the Company?" he asked sharply. "Aye," said the other, with a little of wonder in voice and look, "of the Company, M'sieu most assuredly." The momentary flicker of uneasiness that had gripped the factor with the stranger's speech died at his words. So, of a surety, why not? Had not he himself, born in the smoke of a London street, accepted with the ingenious adaptability of the Irish blood within him the very speech he now wondered at in the other? As the young man sprang lightly to land he held out his hand, and it was gripped with a force that showed the spirit behind the beauty of this new guest. "Welcome, M'sieu," said the factor, "to Fort de Seviere and all it contains." "Bien!" laughed the other with a show of fine white teeth, "but it is good to behold neighbours in so deadly a wilderness as we have passed through for these many days. Naught but God-forgotten loneliness and never-ending forest. Yet it is for these that we barter the comforts of civilisation, eh, M'sieu, and waste ourselves on solitude and the savage?" He turned and waved his gloved hand over the five canoes, now curving one by one in to the landing, and shouted a few terse orders and commands. "But I had nigh forgot, so unused am I to society and the usages thereof,"—he said, turning back with an engaging smile, "Alfred de Courtenay, known in that world across the water; and which my taste, or that of itself, more properly speaking, has caused me to forswear for some length of time, as Mad Alfred, I am, M'sieu—?" "Anders McElroy," supplied the other, "and factor of Fort de Seviere." "Monsieur le facteur, your servant, of French lineage, English nativity, and adventurous spirit." With a motion indescribably graceful he swept off his wide hat and executed a bow which in itself was proof of his gentleness. "And now, M'sieu, lead on to those delights of rest and converse which your hospitality hath so graciously promised." Leaving his company to beach and store for the night the canoes with their loads of merchandise, under the direction of his aide or lieutenant whom he introduced to the factor as John Ivrey, a young man of fine presence, Alfred de Courtenay walked beside McElroy up the gentle slope of the river bank, entered the great eastern gate of the post, not without an appreciative glance at its massive strength and at the well-nigh impregnable thickness of the stockade, the well-placed surveillance of the towering bastions, and thus up the way between the cabins to the door of the factory, open and inviting. "Mother of God, M'sieu!" he said with a copious sigh; "what it is to meet with white faces! For weeks I have beheld along the shores peering brown countenances that lifted my gorge, and I have well-nigh been tempted to turn back." "It has been a long journey, then, to you?" McElroy smiled, thinking of the first impressions and effect of the wilderness on such a man fresh from the ways of civilisation. "Long? Though it is my initial journey, yet am I veteran frontiersman." He turned upon the factor the brilliance of his smile, a combination of dazzling teeth and eyes that fairly danced with spirit, like bubbling wine, blue and swift in their changes from laughter to an exaggerated dolorousness, as when he spoke of these terrible hardships. And if they were quick after this fashion they were no less so in roaming keenly over every corner of the enclosed space within the stockade. Before they had reached the factory the stranger knew that there were three rows of cabins in the post, that the factory was a mighty fortress in its low solidity, and that the small log structure to the right of it with the barred window was the pot au beurre. As they neared the factory the figure of a tall woman, young by the straightness of the back, the gracious yet taut beauty of line and curve, came from behind the cabin of the Savilles, and on her shoulder was perched a three-year-old child which laughed and gurgled with delight, holding tight to her widespread hands. The woman's face was hidden by the child's body, but her voice, deep-throated and rich with sliding minor tones, mingled with the high shrillness of the little one's shrieks. "Hold fast, ma cherie," came its laughing caution, smothered by the flying folds of the baby's little cotton shift." See! The ship dips so, in the ocean,—and so,—and so!" The strong arms, bare and brown and muscular, swayed backward, throwing up the milky whiteness of the little throat, the tiny feet flew heavenward and the baby's wee heart choked it, as witness the screams of irrepressible joy. As the child swayed back there came into view the face of Maren Le Moyne, flushed all over its rare darkness, glowing with tenderness, its great beauty transfigured divinely. The black braids, wrapped smoothly round her head, shone in the evening sun, and the faded garment, plain and uncompromising, but served to heighten the effect of her physical perfection. Alfred. "What. "And you came, I suppose, from York Factory, down by way of God's Lake and the house there. What is the word of Anderson who presides there? A fine fellow,—I met him once at Churchill." "York Factory? God's Lake?" De Courtenay lowered his pipe and looked through the smoke. "Nay," he said, "I know nothing of those places, M'sieu." He turned to young Ivrey. "It might be that these locations answer to different names. Heard you aught from the guides of these two posts?" "We did not pass them, Sir Alfred," answered the young man soberly. "Then, in Heaven's name, which way have you journeyed?" asked McElroy amazed. "Why, by way of Lake Nipissing, across the straits below the Falls of St. Mary, by canoe along the shores of Lake Superior, into Pigeon River, and so on up the various streams to your own Assiniboine—from Montreal. How else, M'sieu?" But the factor of Fort de Seviere had risen in his place, his face gone blank with consternation. "From Montreal!" he cried, "but did you not answer to me as friends and of the Company" "Aye," answered De Courtenay, also rising, the gaiety fading from his face and his eyes beginning to sparkle bodefully, "of the North-west Company, trading from Montreal into the fur country. I am sent of my uncle Elsworth McTavish, who is a shareholder and a most responsible man, to take charge of the post De Brisac on the south branch of the Saskatchewan. But I like not this sudden gravity, M'sieu. Wherein have I offended?" "In naught, De Courtenay," said McElroy quite simply, "save that you are in the heart of the country belonging to the Hudson's Bay Company, as does this fort and all therein." "Nom de Dieu!" cried the other, springing back and tossing up his head; "I knew it not! How is it, then, that at midday of this day we met on the river one who told us of this post of De Seviere, and that it served the Montreal merchants? That we should here find hospitality and friends?" "Eh?" shot out McElroy sharply. "Of what like was such a person?" "A big man, swarthy and dark, with sullen eyes, clad in garments of tanned hides and wearing a red cap and a knife in his belt. He bore on his left temple a pure white lock amid his black hair." "Bois DesCaut!" said Edmonton Ridgar; "he has been these two days gone in his canoe." "A traitorous trapper, M'sieu," said the factor, "one who has umbrage at me for a rebuke administered some time back and hopes by this sorry joke to win revenge. But what is done cannot be helped. We have met as friends,—the unfortunate fact that we find ourselves rivals,—that almost speaks the word 'foes,' I must inform you, M'sieu, since the strife between our companies has become so sharp,—should not cause us to forget the bread we have broken between us personally. I still offer you a night's rest." But De Courtenay had drawn himself to his slender height, his hand at his hip, where, in other times, had dangled a sword. "Nay, M'sieu," he said quickly, "a blunder found and unremedied becomes two. If I ay gather my men we will sleep outside an unfriendly fort,— and in the name of De Courtenay allow me to repay the cost of their entertainment." Reckless, indeed, was this young cavalier, else he would not have made that speech. Anders McElroy turned white beneath his tan and his fingers tapped the table. "Not ungrateful am I, M'sieu, but I stick by the colours I choose. If our companies are rivals, then we are such, and I follow my master's lead. It is at present the North-west organisation. I am pledged in Montreal—and—I prove faithful." The young man's face was fired with that spirit which ever lay so near the surface and he looked at his whilom host with a mighty hauteur. "I thank you for your kindness, M'sieu, but I must decline it further. Come, Ivrey," and turning he picked up his wide hat, bowed first to McElroy and then to Ridgar, and strode toward the outer door. As he passed the lintel the not insignificant form of Rette blocked his exit, en route for a cup she had left behind. With an instant flourish the hat in his hand swept the logs of the floor, he seized the woman's toil-hard fingers and bore them to his lips. "Excellent, Madame, was that meal," he murmured, "and never to be forgot so long as one unused to hardship faces privation. I thank you." Comely Rette flushed to her sleek hair and some flicker of a girlhood that had its modicum of grace, flared up in the swift curtsy with which she acknowledged the compliment. And with a last flash of his blue coat Alfred de Courtenay was gone. McElroy ran his fingers helplessly through his tousled light hair and faced his friend. "Now, by all the Saints!" he said with a strange mixture of regret and relief, "what an unhapy ending!" But at that moment he was thinking of the wondrous beauty of the man and of the picture of Maren Le Moyne's brown arms spread wide apart with the laughing child between, and again that little feeling of vexation crept into his wholesome heart. Without in the soft night the late guest was striding, a graceful figure, hurriedly down toward the gate he had entered so short a time ago, and his slender hand played restlessly at his hip. His heart was seething with swift-roused emotions. So had its quick stirrings brought him into many a scrape in his eventful life. That word of his host, "which speaks almost of foes," sang in his ears. And yet it had been given only in the spirit of enlightenment. Behind, John Ivrey gathered up the men idling about the fire and talking with the men of the post, where question and answer had begun to stir uneasiness. In a ragged, uneven line they strung out, fading into the darkness, and presently from down the river some forty rods there rose up the columns of their fires. Fort. "A.. Side by side, conversing in a few sentences, the trader and the chief entered the post, followed by the headmen and proceeded to the factory, where McElroy stood to welcome them in the open door. They entered, to the ceremony of the pipe, the speech, and the bargain, while those without made a great camp two hundred strong all along the bank of the stream, beached the canoes, stacked the beaver packs, set up the tepees of the seventeen sticks, and built the little fires without which no camp is a camp. In a little space the quiet shore was all a-bustle and activity reigned where the silence of the spring morning had lain, dew-heavy. Among those most eager who peered at the gate, and who presently ventured forth to the better view the bustling concourse of braves and squaws, was Maren Le Moyne, her dark eyes wide, soft lips apart, and face all a-quiver with keen enjoyment of the scene. These were the first she had ever seen of those Indians who came from the west. Who knew? Perhaps those moccasined feet had trod the virgin forest of her dreams, those sombre eyes looked upon the Whispering Hills, those grave faces been lifted to the sweet wind that sang from the west and whose caress she felt even now upon her cheeks. Perhaps,—perhaps, even, some swift forest-runner among them, far on his quest of the home of the caribou or with news of some friendly tribe, had come upon a man, an old man rugged of frame and face, with blue eyes like lakes in his swarthy darkness, and muscles that bespoke the forge and hammer. Who knew? Maren's strongly modelled chin twitched a bit while the little flame of tenderness that flickered ever behind the graveness of her eyes leaped up. She longed for their speech that she might go among them and ask. A little way along the stockade wall to the north there lay a great rock, flat and smooth of surface, and here the girl drew apart from the women and sat herself down thereon, hands clasping her knees and the level sun in her eyes. Her thoughts were soon faraway on the misty trail they had worn for themselves in the many years they had traversed the wilderness in search of what it held, and the eyes between the narrowed lids became blank with introspection. And as she sat thus, a little way withdrawn from the scurrying activity of the scene, there came a, step on the soft green sod and a slim form in buckskins halted beside her. It was young Marc Dupre, and his devil-may-care face was alert and smiling. "Is that seat big enough for two, Ma'amselle?" he asked impertinently, though the heart in him was thumping a bit. This was a woman, he recalled having thought, for whom one would fillip the face of Satan, and he was uncertain whether or no he had made a right beginning. Maren started and looked swiftly up at him. "It is, M'sieu," she said quietly, "if those two are in simple, sensible accord. Not if one of the two coquettes." Over the handsome features of the youth there spread a deep red flush. "Forgive me, Ma'amselle," he said, "my speech was foolish as my heart. They are both sobered." "Then," said the girl, drawing aside the folds of her dress, "you may sit beside me." With a sudden diffidence he sank upon the stone, this handsome boy whose tongue was ever ready and whose heart of a light o' love had taken toll from every maid in the settlement, and for the first time in his life he had no sprightly word, no quip for his careless tongue. They sat in silence, and presently he saw that her eyes were again half-closed and the dreaming look had settled back in them. She had forgotten his presence. Never before in his experience had a woman sat thus unmoved beside him when he longed to make her speak, and it stilled him with silent wonder. He thought of the words of Pierre Garcon that day on the river bank when this maid was new to the post, "if there is, I would not be the one to waken it and not be found its master," and they sent a thrill to his inmost being. Who would awaken her; he wondered, as he watched the cheek beside him from the tail of his eye, a round womanly cheek, sweet and full and rich as a damask rose with the thick lashes above shining like jet. Obedient to her silence, he sat still while she dreamed her dream out to its conclusion, and presently she straightened with a little breath like a sigh, unclasped her hands from her knees and turned her glance upon him as if she saw him for the first time. His head whirled suddenly and he sought for some common word to cover his rare confusion. "See, Ma'amselle," he said, pointing, "the well-lashed packs of the fat winter beaver. Truly they come well laden, these Assiniboines, and we may well thank le bon Dieu for the wealth of skins. Is it not a heartening sight?" The eyes of Maren Le Moyne left his face and swept swiftly down the gentle slope to where the Indians had piled their bales of furs. At the sight they darkened like the waters of a lake when a little wind runs over its surface. "A heartening sight? Nay, M'sieu," she said, shaking her head, "I can find no joy in it." "What?" The trapper was aghast. "No pleasure in the fruits of a fat season?" "See the packs of marten, the dark streaks showing a bit at the edges where the fur rounds over the dried skin. How were those pelts taken, M'sieu?" "How? Why, most cunningly, Ma'amselle,—in traps of the H. B. Company, set with utmost skill, perhaps on a stump above the line of the heavy snows, or balanced nicely at the far end of a slender pole set leaning in the ground. The delicate hand of a seasoned player must match itself with the forest instinct of these small creatures. The little pole holds little snow and the scent of the bait calls the marten up, when, snap! it is fast and waiting for the trapper and the lodge of the Assiniboines, the women and the drying." "Yes. And those hundreds of beaver, M'sieu?" Marc Dupre's eyes were shining and the red in his cheeks flushing with pleasure. What more to a man's liking than the exploitation of knowledge gained first-hand in the pursuit of his life's work? "Again the trap," he said, "set this time at the edge of a stream where the beaver huts peek through the ice, or lift their tops above the open water. Neatly they are set, cunning as an Indian himself; hidden in the soft slime at the margin if the water runs, waiting with open jaws in the small runway above the dam where the creatures come out from the swim. A sleek head lifting above the ripples a scrambling foot or two, —snap! again the price of a pound and a half of powder, a tie of tobacco. No footmark must the hunter leave, Ma'amselle, unsplashed with water, no tainting touch of a hand ungloved on chain or stake or trap itself. Ah! one must know the woods and the stream, the cold and the snow and the winds." "You know them, M'sieu, I have no doubt," said Maren, "for you follow the trapping trail. And those beautiful silver fox, frosty and fine as the sparkle of a winter morning? The heavy hides of the bear, soft and glossy and thick as a folded blanket?" "All the trap,—unless the latter drops through the flimsy roof of some well-hidden dead-fall, covered with brush." The girl was not looking at him, her glance being still on the bustling camp below. The fingers on her knee were laced tight together. Now she began to speak in a low voice, deep and even. "Aye! All you have said is true. Wealth, indeed, is in those packs, and patience and cunning and utmost skill, defiance of the snows and the crackling cold, long miles on snowshoes and the hardships of the trail, the nights in the bough-tied huts, the pack galling the shoulders. But what is all this beside that which waits the runner of the trail at every 'set' in those many miles? Here he finds his leaning-pole. There have been little tracks up its slim roadway, but those were covered by the fall of three days back and the little creature who made them hangs there at the end, three small feet beating the cold air feebly, a tiny head squirming from side to side, two dull black eyes set at the distorted world. He has caught his marten. It has not frozen, for the snow was light and the forest still and thick, and three days have passed, M'sieu. Three days! Mon Dieu! How much were those three days worth? The trapper taps the squirming head and puts the bit of fur in his pack-bag. On to the next. The beaver? Dead, M'sieu, thanks to the good God, drowned in its own sweet water. The pack is heavy with small bodies ere the Assiniboine reaches the place where he has laid his trap for the silver fox. And what greets him here? Only a foot gnawed off in the silence of the day and the night, and some beauty gone staggering away to lie and suffer with starvation in the cold." The youth was staring at the averted face beside him, mouth open and utter amazement on his features. Maren went on. "And lastly, M'sieu, far at the end of the trail,—at the outer, rim of the circle traced by his traps,—he comes eagerly, to peep and peer for what might have happened at the head of the little dip leading down to the stream where the firs bend heavily under their weight of snow. "Here he had laid his cunningest instrument, a thing of giant jaws, of sharp ragged points, each inlocking with the other, the whole unholy thing hung to a chain at whose other end there lay a ball of iron, weighing, M'sieu, some eighty pounds. That was for the .great shy bear, rocking along ire his quest of berries or some tree that should ring hollow under his scratching claws, bespeaking the hive of the wild bees. The oiled and fur-wrapped Indian stoops down and looks along the dip. Ah! There he sees that which brings a glint to his small eyes. No bear, M'sieu, nor yet the trap he had left, but a thrashed and broken space where the snow went flying in clouds and the bushes were torn from their roots, where the very tree-trunks bore marks of the conflict and a wide and terrible trail led wildly off to the deeper forest. "He takes it up. "All day he follows it. At night he camps and sleeps by his fire in comfort. By daybreak again he is swinging along on that trail. Its word is plain to him. At first it raged, that great shaggy creature, tall as an ox and slow, raged and fought and broke its teeth on the strange thing that bit to the bone with its relentless jaws, and tore along the white silence dragging its hindering ball, that, catching on bush and root, skinned down the flesh from the shining bone. And presently the wild trail narrowed to undisturbed snow, with naught save two great footprints, one after the other. With the cunning of a man, M'sieu, the tortured animal has gathered in its arms that chain and ball, and is walking upright. For another day and night the trapper follows this trail of tragedy and at their end he comes upon it. "Beside a boulder, where the snow is pushed away there lies a round heap of anguish, curled up, pinched nose flat on the snow and two ears laid lop to a vanquished head. It is still breathing, though the dull eyes open not at sound of the trapper, bold in his safety, who lifts his gun and ends it all. "A fine pelt,—save that the right foreleg is somewhat spoiled. "It lies there in that pile, M'sieu, and makes for wealth,—but to me it is no heartening sight. I have followed that trail to the deeper woods." The eyes of the woman were deep as wells, flickering with light, and the dark brows frowned down the slope. She had drawn her hands tight around her knees, so tight that each knuckle stood out white from the surrounding tan. The young man shut his open lips and drew in a breath that quivered. "Ma'amselle," he said huskily, "nowhere in the wide world is there another woman so deep of heart, so strong in tenderness. Never before have I seen that side of the trapping. To a man that is shut. It needs the soul of a woman to see behind those things. And, oh, Ma'amselle!" his voice fell low and trembling, "I have seen more,—the divinity within your spirit. May the good God make me worthy that you may speak so to me again. I would I might serve you,—with my life I would serve you, Ma'amselle, for I have seen no woman like you." He was on his feet, this young Marc Dupre, and the hot blood was coursing fast in his veins. The awakening was coming, though not for Maren Le Moyne. "May the time come when I may be a stone for your foot," he said swiftly. "I ask no better fate." Maren looked up at him and a wonderful tenderness spread on her face. "I think the time will come, M'sieu,—and, when it does, it will be worth while. I think it would be a lifting sight to see you in some great crisis, before some heavy test." "You do?" he said slowly; "you do, Ma'amselle? Then, by Heaven, it would!" "And some day I shall see it." They little knew, these two in their glowing youth, how true was that word, nor how tragic that sight would be. "And till then," said this wild youth of the forest, "until then may we be friends?" The head under the crimson cap was whirling. "Friends?" smiled Maken, and her voice was very gentle; "assuredly, M'sieu—I had destined you for that some time ago." As she turned away, her glance once more fell upon the long camp of the Assiniboines, and Marc Dupre faded from her mind. Not so with him, left sitting on the flat stone, the blood hot in his face and a sudden mist before his eyes. Her last words sang in his ears like the voice of many waters. He did not look after her,—there was something within that held him silent, staring at the waters of the river, now sparkling like a stream of diamonds in the risen sun, the lightness gone from him and a trembling loosed in his bosom. Within the big trading-room at the factory, seats had been placed, the chief and his headmen sat in a solemn circle, and McElroy, holding in his two hands the long calumet, stood in the centre of the small conclave. Very gravely he pointed the stem, clinking with its dangling ornaments, to east and west, to the heavens and to the earth, and then with a deft motion swung it around his head. "My brothers," he said, glancing around at the solemn visages of these his friends and people, "may the sun smile all day upon us together in peace." Wherewith he smoked a moment at the carven mouthpiece and handed the pipe to Quamenoka. With the utmost gravity Ridgar took it from the chief, passed it to the savage on his right, who likewise smoked and passed, it on, and presently the ceremony was done and the visit had begun. "My. "A runner of the Saulteurs, resting in the lodges of the Assiniboines, has told Quamenoka of their strange customs, their hardness, and their shut forts guarded with suspicion and sentinelled with fear." He ceased a moment and smoked in silence. No breath of sound broke the stillness, for this was ceremony and of great dignity. Only McElroy was acutely conscious of the figure in the doorway and the peering face of the girl, so full of hushed intensity. "Also do we bring word of a great tribe, the Nakonkirhirinons, living far beyond the River Oujuragatchousibi, who this year journey down to Fort de Seviere with many furs,—more than all that will come from the Assiniboines, the Crees, the Ojibways, and the Migichihilinons put together. "Past York and Churchill on the Great Bay they come, because of unfair dealings which met them at those places last year and the year before, down to the country of the Assiniboines, in whose lodges they will eat the great feast of the Peace Dance. Not long have the Nakonkirhirinons traded their furs, living to themselves in their hills, and much credit is due Quamenoka by whose word they come this year to his brothers on the Assiniboine." The chief paused impressively and raised his glance to the factor's face. McElroy nodded. "Greatly does the heart of thy brother rejoice at such word, and a present over and above that meant for him shall be given Quamenoka. Let the talk go on. We listen." But before the chief could speak again, Edmonton Ridgar had broken silence: "Negansahima is chief of that tribe and my Indian father, he having adopted me with all ceremony once when I sojourned a year among them. The sight of him will gladden my spirit." Swift surprise spread on the factor's face, but he did not speak. There was much in the checkered life of his friend that had not been set before him, and each revelation was full to the brim of romance, of daring, and of that excitement which attends a life spent in the wilderness. The Indian nodded and went on: "And last of the news of forest and lake and river is word of the meeting of canoes, the half of one-ten, laden with goods and going up the river, which passed but few suns back. A sun-man sat in the first, beautiful of face and with hair like light, who strove to barter. But the Assiniboines come to their brothers. They heeded not his words, though they were sweet with promise. I have spoken." The chief fell silent, for the year had been told, and McElroy spoke presently of his joy at their presence, their words, and their friendship, as was the custom of the H. B. Company's factors on such occasions; and Ridgar rose from the council to bid a young clerk, one Gifford, bring forth the presents for the guests,—a coat with coarse white lace and lining of vermilion, a hat of felt and a sash of many colours for Quamenoka, and lesser glories for his four headmen. These presented with due formality, and actually donned by the recipients without loss of time, the ceremony of the opening council was over, save for the triumphal march of the potentate, accompanied by McElroy and Ridgar, back to the camp on the river bank. As they passed out the factory door, they brushed by Maren Le Moyne, where she had drawn aside, still wistfully watching the comers from the wilderness. The young factor's eyes went to her face and for a moment held her glance. Instantly, with that deep look, the girl's hand shot forth and touched his arm, a light touch with the deftness of strength held in abeyance, and McElroy felt his flesh tingle beneath it. "M'sieu," she said, "where do they come from, how far in the west?" "Not far, Ma'amselle,—only from the Lower Saskatchewan. The Assiniboines are our nearest tribe, living along the country from the Hare Hills to the parting of the twin rivers above the Qui Appelle. Hold they interest for you?" "Nay," she said, shaking her black head, "not if they come not far, other than that excited by their strangeness. I thank you." She drew back, and McElroy, perforce, followed his way to the encampment, but he thought not this time of the red flower. Only within him was roused that same desire which had prompted De Courtenay to snatch the bloom from the stockade wall,—a longing to give her something, to offer homage to this tall young woman with the wondrous face of beauty and wistful strength. Since she was but a child had men who looked upon her felt this same longing, this stirring of the worshipper within. But few had dared the wall of quietness about her; therefore, she had remained apart. Only Prix Laroux of all those who had seen her grow into her magnificent womanhood at Grand Portage had come to her with his gift of faith and tied himself to hand for life, and he came not with the love of man but rather as one who follows a goddess. Yet it was that aching desire to serve her which sent him. And now it gripped the young factor of Fort de Seviere and he looked among the Assiniboines for a gift. Here a squaw held forth to him a garment that took his eye at once. Of doeskin it was, soft and white as a lady's hand, and cut after the fashion of the Indian woman's dress, in a single piece from throat to ankle, the sleeves straight from the shoulder, and at edge and seam, sewed with thorn and sinew, rippled and fluttered a heavy fringe the length of a man's hand. Across the breast there gleamed and glittered a solid plastron of the beadwork so justly famed for its beauty of colour and design, which came from the hands of none save the women of this tribe, and at hem and elbow, above the dangling fringe, there ran a heavy band of it. Above the hips there hung a belt made of the brilliant stained quills of the porcupine. The factor took the beautiful thing in his hands, and the purpose in his mind crystallised. In a swift moment he had bargained with the silent woman for a price that astonished her and was back within the post, walking hurriedly toward the cabin of the Baptistes. At the door Marie met him, her bright eyes sparkling with the honour of this visit of him who was the Law, the Head of De Seviere, and at her eager greeting the first abating of the flush within took hold upon him. He stood like a boy, the gorgeous garment hanging in his hand and the word on his lips forgotten. "Madame," he stammered, "I would—" and got no further. Sudden embarrassment took him and he grew angry with himself. What could he say, how dared he do what he had done? He could have thrown the white garment into the river in his sudden vexation. Factor of the post, he had made of himself a stammering youth, all for sake of the compelling beauty of a woman's eyes. But at that moment, while Marie stood blankly on the sill holding to the doorside and the silence grew unbearable, there was a step within the cabin and Maren Le Moyne came from the inner room. In one moment, so keen was the perception of her, she had seen the red blood in McElroy's face, the wonder on Marie's, and she, too, stood in the open door. "Ah, M'sieu!" she said quickly, "do some of them, by chance, come from the west?" The tone of her deep voice broke the spell, so subtly natural was it, and McElroy found his tongue. "No, Ma'amselle," he smiled, the ease coming back to his blue eyes, "but I have found something very beautiful among them which I wish you to have. It is more beautiful than a red flower." He held up to her the doeskin garment and his eyes were very anxious. For a moment Maren stared as she had stared at De Courtenay and a curious expression of perplexity spread on her face. Truly men were different here in this wilderness from those who lived at the Grand Portage, and for a moment she drew herself up and the straight brows began to frown. But as she had felt the whimsical charm of De Courtenay, so now she felt the eagerness, the taut anxiety of this man, and she noticed that there was no smile on his face as she hesitated. Moreover, Marie was watching, sharp as a little hawk. "Why, M'sieu," she said, and there was a baffling note to the voice this time, "why,—you wish me to have this?" "Yes, Ma'amselle," said McElroy simply. The girl stooped and took it from him, and for a moment her hand lay against his palm, a smooth warm hand. "And you wish me to wear it?" she asked. "If it shall please you." "Then it shall please me," she said quite easily, "and I thank you." McElroy turned away and walked back to the factory, and all the way he did not know what he had done. It had been an impulse, and he had rushed to its fulfilling without a thought. Had he bungled in giving her a garment where De Courtenay had played on a wind-harp in giving her a little red flower? He was hot and cold alternately, and the memory of that momentary frown came turn and turn with that of the gentle manner in which she had reached down for the lifted gift.. Unlike. Kept. "Verily, Marie, it is good to be here," sighed Micene Bordoux, sitting on her sill with her capable arms folded on her knees, and her eyes, cool and sane and tolerant, roving over the settlement lolling so quietly in the sun. "After the trail the rest is good, and yet I will be eager long before the year has passed to follow Maren,—may Mary give her grace!—into that wilderness which so draws at her heartstrings." "Oh, Micene!" cried Marie, a trifle vexed, "if only she might forget her dreams! What is it like, the heart of a maid, that turns from thought of love to that of these wild lands, to the mystery of the Whispering Hills that lie, the good God knows where, in that dim and untracked West! I would that Maren might love! Then would we have peace and stop forever at this pleasant place." Good Micene, with her brave heart and her whole-souled sense, smiled at Marie. "Love," she said,—"and think you THAT could turn that exalted spirit from its quest? Still the stir of conquest within her bosom, hush the call of that glorious country which we know from rumor, and. plain hearsay lies at the heart of the Athabasca? "Little do you know Maren, Marie, though the same mother gave you birth. There is naught that could turn the maid, and I love her for it. It is that undaunted faith, that steadfast purpose, that white fire in her face which holds at her heels the whole of us, that turns to her the faces of our men, as those legions of France turned to the Holy Maid. Love? She would turn not for it if she could not take it with her." Micene looked off across the cabins, and there was a warm light in her eyes. "Nay, Marie," she said, "make ready for the trail the coming spring, for we will surely go." It was this day, golden and sweet with little winds that wafted from the blossom-laden woods, that Maren Le Moyne, drawn by the dusky depths, passed, out the stockade gate, traversed slowly the length of the Indian camp, stopping here and there to hold out a hand to a frightened pappoose peeking from behind its mother's fringed leggings, to watch a moment at the cooking fires, to smile at a slim young boy brave in a checkered shirt, and entered the forest. From the door of the factory McElroy saw her go and the call of the spring suddenly became unbearable. With a word to Ridgar he stepped off the long log step and deliberately followed. The Irish blood within him lifted his head and sent his heart a- bounding, while the half-holy mysticism that came from the Scottish hills drew his glance upward to the blue sky arching above. A tumult surged in his breast and every pulse in his body leaped at thought of speech with her, and yet again a diffidence fell upon him that set him trembling. As the conqueror he went, pushing toward victory, yet humble in his ambition. He felt a mist in his eyes as he entered the high arched aisles, cool beneath their canopy of young green, and he looked eagerly here and there for sight of a tall form, upright, easy, plain in its dark garb. Along the river bank he went where he saw a footprint in the soft loam, and presently it turned deeper into the great woods and he swung forward into those depths whose sweetness had called him subtly for these many days. She was a strong traveller, that straight young creature of the open ways, and a full hour went swiftly before he caught the sight he wanted. At sight of her he halted and stood a moment in hushed joy, looking with eyes that knew their glory, for with every passing second Anders McElroy was learning that nowhere in all the world, as had said that flaming youth Marc Dupre, was there another woman like this Maren Le Moyne. She stood in a little glade, cool, high-canopied, where the sunlight came in little spots to play over the soft carpet of the pale forest grass thick-starred with frail white flowers, and her back was to a tree that towered to heaven in its height. At her sides her brown arms hung, palms out in an utter abandon of pleasure, while her lifted face, with its closed eyes, communed with the very Spirit of the Wild. Like some priestess she was, and McElroy felt an odd sensation of unworthiness sweep over him as he stood silent, his sober blue eyes on the beauty of her face. He cast swiftly back across his life. Was there anything there which might forbid him now, when he would go forward to so pure a thing as this maid, dreaming her dreams of prowess in the wilderness? Nay, he saw no unworthy deed, nothing to spoil the page of a commonplace life spent at his old father's side across the sea, nothing of the so common evils of the settlement. Within him there was that which thanked its Maker unashamed that he had kept himself from one or two temptations which had beset him in these stirring years of service on the fringes of the great country spreading from the bay. With that thought he went forward, and Maren did not hear his step on the soft grass, so far was she on her well-worn trail of dreams, until he stood near and the feeling of a presence finally brought back the wandering soul. Then she opened her eyes and they fell full upon the factor, his light head bared to the dancing sun-spots, his blue eyes sober and touched again with that anxiety which had compelled her to take his gift. There was no sudden start of fear, no little startled breath, for this woman was calm as the dreaming woods and as serene. "Bon jour, M'sieu," she said, and at sound of her voice, so deep and full of those sliding minors, McElroy felt her power sweep over him in a tumultuous flood. "Ma'amselle," he said, "Ma'amselle!" And in the next moment stopped, for the words of love were on his tongue and the wide dark eyes were looking at him wonderingly. "No longer could I withstand the call of the springtime and the woods," he finished falteringly; "the trading-room and the bargain were grown hateful to me in these warm days with the scent of flower and leaf and heated mould coming in at the door and bidding me come. I left my post, a traitor, Ma'amselle, betrayed by the forest. Too weak am I for courage when the big woods call." Maren looked at him and the light grew up in her eyes, that little flame that flickered and leaped and gave so baffling a charm to her beauty. "Ah!" she said softly; "you love it too, the great wilderness?" "Aye, most truly." "And you can hear the whisper of the far countries, the ripple of distant streams, the wind in the pines that have never sheltered a white man? You know these things, M'sieu?" She leaned forward from the great smooth-barked tree and looked at him eagerly. "They are what brought me over seas," he said quietly, "what sent me to De Seviere, what hold me to the tribes that come each year to my doors." Maren's lips were parted, the fire of her passion in her flaming face. "Then you know why I come to the woods, why I grieve that the spring is passing, why I can scarcely hold my soul in patience through this delay!" With the suddenness of her words her breath had leaped to a heaving tumult, the wide eyes, so calm, so cool, had filled first with fire and then with a mist. That clouded them like tears. "Oh, M'sieu!" she cried tensely; "know you of that country which lies far to the west and which the Indians call the Land of the Whispering Hills?" "Aye. It lies circling a great lake, blue as the summer skies, its waters forever rippled by the winds of the west which sing in the grassy vales and over the rounded knolls that stud the region,—a land of waving trees, of high coolness, or rich valleys thick with rank grasses and abounding with the pelt animals. It is the country of the Athabasca and from it came last year a band of the Chippewas heavily laden with furs. They told fine tales of its beauty. It is for that land you are bound?" "For that land, M'sieu," said Maren Le Moyne, and her lips trembled; "for that virgin goddess of the dreams of years! I have seen its hills, its waving grass, wind-blown, its leaping streams,—I have breathed the sweet air of its forests and gazed on its beauties since my early childhood, in dreams, always in dreams, M'sieu, until I could bear the strain no longer. And now, when it beckons almost within my reach, when its very breath seems in my nostrils, I must stop for a year's space! You know, M'sieu,—you comprehend?" She leaned forward looking earnestly into McElroy's eyes, and a surge of painful ecstasy shot to the man's heart, so near she seemed in the suddenly created sympathy of the moment, so near and gracious, so strong in her pure passion, so infinitely sweet. "I know," he said, and his voice sounded strange in his ears; "I know every pulse of your heart, Ma'amselle, every longing of your spirit, every pure thought of your mind,—for these many days I have trembled to every vibration that has touched or thrilled you. Oh, Ma'amselle!" With the surge of that overwhelming thing within him the young man had forgot all things,—that this girl was near a stranger, that he had quaked at his temerity of the gift, forgot all but that she leaned toward him with the mist in her wide eyes, and he strode forward the step between them, his arms reaching out instinctively to enfold her. With. CHAPTER IX GOLD FIRE If that time in the tuneful spring was crowded full to the brim of emotions scarce bearable to McElroy, how much more wonderful was it to Maren Le Moyne, for the first time in her life trembling in all her being from the touch of a man's lips? To the outward world there was no sign of the tumult within her as she came and went about the business of the new cabin by the stockade wall, but in her virgin heart there stirred strange new things that filled her calm eyes with wonder. In the seclusion of the little room to the east she spread out on the patchwork quilt the Indian garment and looked at it with a new meaning. Never before in her life had she thought of a man's eyes as she thought of McElroy's, thrilling to the very tips of her fingers at memory of the blue fire in them, and never before had she been conscious of anything as she was conscious of the flesh on her shoulders where his hands had rested, her lips sealed under the warm caress of his. Verily, there was nowhere another such man as this one who knew the longing of the wild as did she, whose heart responded to the same call of the great wilderness. Night and day she thought of him, and the memory of that day in the forest glade haunted her like a golden melody newly heard. Yet something within her held her back from his sight, kept her eyes from that part of the small settlement where stood the factory with its wide doorway. She could not bear to look upon him yet in the newness of this awakening. And McElroy, deep in the work of the trading, was eaten by a thousand qualms and torments. All those doubts that beset lovers tore at his heart and made of his days a nightmare. With the cooling of his exalted intoxication what time the touch of the girl's young body had fired him with all confidence, came a thousand condemnations for his blundering haste, his stupid boasting of conquest. To what depths of scorn might he not now be fallen in the mind of such a girl as Maren Le Moyne with her calm judgment; how far might he not be from the object of his longing! And the fact that he could catch no sight of her, no matter how often he stepped near the door nor how diligently he sought for a glimpse of the shining braids and plain garment among the women at the well, but added fuel to the fire that scorched him. But the times were getting very busy at Fort de Seviere. Before the Assiniboines were ready to depart back up the waterways down which they had come, their canoes laden with the wealth of the coming season, other flotillas were on the little waves of the river, other chiefs made their entrance up the main way of the post, and the goods of the Hudson's Bay Company went out in a stream as the priceless pelts came in. "Lad," said Edmonton Ridgar with that easy probing of the well-known friend, "there is something eating at your mind these days. The trade goes differently from that of last year. It is not so all-absorbing. I fear me that the Nor'westers, with their plundering and their tales of deportation, have entered a wedge of worry." "'Tis. Never before had the Nakonkirhirinons been so far in the south. And long before they reached Deer Lake word had been brought to that new venturer in his post on the Saskatchewan, Alfred de Courtenay, and he was keenly alert. About the same time a half-breed trapper came into Fort de Seviere, loud in his lamentations, and sought McElroy. From the flats south of the Capot River, where he had wintered amid a band of Blackfoot Indians, a rare thing for a white man, he had come laden with rich furs from that unopened country, bound for De Seviere, and on the banks of the Qui Appelle three men had come upon him who had shared his lonely campfire. Rollicking fellows they were, brawny of form and light of head, and they had carried much liquor in flasks in their leg-straps, which liquor flowed freely amid songs and fireglow. In the morning when he awoke late with, Mon Dieu! such a head! there were no three men, who had vanished like dreams of the liquor, likewise there was no well-strapped pack of fat winter beaver! The man, a French half-breed, whimpered and cursed in impotent wrath, and showed McElroy one of the flasks that had been in the leg-straps of his visitors. It was covered with a fine light wicker weave, of the same pattern as that jug which De Courtenay had left at the post gate that morning in early spring. "Ridgar," said the factor, showing the thing to him, "our friend from Montreal is taking a high hand with the country. The freedom of the wild has gone to his head." Indeed it seemed as though that were true, for the tales of the reckless doings of that post of the Nor'westers on the Saskatchewan over which De Courtenay presided became more frequent and always they were characterised by a wildness and folly that were only exceeded by their daring. The young adventurer had already made a headlong sally into the fringes of that country which came too near his Tom-Thumb garrison, and along which roving bands of the sullen Blackfeet trailed with a watching eye on the white men at the forts, and returned without two of those long curls of which he was so proud, a spear-head pinning them in the trunk of a tree which happened to form a convenient background. To add to the small resentment against him which began to rankle in McElroy's heart, and which had never really left it since that evening in De Seviere when Maren Le Moyne had passed behind the cabin of the Savilles with some voyageur's tot on her shoulder and the handsome gallant from Montreal had lost his manners staring, one day in this same week a Bois-Brules came to the post gates and asked for one Maren Le Moyne. He stood without and stubbornly refused to give his message, and at last McElroy himself went to the cabin of the Baptistes. He had not seen the girl since that day in the forest, and his heart beat to suffocation as he neared the open door and caught the sound of her voice singing a French love song. He stopped on the step, and for a moment his glance took in the interior: By a window to the north she stood at a table, its wooden surface soft and white as doeskin from water and stone, and prepared the meal for ash-cakes, her sleeves, as usual, rolled to her shoulder and the collar of her dress open at the throat. To the young factor's eyes she was a sight that weakened the knees beneath him and set him quaking with a new fear. He dared not speak and bring her gaze upon him, the memory of his boastful words in the forest was too poignant. But it needed not speech. Had he but known the wonder that had lived within her all these days he would have understood the force that presently stopped the song on her lips, as if her soul listened unconsciously for tangible knowledge of the presence it already felt near, that slowed her nimble brown fingers in the pan, that presently lifted her head and turned her face to him. Instantly a warm flush leaped up to the dark cheeks, and McElroy felt its answer in his own. "Ma'amselle," he stammered, far from that glib "Maren" of the glade, "there is one at the gate who demands speech of you." The words were commonplace enough and the girl did not get their import for the intensity of her gaze into the eyes whose blue fire had set her first wondering and then a-thrill with these strange emotions. "Eh, M'sieu?" she smiled, and McElroy, revived through all his being with that smile, repeated his message. She took her hands from the yellow meal and dusted them on a hempen towel, and was ready to go forth beside him. That short walk to the stockade gate was silent with the silence of shy new joy, and once the factor glanced sidewise at the drooped lashes above the dusky cheeks. "Had you expected any messenger, Ma'amselle?" he asked indifferently as they neared the portal with its fringe of peeping women and saw beyond them the tall figure of the Bois-Brule, his lank hair banded back by a red kerchief. "Nay, M'sieu," replied the girl, and went forward to stand in the gate. The messenger from the woods asked in good French if she were Maren Le Moyne, and being answered in the affirmative, he took from his hunting shirt a package wrapped in broad green leaves and placed it in her hands. The leaves were wilted with the heat of the man's body and came easily off in her fingers, disclosing a small square box cunningly made from birchbark and stained after the Indian fashion in brilliant colours. A tiny lid was fastened with a thong of braided grass. Wonderingly she slipped the little catch and lifted the cover. Inside upon a bed of dampened moss there lay a wee red flower, the exact counterpart of that one which Alfred de Courtenay had fastened in her hair that morning by the well. McElroy, at her shoulder, looked down upon it, and instantly the warmth in his heart cooled. When Maren looked up it was to find his eyes fixed on the messenger whose tall figure swung away up the river's bank toward the north forest, and they were coolly impersonal. She was unversed in the ways of men where a maid is concerned, this woman of the trail and portage, and she only knew vaguely that something had gone wrong with sight of the little flower. She?" With a gesture pathetically dramatic the little maid threw her hands across her heaving breast and gazed at McElroy with big eyes, starry in the dusk. Her emotion was genuine he could not help but see, even through his astonishment, and he stared at her with awaking sympathy. "Is there some one who is so much to you, little one?" he asked. "I thought there wasn't a youth in the post—no, nor in any other this side the Red River-who did not pay homage to France Moline's little daughter. Who is of such poor taste? Tell me, and what I can do I will do to remedy the evil." He was smiling at the little maid's pretty daring in coming straight to the very head of De Seviere with her trouble, and he reached out a hand to draw her down on the step beside him. There was never a woman in distress who did not pull at the strings of his heart, and he longed to soothe her, even while he smiled to himself at her childishness. But Francette was not so childish, and he was one day to marvel at her artless skill. At the touch of his hand she came down, not upon the step beside him as he meant, but upon her knees before him, with her two little hands upon his knees and her face of elfin beauty upheld to him in the starlight. "Oh, M'sieu, there is one who is so much,—oui, even more than all the world, more than life itself,—more than heaven or hell, for whose sake I would die a thousand deaths! One at whose feet I worship, scorning all those youths of the settlement and the posts. See, M'sieu," she leaned forward so close that the fragrance of her curls blew into the man's nostrils and he could see that the little face was pale with a passion that caused him wonder; "see! Today came one from the forest bringing love's message to that tall woman of Grand Portage,—the little red flower in the birchbark case. It spoke its tale and she knew,"—subtle Francette!—"she knew its meaning by the eye of love itself. So would I, who have no words and am a woman, send my message by a flower." The hands on the factor's knees were trembling with a rigour that shook the whole small form before him. "See, M'sieu!" she cried, with the sudden sound of tears in the low voice; "read the heart of the little Francette!" She took from her bosom a fragile object and laid it in his palm, then clasped her hands over her face and bowed until the little head with its running curls was low to the log step. McElroy strained his eyes to see what he held. It was a dried spray of the blossoms of the saskatoon. For a moment he sat in stupid wonder. Then swiftly, more by intuition and that strange sense which recalls a previous happening by a touch, or a smell, than by actual memory, he saw that golden morning when he had stopped by the Molines' cabin and watched the great husky balance on his shaky legs. He had twirled in his fingers the first little spray of the saskatoon, brought in by Henri Corlier to show how the woods were answering the call of the spring. "Why," he said, astounded beyond measure, "why, Francette,—little one, what does this mean?" But Francette had lost her tongue and there was no answer from the bowed figure at his knees. He put out a hand and laid it on her shoulder and it was shaken with sobs,—the sobs of a woman who has cast her all on the throw of the die and in a panic would have it back. Off in the forest a night bird called to its mate and the squeaky fiddle whined dolorously and a profound pity began to well in the factor's heart. She was such a little maid, such a childish thing, a veritable creature of the sunlight, like those great golden butterflies that danced in the flowered glades of the woods, and she had brought her one great gift to him unasked. Some thought of Maren Le Moyne and of that reckless cavalier with his curls and his red flowers crept into his voice and made it wondrously tender with sympathy. "Sh, little one," he comforted, as he had comforted that day on the river bank when she had wept over Loup; "come up and let us talk of this." He lifted her as one would lift a child and strove to raise the weeping eyes from the shelter of her hands, but the small head drooped toward him so near that it was but a step until it lay in the shelter of his shoulder, and he was rocking a bit, unconsciously, as the sobbing grew less pitiful. "Sh-sh-little one," he said gently; "sh—sh." Meanwhile Maren Le Moyne sat in the doorway of her sister's cabin with her chin on her hands and stared into the night. Marie and Henri were at the cabin of the Bordoux, laughing and chattering in the gay abandon of youth. She could hear their snatches of songs, their quips and laughter rising now and again in shrill gusts. Also the wailing fiddle seemed a part of the warm night, and the bird that called in the forest. All the little homely things of the post and the woods crept into her heart, that seemed to her to be opening to a vague knowledge, to be looking down sweet vistas of which she had never dreamed among her other dreams of forest and lake and plain, and, at each distant focus where appeared a new glory of light, there was always the figure of the young factor with his anxious eyes. Strange new thrills raced hotly through her heart and dyed her cheeks in the darkness. She tingled from head to foot at the memory of that day in the glade, and for the first time in her life she read the love-signs in a man. That change in his eyes when he had looked upon De Courtenay's red flower was jealousy. With the thought came a greater fulness of the unexplainable joy that had flooded her all these days. Aye, verily, that red flower had caused him pain,—him,—with his laughing blue eyes and his fair head tilted back ever ready for mirth, with his tender mouth and his strong hands. The very thought of that killed the joy of the other. If love was jealousy, and jealousy was pain, the one must be healed for sake of the other. With this girl to think was to do, and with that last discovery she was upon her feet, straight and lithe as a young animal beside the door. She would go to this man and tell him that the red flower was less than nothing to her, its giver less than it. At that moment a figure came out of the dusk and stopped before her. It was her leader, Prix Laroux, silent, a shadow of the shadows. "Maren," he said, in that deep confidence of trusted friends, "Maren, is all well with you?" "All is well, Prix," said the girl, her voice tremulous with pleasure, "most assuredly. Thought you aught was wrong?" "Nay,—only I felt the desire to know." "Friend," said Maren, reaching out a hand which the man took strongly in both his own; "good, good friend! Ever you are at my back." "Where you may easily reach me when you will." "I know. 'Tis you alone have made possible the long trail. Ah! how long until another spring?" But, when Prix had lounged away into the dusk and the girl had stepped into the soft dust of the roadway, she fell to wondering how it was that mention of the year's wait brought no longer its impatience, its old dissatisfaction. She was thinking of this as she neared the factory, her light tread muffled in the dust. "Foolish Francette! What should I do with a gay little girl like you? Play in the sunshine years yet, little one, and think not of the bonds and cares of marriage. How could these little hands lift the heavy kettles, wash the blankets, and do the thousand tasks of a household? You are mistaken, child. It is not love you feel, but the changing fancies of maidenhood. Play in the sun with Loup and wait for the real prince. He will come some day with great beauty and you will give no more thought to me. He must be young, little one, a youth of twenty; not one like me, nearer the mark of another decade. It would not be fitting. Youth to youth, and those of a riper age to each other." He was thinking of a tall form, full and round with womanhood, whose eyes held knowledge of the earth, and yet, had he been able to define their charm, were younger even than Francette's. The little maid had ceased her weeping long since and the face on McElroy's shoulder, turned out toward the night, was drawn and hard. The black eyes were no longer starry with passion, but glittering with failure. And the man, stupid and good of heart as are all men of his type, congratulated himself that he had talked the nonsense out of her little head. Suddenly he felt the slender figure shiver in his arms and the curly head brushed his cheek as she raised her face. "Aye, M'sieu," she whispered, "it is as you say, but only one thing remains. Kiss me, M'sieu, and I go to—forget." The factor hesitated. He felt again his one passionate avowal on the lips of his one woman. This was against the grain. "Please, M'sieu," begged the childish voice, with a world of coaxing; and, thinking to finish his gentle cure, he bent his head and kissed her lightly on the cheek. "And now—" he started to admonish, when she threw her arms about his neck, stiffling the words in her garments.. There. "Let it be, Marc Dupre," as the youth dropped his and from Maren's arm. "Ma'amselle does not object,—a trapper or a cavalier, all are fish to Ma'amselle's net. Mon Dieu! If all were so attractive as Ma'amselle!" The little maid sighed in exaggerated dolour. Dupre flashed round on his moccasined heel and reached her in a stride. "Aha! It is you, by all the saints!" he said beneath his breath, as he took her none too gently by the shoulder. "I know your tricks." Aloud he said, "Francette, children should keep from where they are not wanted. Get you back to your mother." "Children, you say, M'sieu Dupre? Is eighteen so far behind twenty-two? Grow a beard on your cheek before you give yourself the airs of a man. And, anyway, grown men of twice eighteen have been known to love children of that age." It was a dagger thrust, and it found its mark even as the girl glanced slily at her victim. Maren's full mouth twitched and she looked dully away to the fort gate. Dupre gave Francette an ungallant push. "Begone!" he cried angrily; "you little cat!" With a ringing laugh the maid danced away in the sunshine, and Dupre faced Maren. "It is that imp of le diable, Francette?" he asked. "What has she done to you, Ma'amselle?" But Maren shook her head. "The maid is not to blame. She is but a child in spirit and what le bon Dieu has seen fit to give her has gone to her head. That is all, save as your quick eye has detected, M'sieu, I have received a heavy hurt." Suddenly, with that whimsical youthfulness of soul which glimmered at times through her apparent strength, she looked at Dupre with a sort of fright. "Merci, M'sieu! For what reason does the good God let some things befall? ...But I have still a stone. Throughout I will remember that." In a moment she was gone, walking toward the cabin of Micene Bordoux, and Marc Dupre went on his quest of Pierre, wondering and all a-tremble with pity and thought of that promise. Where Marc, with the revelation of adoration, had seen sharply, Micene with her good sense felt vaguely that something was wrong with the intrepid leader of the long trail. "Maren," she said this day, as she took the bread pan which had been borrowed, "I fear there is something troubling you. Is there bad news from Athabasca?" Always there lay behind Maren's eagerness a fear, sleeping like a hidden fawn but ever ready to quiver into life, a fear of news from the Whispering Hills, news that should make the promise of the trail a sudden void. "Nay, Micene," smiled Maren, "these latest Indians come from the south." "And all is well with the plans?" The vague uneasiness was not stilled in Micene. "All is well with the plans. There is not a year now." The girl looked straight in her friend's eyes without a trace of the dazed misery which Marc Dupre had surprised in her own. Mic. A lump rose in his throat as he caught the outline of the braided head bowed lower than he had ever seen it, saw the whole attitude of the strong figure, every line relaxed as if in a great weariness. "Maren," he said, with the wonder of love in his voice, "Maren—my maid!" And he strode forward swiftly, stooped, and laid his hand on her shoulder. With a jerk the drooped head came up. She drew from his touch as if it burned her. "If you please, M'sieu," she said coldly, "go away." McElroy sprang back. "What? Go away! You wish that,—Ma'amselle?" The tone more than the words drove out of him all daring of her sweet name, took away in a flash all the personal. "Of a surety,—go away." The factor stood a moment in amazed silence. Did the red flower mean so much to her, then? Had she accepted its message? And yet he knew in his heart that the look in her eyes, the smile on her lips had told their own tale of awakening to his touch. What but the red flower in its birchbark case had wrought the change? He thought swiftly of De Courtenay's beauty, of his sparkling grace, his braided blue coat, his wide hat, and the long golden curls sweeping his shoulder. Truly a figure to turn a woman's head. But within him there rose a tide of rage, blind vent of the hurt of love, that boded ill for the dashing Nor'wester on the Saskatchewan. Sick to the very bottom of his heart, he bowed ever so slightly to the tense figure on the step and strode away in the shadows. So! Thus ended his one love. For this he had kept himself from the common lot of the factors in their lonely posts; for this he had never looked with aught save friendly compassion upon the maids of the settlements, the half breed girls of the wilderness, the wild daughters of the forest. Waiting for this one princess in his small kingdom, he had thrown himself on the out-bearing tide of love only to be stranded on some barren beach, to see her taken from him by some reckless courtier not fit to touch a woman's hand! Thus they turned apart, these two meant for each other from the beginning, and in each love worked its will of pain. Maren on the step stared dry-eyed into the night, uncomprehending, unrebelling, and McElroy strode ahead, blind with sudden anguish, scarce knowing which way his steps tended. And, like a ghoul behind a stone, a small dark face peeped keenly from a corner. Francette was watching her leaven work. CHAPTER XII THE NAKONKIRHIRINONS In the week that followed the waters of the Assiniboine grew black with myriads of canoes. Like the leaves in fall, truly, they came drifting out of the forest, long slim craft, made with a wondrous cunning of birchbark peeled from the tree in one piece, fitted to frames of ash fragile as cockleshell and strong as steel under the practised hand, and smeared in every crinkle and crease and crevasse with the resinous gum of the pine tree. By scores and hundreds and battalions, it seemed to the traders at De Seviere, they poured out of the wilderness, choking the river with their numbers, spilling their contents on the slope under the bastioned walls until a camp was made so vast that it stretched into the forest on each side the clearing of the post and even extended to the marsh at the south. Half-naked braves stalked in countless numbers among the tepees that went rapidly up, tall fellows, mighty of build and fearless of carriage and of eagle eye, aloof, suspicious, watching the fort, guarding the rich piles of peltry and exchanging a word with none. These were the great Nakonkirhirinons from that limitless region of the Pays Ten d'en Haut. If McElroy's heart had not been so full of his own trouble he would have exulted mightily in their coming, for did it not prove one failure for that reckless Nor'wester on the Saskatchewan? They had come, past all his blandishments of trade, to Fort de Seviere, and their coming spelled a number of furs this season far in advance of any other for that small post. If he wondered at first how they had held out against De Courtenay it was all made plain when among the strangers he espied many Assiniboines and saw in the great canoe of the chief Negansahima, old Quamenoka, who had boasted of the coming of this tribe to De Seviere as his work. He had spoken truly and had evidently made his word good by meeting the approaching columns and returning with them. To him alone was due the failure of De Courtenay, McElroy felt at once, and determined in his mind on that present which he had promised for this zeal. With the coming of the strangers Fort de Seviere was put under military rule. The half-moon to the right of thegate, with its small cannon, received a quota of menwho strayed carelessly all day within reach of the low rampart; a guard lounged in the great gate, ready at a moment's notice to clang it shut, and seemingly matter-of-course precautions were taken throughout, for these Indians were as uncertain as the flickering north lights crackling in a frosty sky. There was a scene not to be likened to any other outside the region of the Hudson Bay country, where strange relations existed between white trader and savage, when Edmonton Ridgar met the canoe of the chief at the landing. Savage delight overspread the eagle features of Negansahima as he beheld the white man. Towering mightily in the prow of his canoe, the sweeping head-dress of feathers crowning him with a certain majesty, he fixed his keen glance on Ridgar and came gliding toward him across the rippled water. As the canoe cut cleanly up and stopped just short of scraping on the stones at the edge, obeying the paddles like a thoroughbred the bit, the chief trader of De Seviere stepped forward and held out his arms. "Who art thou?" he called. Deep and guttural as thunder from the broad chest, naked under the lines of elk teeth, came the reply, "Thy father" "And master of my goods. The heart of thy son melts as the snow in spring. Wiskendjac has sent thee." McElroy, standing near, saw the face of his friend illumined with a real affection as the savage landed and, contrary to the custom of the Indians in the lower country, embraced with every sign of joy the lean white man whose skin was nearly as dark as his own and whose greying temples bespoke almost a as many years as the chief's black locks could boast. In the eyes of both, as they regarded each other, were memories known to no one else. McElroy wondered what they were and what that year, of which Ridgar had spoken only once, had held. The trader spoke their tongue as easily as he spoke any other that came to the post, naturally and with quiet fluency. So deep was the apparent pleasure of the meeting that, when the interpreting was done and the ceremonies over, Ridgar went with the Indian among the tepees and no more did McElroy see him until he came to the factory at dusk. "Mother of Heaven!" he ejaculated, flinging himself down at the table in the living-room where Rette's strong coffee tempted the nostril; "such furs! Beaver in countless packs, all the fat winter skins, no Bordeaux, no Mittain. Fox, also of the best only,—black fox, fine and shining, fox of those far-north regions where they hunt beyond the sun, white as the snow it runs on, and Mon Dieu, McElroy! Seven silvers as I hope for salvation! Verily are they a prize beyond price, these Indians that have come in to us, and I fancy that young Nor'wester is swearing at his luck in losing them. Old Quamenoka struts as if their wealth belonged to his meek Assiniboines.... But the furs! Ermine and nekik and sakwasew and wapistan, all the little fellows that, taken from those virgin north lands, are worth their weight in gold! Nowhere have I seen a common pelt. They are connoisseurs, these wild Nakonkirhirinons, and they carry a king's ransom in their long canoes. White bear and brown arctic wolf and everywhere the best of its kind! To-morrow's trade will be worth while—but keep the guns in evidence and quiet above all things." "Ah!" said McElroy, "what is there to fear, think you? Is not the chief bound to you by all ties of ceremony and regard?" "Most assuredly," returned Ridgar quietly, "but those young braves are strung like a singing wire and swift as a girl to take suspicious fright; and there are somewhere near five hundred of them, as near as I can make out from the numbers seething among the lodges. They are in a strange country and watching every leaf and shadow." Thus the sun went down on De Seviere, with the eager maids and women passing and repassing near the gate to peep out at the rustling throng, at the tepees with their fine skin coverings painted with all the wonders of battle and the chase, at the comely squaws and maidens, the chubby brown children, the dogs snarling arid savage, for they had full complement of the grey northern huskies. To a woman they peeped at the gate from all the cabins of the post, save only that one who had been most eager before when the Indians came, Maren Le Moyne, sitting in idle apathy on her sister's doorstep. "Ma'amselle," said Marc Dupre, stopping hesitant before her, "have you seen the Nakonkirhirinons?" "Nay," she said listlessly, "I care not, M'sieu." And the youth went gloomily away. "Something there is which preys on her like the blood-sucker on the rabbit's throat. But what? Holy Mother, what?" His handsome eyes were troubled. By dawn on the following day the trading had begun. Up the main way passed a line of braves, each laden with his winter's catch of furs, to barter at the trading-room, haggle with the clerks by sign and pantomime, and pass down again with gun and hatchet and axe, kettle and bright blanket, beads, and, most eagerly sought of all, yards of crimson cloth. There was babble of chatter among the squaws, shrill laughter, and comparison of purchases. In the trading-room sat the chief with his headmen and old Quamenoka of the Assiniboines, smoking gravely many pipes and listening to the trading. Like some wild eagle of the peaks brought down to earth he seemed, ever alert and watchful behind his stately silence. For two days the trading progressed finely, and McElroy had so far laid aside his doubts as to take delight in the quality of the rare furs. Never before had such pelts stacked themselves in the sorting-room. It was a sight for eyes tired by many springs of common trade. Then, like a bomb in a peaceful city, came a running word of excitement. The Nor'wester from the Saskatchewan was among the Nakonkirhirinons! Was at the very gates of De Seviere! When Pierre Garcon brought the news, McElroy flushed darkly to his fair hair and went on with his work. This was unbearable insolence. "An', M'sieu," pursued Pierre, "not only the man from Montreal, but, like the treacherous dog he is, among the Nor'westers is that vagabond Bois DesCaut." "Turncoat?" said the factor. "Aye." True enough. When McElroy, after trading hours, strolled down to the gate between the bastions, whom should he behold but the hulking figure of his erstwhile trapper, sulky of appearance, shifty eyes flitting everywhere but toward his old factor. And farther down the bank, among a group of warriors, a brown baby on his shoulder and his long curls shining in the sunset, was that incomparable adventurer, Alfred de Courtenay. Apparently. For. Then. She was conscious only of a giant form lurching, red-eyed and yelling, out of the turmoil, of brown hands that clutched her arms, and of another form which shot past her. For the second time in a few moments one man had reached for her and another flung himself to her rescue. She saw the Indian reel back with a red line spurting across his eyes, felt herself lifted and flung across a shoulder, and knew that the gate behind was swinging open. The next instant she slid down to her feet with her face in the buckskin shirt of Marc Dupre, who leaned shaking against the stockade wall and held her in a grip like steel, while Henri Corlier shot the bolts into place. Huddled in white groups were the women, some of them already raising their voices in weeping, others silent with the training of the women of the wilderness. The men faced each other with lips drawn tight and breath that came swiftly. Prix Laroux, his dark eyes cool and sharp, looked swiftly over the populace as they stood, for with that first shot every man in Fort de Seviere had rushed to the gate, and in that first moment of getting breath he calculated their strength and their ability. A leader born himself, he was looking for a leader among McElroy's men; but, with that intrepid factor himself gone and Edmonton Ridgar also, there was nowhere a man with the signs of leadership upon him. Through Prix's mind this went while they stood listening to the death- wail that was beginning to rise from the tepees without. Then he quietly took command, knowing himself to be best fitted. "Corlier," he said quietly, "leave the gate to Cif Bordoux. Take one man and get to the southwest bastion. You, Gifford," turning to that young clerk who worked in the sorting-room, "man the northwest. Garcon and Dupre will take the forward two. The rest will stand ready with guns and ammunition along the four walls and at the gates. We know not what will transpire." As if their factor spoke, the men of De Seviere turned to obey, feeling that strange compelling which causes men to follow one man to death on the field of battle, and which is surely the gift of God. Out of his shaking arms Marc Dupre loosed Maren, the trembling lessening as the danger passed. That sight of the defenceless girl among the Indians had shaken him like a leaf in the wind, had nerved his arms with iron, had worked in him both with strength and weakness. Now he looked into her eyes and said never a word, for once again he saw that they were dazed and void of knowledge. As he set her upon her own strength, she swayed. Her eyes went round the hushed groups of faces with wild searching. At last they found the face of her leader, and clung there, dark and dull. "Prix!" she cried. "Prix! Open the gate!" "I cannot, Maren," he said quietly; "'twould be but madness." "But they are without!" All horror was in the cry. "They are among the Indians!" "Aye,—and may the good God have mercy on them!" Laroux hastily made the sign of the cross. "We must guard the post, Maren." "But—" She turned her eyes slowly around from face to face and not a woman there but read her secret plain, the open script of love,—but for which man? "But-they-will—be—" She did not finish the sentence, staring at Laroux. Once she moistened her lips. "They will—Prix,—as I am your leader, open that gate!" With sudden reviving the daze went out of her features and the old light came back to her eyes, the far-seeing, undaunted light that had beaconed the long way from Grand Portage. She was every inch the leader again, tall, straight against the logs, her brown arm pointing imperiously to the closed gate. "Open, I say!" For a moment Laroux faced her squarely, the man who had tied himself to her hand, pledged himself to forge the way to the Whispering Hills, who followed her compelling leadership as these lesser men had turned to follow his but now. Then he set his will to hers. "I will not," he said quietly. With no more words she flung herself upon the gate and tore at the chains, her strong hands able as a man's. As the sight of her in peril had worked for both weakness and strength in Dupre, so had McElroy's plight affected her. That helpless moment was the one defection of her dauntless life. Now again she was herself, reaching for the thing of the moment, and the roar outside the palisade, constantly rising in volume, in menace and savagery, brushed out of her brain every cloud of shock. Laroux caught her from behind, pinioning her arms. "Maren," he said quietly, "hear me. Out there are five hundred warriors wild as the heart of the Pays d'en Haut, howling over the body of their dying chief. What would be the opening of the gate but the massacre of all within? Could forty men take the factor from them? There would be but as many more scalps on their belts as there are heads within the post. See you not, Maren?" In his iron grip the girl stood still, breathing heavily. As he ceased speaking a great sigh came from her lips, a sigh like a sob. "Aye," she said brokenly, "I see,—I see! Mary Mother! Let me go, Prix. I see." Laroux loosed her, knowing that the moment was past, and went at once about his duties of throwing the post into a state of defence. Once more strong and quiet, Maren went to the cabin by the gate. Here Marie knelt at her bed with a crucifix grasped in her shaking hands, her face white as milk and prayers on her trembling lips. "Maren!" she gasped, with the child's appeal to the stronger nature. "Oh, Maren, what will befall? For love of God, what will befall?" "Hush, Marie," answered Maren; "'tis but a tragedy of the wild. Naught will befall us of the post." "But those without? What is that roaring of many throats? Little Jean Bleaureau but now ran past crying that the Nakonkirhirinons were killing the factor" "No!" Marie jumped at the word like one shot, so wild and sudden it was. "No! No! Not yet!" Even in the stress of the moment Marie stared open-mouthed at her sister. "Holy Mother! It is love,—that cry! You love the factor!" "Hush!" whispered Maren, dry-lipped. The roar from the river bank had sharpened itself into one point of utterance which pierced the calm heavens in a mingling of native speech, French and broken English from Nakonkirhirinon and halfbreed, and, worse than both, dissolute "white Indian," and its burden was, "A skin for a skin!" CHAPTER XIV FELLOW CAPTIVES After that tense moment of hush following the shot, McElroy had no distinct recollection of what occurred. He was conscious of a sickening knowledge of Negansahima with his banded brown arms stretching into the evening light, of the tepees, of the river beyond, of the face of Edmonton Ridgar, and of all these etched distinctly in that effect of sun and shade which picks out each smallest detail sometimes of a rare evening in early summer. Then the whole scene went out in a smother as an avalanche of bodies descended upon him. He could smell the heavy odour of flesh half-naked, the scent of the hidden paint, he felt arms that fought to grip him and fingers that clutched like talons. Under it all he went down in the grass of the slope, fighting with all his strength, but powerless as a gnat in a pond. Above the turmoil of cries and guttural yells, even while he felt himself crushed at the bottom of that boiling mass, he heard the light voice of De Courtenay ringing clear in his whimsical farewell to Maren Le Moyne. Then he was wrenched up through the mass, something struck him on the head with a sharp blow, a shower of stars fell like a cataract, and the sickening scents in his nostrils faded away. When he again opened his eyes it was to behold real stars shining down from a velvet sky, to hear the river lapping gently at the landing, and the night birds calling in the forest. From the prairie beyond the fringe of woods to the east there came the yapping of the coyotes, and far to the north a wolf howled. At first a sense of bewilderment held him. Then in a rush came back the memory of what had happened. He listened intently. Back and forth, back and forth somewhere near went a soft footstep, the swish and glide of a moccasin. He strained his eyes, which smarted terribly, into the darkness, and presently descried a tall form pacing slowly up against the skyline of his vision and back again into the shadows. A single feather slanted against the stars. A guard pacing the place of captives. With a slight movement McElroy tried to lift a hand. It was immovable. He tried the other. It likewise refused his will. So with both feet when he attempted, ever so cautiously, to move them. He was bound hand and foot, and with cruel tightness, for with that tiny slipping of his muscles there set up all through him such a tingling and aching as was almost unbearable. His head seemed a lump of lead, glued to whatever it lay upon, and big as a buttertub. Turning his eyes far as he could to the right, he looked long in that direction. Faintly, after a while, he picked out the straight line of the stockade top, the rising tower at the corner. The line of the wall faded out in darkness the other way, strain as he might. To the left were the ragged tops of the tepees, their two longer sticks pointing above the others. From the sound of the river, he must be between it and the stockade gate. Presently his numbed hearing became conscious of a sound somewhere near, a sound that had rung so ceaselessly since his waking that it had seemed the background for the lesser noise of the sentry's slipping moccasin. It was the weird, unending, unbeginning wail of the women, the death-song of the tribe mourning the passing of a chief, the voices of some four hundred squaws blending indescribably. McElroy listened. With consciousness of that his mind grew clearer and he began to think. What a fool he had been! Once more had he played like an unbalanced boy at the game of love. What right had he to strike De Courtenay for kissing the woman whom he had won with his red flowers and his curls before the populace? That he himself had fancied for a brief space that she was his was no excuse for plunging like a boy at his rival's throat. If he had held his peace, all would be well now and the old chief would not be lying stiff and stark somewhere in the shadowed camp, the women wailing without fires. It was no balm to his sore heart that he in his blundering wrath had wrought this fresh disaster. And his post, De Seviere, which he had won by daring service and loyalty to the H. B. C., what would become of it? Who after him would rule on the Assiniboine? For well he knew that death, and death thrice,—aye, a million times refined,—awaited so luckless a victim as he whose hand had killed the great chief. But he had not killed Negansahima. It was the gun in De Courtenay's hand. Ah, De Courtenay! Where was De Courtenay? A captive assuredly, if he was one. They had both gone down together under the foam of that angry human sea. And, if he was here, his antagonist must be somewhere near. With exquisite torture, McElroy slowly turned his head to right and left. At the second motion his face brushed something close against his shoulder. It was cloth, a rough surface corrugated and encrusted with ridges,—what but the braid on the blue coat of the Montreal gallant! There was no start, no answering movement at his touch. The rough surface seemed strangely set and still. He lay silent and thought a moment with strange feelings of new horror surging through him. Was De Courtenay dead? Or was it by chance a stone under the braided coat, a hillock where it had been thrown? That strange feeling of starkness never belonged to a human body soft with the pulse of life.. With dreary insistence his sore heart brought up each sweet memory, each thrill of joy of those warm days. He saw every flush on her open face, every droop of her eyes. Again he saw the white fire in her features that day in the forest glade when she spoke of the Land of the Whispering Hills. He pondered for the first time, lying bound and helpless among savages, of that unbending thing within her which drove her into the wilderness with such resistless force. Granted that she had loved him as he thought during that delirious short space of time, would love have been stronger than that force, or would it have been sacrificed? She was so strong, this strange girl of the long trail, so strong for all things gentle, so unmoving from the way of tenderness. Proving that came the picture of the tot on her shoulder. "dipping as the ships at sea, ma cherie," and the look of her face transfigured. And yet home for her was "the blue sky above, the wind in the pine- tops, the sound of water lapping at the prow of a canoe." So she had said on that last day they spoke together in happiness, passing in diffident joy to the gate to meet De Courtenay's fateful messenger. Of all women in the vast world she was the one woman. There was never another face with that strange allurement, that baffling light of strength and tenderness. Sore, sore, indeed, was the heart of the young factor of Fort de Seviere as he lay under the stars and listened to the death-wail in the darkened camp. Nowhere was there a fire. Desolation sat upon the Nakonkirhirinons. Along toward dawn, presaged by the westward wheeling of the big stars, tom-toms began to beat throughout the maze of lodges. They beat oddly into the air, cold with the chill of the coming day, McElroy's thoughts had left the great country of the Hudson Bay and travelled back along the winding waterways, across the lakes, and at last out on that heaving sea which bore away from his homeland. Once more he had been in the smoke of London town, had looked into the loving eyes of his mother and gripped the hand of his tradesman father. Once more he had wondered what the future held. The sudden striking up of the tom-toms answered him. This. This was to be the end of his eager advance in the Company's favour, the end of that good glass of life whose red draught he had drunk with wholesome joy, the end of love that had but dawned for him to sink into aching darkness. He sighed wearily. So poignant was his sense of loss and the pain of it that the end was a weariness rather than a new pain. The thing that hurt was the fact that he himself had juggled the cards of fate to this sorry dealing. The sudden rage concerning De Courtenay had spent itself. There remained only the deep anger of the man who has lost in the game of love. And yet, what right had he to cherish even this wholesome anger against his rival when the maid had chosen of her own free will? As well hold grudge to the great Power whose wisdom had given the man such marvellous beauty. As he lay in the darkness listening to the unearthly noises he worked it all out with justice. He alone was to blame for the sorry state of things. De Courtenay was but a man, and what man, looking upon Maren Le Moyne, could fail to love her? Therefore, he freed his rival of all blame. And Maren,—oh, blameless as the winds of heaven was Maren! What had she given him that he could construe as love? Only a look, a blush to her cheek, the touch of a warm hand. In his folly he had hailed himself king of her affections when perchance it was but the kindliness of her womanly heart. And what maid could be blind to De Courtenay's sparkling grace,— compared to which he was himself a blundering yokel? Thus in bound darkness he reasoned it all out and strove to wash away the anger from his heart. And presently there came dawn. First a cold air blowing out of the forest, and then a deeper darkness that presently gave way to faint, shadowy light. Here and there tall figures came looming, ghostly-fashion, out of chaos, to take slow shape and form, to resolve themselves into tapering lodges, into hunched and huddled groups. And with light came action. McElroy saw that around the central lodge before the gate there was a solid pack of prostrate Indians covering the ground like a cloth, and from this centre came the tom-toms and the wailing. It was the lodge of the chief and within lay the stark body of the murdered Negansahima. As the faint light grew, one by one the warriors rose out of the mass like smoke spirals, drawing away to disappear among the tepees. Soon there came the sound of falling poles and McElroy knew that they were striking the camp. For what? Why, surely, for one thing. A chief must go to the great Hunting Ground from his own country; in his own country must his bones seek rest. They would journey back up the long and difficult trail down which they had just come to that vague region from which they hailed. But. The swish of the moccasined feet was as the sound of many waters. "No time for play," thought McElroy; "that will come later,—when we have reached the Pays d'en Haut." For he knew now that he and De Courtenay were to be taken along. The body of Negansahima was placed in the first canoe, covered with a priceless robe of six silver foxskins laced together; the six big warriors, their halfnaked bodies painted black, manned the paddles, and at the prow there stood the sad figure of Edmonton Ridgar. At one side had drawn out old Quamenoka and his Assiniboines, their way lying to the west. They raised a chant as the first canoe circled out and headed down the stream. Behind it fell in five canoe-loads of Bois- Brules, their attachment a mystery, and the river became alive with the great flotilla. Not until the death-boat had passed the far bend did the pacing Indian give way to a dozen naked giants, who lifted the captives with ceremony and carried them down the slope. As he swung between his captors McElroy looked back at the closed gates of De Seviere and a sharp pain struck at his heart, a childish hurt that the post he had loved should watch his exit from the light of life with unmoved front. It seemed almost that the bastioned wall was sensate, as if the small portholes here and there were living eyes, cold and hard with indifference, nay, even a-glitter with selfishness. But quick on the sense of hurt came the knowledge which is part of every man in the wilderness; and he knew well that every face in the little fort was drawn with the tragedy, that from those blank portholes looked human eyes, sick with the thing they could not avert, that whoever had taken charge within was only working for the safety of the greatest number, and with the thought his weakness passed. Only one more pang assailed him. He gave one swift thought to Maren Le Moyne. Where in Fort de Seviere was she, and what was in her heart? Then he was swung, still bound, into the bottom of a canoe, saw De Courtenay tossed into another, felt the careless feet of Nakonkirhirinons as the paddlemen stepped in, and existence became a thing of gliding motion, the lapping of water on birchbark, and the passing of a long strip of cloud-flecked sky, pink and blue and gold with the new day. Lulled by the rocking of the fragile craft that shot forward like a thing of life beneath the paddles dipping in perfect unison, McElroy lay its a sort of apathy for hours, watching the sliding strip of sky and the bending bodies of the Indians. He knew that the end awaited him somewhere ahead, but it was far ahead, very far, even many leagues beyond York factory, and his mind, again dropping into the dulness of his early awakening, refused to concern itself with aught save the blue sky and the sound of water lapping on birchbark. That sound was sweet to his befuddled brain, suggesting something vaguely pleasant. Ah, yes, it was the deep voice of the maid of the long trail speaking of the streams and the waving grass of that visionary Land of the Whispering Hills. He fell to wondering at broken intervals if she would ever reach it, to see drowsy visions of the tall form leading its band of venturers into the wilderness beyond Lac a la Croix, penetrating that country which tried the hearts of men, and with the visions came a sadness. She would go without love, mourning her cavalier of the curls, and who would be responsible for the desolation of the heart he would fain have made happy but himself? McElroy sighed, and the visions faded. When he again awakened it was evening and camp had been made. Fires danced and crackled all up and down the reach of shore set like a half- moon of pearl in a sea of emerald, where the forest shouldered down to the stream, and the smell of cooking meat was poignantly sweet. Women were busy at the work of the camp, carrying wood, mending the fires, tending the kettles swung from forked sticks, and scolding the scrambling children.. He was still bound, though not so tightly, some of the thongs having been taken off entirely, and he found that he could sit up with comparative ease, though his hands were still fast behind him and his ankles tied. There was no pacing guard this time, distance and possession making such precaution needless, for well the Nakonkirhirinons knew that none from the little post on the Assiniboine would attempt rescue in face of so great a horde as an entire tribe. McElroy sat up and looked around. One of the first things he encountered was the face of the cavalier, still smiling and looking very much as it had looked in the dawn. Like that encounter, too, De Courtenay was the first to speak in this. "Aha, my fighter of the H. B. C.," he laughed from his seat against a towering maple, "have your laggard wits come in from wool-gathering?" He, too, was more comfortably bound, and McElroy noticed that there were little rubbed creases in the sleeves of the gay blue coat where the numbing bonds had cut. The sparkling spirit was as high in his handsome face as it had been that long past morning morning by the well. The factor wondered if there was in heaven or earth anything with power to dim it. He was to see, and marvel at, the test. "Aye," he answered the cheerful query; "it has been a weary day, M'sieu, it would seem, with my senses drifting out and in at ragged intervals of which I have only vague impressions. How has it fared with you?" "Much. "Another turn to the wheel, M'sieu," said that intrepid venturer; "what next?" As if his thought had reached out among the shadows of the wood where stood the death tepee and touched its object, Edmonton Ridgar appeared among the lodges. He was bare-headed, and McElroy saw that his face was deep-lined and anxious, filled with a sadness at which he could but marvel and he passed within a stone's throw without so much as a glance at his superior. No captive was this man, passing where he listed, but McElroy noticed the keen eyes watching his every move. What was he among this silent tribe with their war-paint and their distrust of white men? It was a hopeless puzzle, and the factor laid it grimly aside. Next to the closed and impregnable front of his own post what time he passed from its sight, this cold aloofness of his chief trader cut to inmost soul. But these things were that life of the great North-west whose unspeakable lure thralled men's souls to the death, and he was content. It was chance and daring and danger which drew him in the beginning to the country, love of the wild and breath of the vast reaches, something within which pushed him forward among these savage peoples, even as the same thing pushed Maren Le Moyne toward the Whispering Hills, sent De Courtenay to the Saskatchewan. At any rate he was very hungry, and when a bent and withered crone of a squaw brought food and loosed his right hand, the young factor tossed up his head to get the falling hair out of his eyes and fell to with a relish. "Faugh!" said De Courtenay with the first mouthful; "I wonder, M'sieu, is there nothing we can do to hasten the end? Many meals of this would equal the stake." Whereat the gallant smilingly tossed the meat and its birchbark platter at the woman's feet. "If you would not prefer starvation, I would suggest that you crawl for that, M'sieu," said McElroy gravely; but the wrinkled hag gathered it up, and left them to the night that was fast settling over the forest. Thus began the long trail up to the waters of Churchill and beyond into that unknown region where few white men had yet penetrated, and fewer still. returned. CHAPTER XVI TRAVEL Day followed day. Summer was upon the land, early summer, with the sweet winds stirring upon the waters, with gauze-winged creatures flitting above the, shallows where willow and vine-maple fringed the edges and silver fish leaped to their undoing, with fleecy clouds floating in a sapphire sky, and birds straining their little throats in the forest. McElroy and De Courtenay were loosed of their bonds and given paddles in the canoes, a change which was welcomed gladly. At night a guard paced their sleeping-place and the strictest surveillance was kept over them. Down the Assiniboine, into Red River, and across Portage la Prairie went the great flotilla, green shores winding past in an endless pageant of foliage, all hands falling to at the portages and trailing silently for many pipes, one behind the other, all laden with provisions and packs of furs, the canoes upturned and carried on heads and shoulders. Of.? Not the clerks, youths from the Bay, not the traders nor the trappers. With a daring heart the venturer from Grand Portage went in across the sill. To a man the men of De Seviere rallied to him and council was held. Everywhere in the trading-room, the living-room behind, were evidences of the factor and Ridgar. It seemed as if the two men had but just stepped out-were not in hostile hands drifting down the river toward an unspeakable fate. In the midst of the grave-faced council another step sounded on the sill and once again Maren Le Moyne stood looking in at the factory door, though this time there was no eager interest on her face, only a drawn tenseness which cut to the heart of her leader like a knife. "Come in, Maren," he said in aching sympathy. "Men," she said straightly, "is there none among you who will turn a hand to save his factor?" Over every face her eyes travelled slowly, hot and burning. In every face she read the same thing,—a pitying wonder at the folly of her words. "Aye," spoke up Henri Corlier, grizzled and weathered by his years of loyal service to the Great Company, "not a man among us, Ma'amselle, but would give his life if it would serve. It would not serve." "And you?" her gaze shifted feverishly to Laroux; "you, Prix?" "'Tis useless, Maren. What would you have us do?" "Do?" She straightened by the door, and the hand on the lintel gripped until the nails went white. "Do? Anything save sit with closed gates in safety while savages burn your factor at the stake! The Hudson's Bay brigade comes from York this very month. What easier than to meet it and get help of men and guns?" "Nay," said Laroux gently; "you do but dream, Maren." Whereat the girl turned abruptly from the doorway and went down among the cabins. Here and there in the doorways groups of women stood together, their voices hushed and trouble in their eyes. As Maren passed, seeing nothing to right or left, they looked in pity upon her. The heart of this woman was drifting with the canoes,—but with which man? "'Tis the gay Nor'wester with his golden curls," whispered Tessa Bibye sympathetically. "The Nor'wester? 'Tis little you know, truly, Tessa," said the young wife of old Corlier. "What maid in her senses would look twice at yonder be-laced dandy when a man like Anders McElroy stood near?" "Aye, an' may the Good God have mercy on our factor!" whimpered a withered old woman, wife of a trapper, making the sign of the cross; "nor hold back His mercy from the other!" Night seemed to fall early on Fort de Seviere, waiting sadly for its healing touch on fevered hearts. Throughout the long day a waiting hush had lain upon the post, an expectancy of ill. Over the dark forest the stars came out on a velvet sky, and a little wind came out of the south, nightbirds called from the depths, and peace spread over the Northland like a blanket. While the twilight lasted with its gorgeous phantasmagoria there were none of the accustomed sounds of pleasure in the post,—no fiddle squeaked by the stockade wall, no happy laughter wafted from the cabins. Even the sleepy children seemed to feel the strangeness and hushed their peevish crying. Night and darkness and loneliness held sway, and in one heart the shadows of the world were gathered. What was the meaning of this Life whose gift was Pain, where was the glory of existence? By the window to the east Maren Le Moyne stood in the darkness, with her hands upon her breast and her face set after the manner of the dreamer who follows his visions in simpleness of soul. Once again a great call was sounding from the wilderness, as that which lured her to the Whispering Hills had sounded since she could remember, once more the Long Trail beckoned, and once more she answered, simply and without fear. She waited for the depth of night. Long she stood at the little window, facing the east like some worshipper, even until the wheeling stars spelled the mid hour. To Marie she gave one thought,—child-like Marie with her dependence and her loving heart. But Marie, to whom she had been all things, was safe in the care of Henri. There remained only the dream of the Whispering Hills and the illusive figure of a man,—an old man, sturdy of form and with blue eyes set in swarthy darkness. Poignant was the pain that assailed her at that memory. Would she ever reach that shadowy country, ever fulfil the quest that was hers from the beginning? Did she not wrong that ghostly figure which seemed to gaze with reproach across the years? Her own blood called, and she turned aside to follow the way of a stranger, an alien whose kiss had brought her all sorrow. And yet she was helpless as the water flowing to the sea. The primal quest must wait. Her being turned to this younger man as the needle to the pole, even though his words were false, his kiss a betrayal. When the mid hour hung in silence over the wilderness a figure came out of the darkness and stood at the gate beside that watcher, Cif Bordoux, who paced its length with noiseless tread. A strange figure it was, clad in garments that shone misty white in the shadow, whose fringes .fluttered in the warm wind and whose glowing plastron glittered in the starlight. "Cif Bordoux," said the figure, "I would go without." Wondering and startled, Bordoux would have refused if he dared; but this was the leader of the Long Trail and her word had been his law for many moons, nor had he ever questioned her wisdom. Therefore he drew the bolts and opened the gate the width of a man's body, and Maren Le Moyne slipped outside the palisade into the night. A rifle hung in her arm and a pouch of bullets dangled at her knee. Swiftly and silently she pushed a canoe into the water at the landing, stepped in, and with one deep dip of a paddle sent the frail craft out to midstream. She did not turn her head for a farewell glance toward the post, but set her face toward the way that led to the Pays d'en Haut and the man who journeyed thither. Deep. With her arms full of dead sticks she came back to the canoe,—and face to face with Marc Dupre. His canoe lay at the cove's edge and his eyes were anguished in a white face. "Ma'amselle," he said simply, "I came." No word was ready on the maid's lips. She stood and looked at him, with the little sticks in her arms, and suddenly she saw what was in his eyes, what made his lips ashen under the weathered tan. It was the same thing that had changed for her the face of the waters and the wood. She had learned in that moment to read a man better than she had read aught in her life beside the sign of leaf and wind. "Oh, M'sieu!" she cried out sharply; "God forbid!" The youth came forward and took the sticks from her, dropping them on the ground and holding both her hands in a trembling clasp. "Forbid?" he said and his voice quivered; "Ma'amselle, I love you. Though my heart is full of dread, I am at your feet. By the voice of my own soul I hear the cry of yours. We are both past help, it seems, Ma'amselle,-yet am I that stone to your foot which we pledged yonder by the stockade wall. You will let me go the long trail with you? You will give me to be your stay in this? You will let me do all a man can do to help you take the factor from the Nakonkirhirinons?" The infinite sadness in Dupre's voice was as a wind across a harp of gold, and it struck to Maren's heart with unbearable pain. Her eyes, looking straight into his, filled slowly with tears, and his white face danced grotesquely before her vision. "M'sieu," she said quite simply, "I would to God it had been given me to love you. We have ever seen eye to eye save in that wherein we should have. And I know of nothing dearer than this love you have given me. If you would risk your life and more, M'sieu, I shall count your going one of the gifts of God." "I cannot ask you to return, Ma'amselle,—too well do I know you,—nor to consider all you must risk for, this,—life and death and the certain slander of the settlement,—though by all the standards of manhood I should do so. The heart in me is faithful echo of your own. This trail must be travelled,—therefore we travel it together. And, oh, Ma'amselle! Think not of my love as that of a man! Rather do I adore the ground beneath your foot, worship at the shrine of your pure and gentle spirit! See!" With all the prodigal fire of his wild French blood, the youth dropped on his knee and, catching the fringe on the buckskin garment, pressed it to his lips. For once Maren, unused to tears, could speak no word. She only drew him up, her grip like a man's upon his wrists, and turned to the making of the fire. Dupre drew up his canoe and took a snared wild hen from the bow. * * * * * * * * * "I think, Ma'amselle," said the youth when Maren awaked some hours later from a heavy sleep, during which Dupre had killed the little smoke of the fire and kept silent watch from the shore, "that we had best leave your canoe here and take mine. It is much the better craft." "So I see. Mine was but the first I could put my hands upon in the darkness." "'Tis that of old Corlier, and sadly lacking in repair. If you will steer, Ma'amselle?" Thus set forth as forlorn a hope as ever lost itself in that vast region of hard living and daily tragedy, with the strength of the man set behind the woman's wisdom in as delicate a compliment as ever breathed itself in silken halls, and the blind courage of the dreamer urged it on. . At the forks of Red River they passed the signs of a landing. Here had the Indians summarily sent ashore all of the Nor'westers who had been with De Courtenay and who had followed in the uncertainty of fear, not daring to desert lest they be overtaken and massacred. All, that is, save Bois DesCaut and the lean, hawk-faced Runners of the Burnt Woods. Thanking their gods, the North-west servants had lost no time in taking advantage of the fact that they were not wanted, leaving their Montreal master to whatever fate might befall him. Dupre went ashore and examined the reach of land, the trampled grass, a broken bush or two. "Ten men, I think," he said, returning, "and all in tremendous haste. The Nor'westers escaping, I have no doubt. Would our captives were among them." "No such fortune, M'sieu," said Maren calmly, "Heard you not the cry before the gate in that unhallowed scramble what time they took the factor and the venturer? 'Twas 'a skin for a skin.' There are many guards." The summer day dreamed by in drowsy beauty, like a woman or a rose full-blown, and Maren, who would at another time have seen each smallest detail of its perfection through the eye of love, saw only the rushing water ahead and counted time and distance. Dupre, kneeling in the bow, his lithe brown arms bare to the shoulder, where the muscles lifted and fell like waves, was silent. Sadness sat upon him like a garment, yet lightened by a holy joy. Odd servers of Love, these two, who knew only its pain without its pleasure, yet who were standing on the threshold of its Holy of Holies. Of nights they sat together at the tiny fire of a few laid sticks and talked at intervals in a strange companionship. Never again did they speak of love, nor even so much as skirt its fringes, though the young trapper read with wistful eyes its working in the woman's face. Out of her eyes had gone a certain light to be replaced by another, as if a star had passed near a smouldering world and gone on, changed by the contact, its radiance darkened by a deeper glow. The firm cheeks, dusky as sunset, had lost something of their contour. Like comrades, too, they shared the work and the watches, the girl standing guard with rifle and ball while Dupre snatched heavy sleep, herself dropping down like the veriest old wolf of the North on mossy bank or green grass for the rest they sternly shortened. "'Tis near the time of the Hudson's Bay brigade, is it not, M'sieu?" she would ask sometimes. "Think you we shall meet them surely if we skirt the eastern shore of Winnipeg?" And Dupre would always answer, "Assuredly. By the third week in July they will be at the upper bend where the river comes down from York. The Nakonkirhirinons will hold to the west, going up Nelson River and west through the chain of little lakes that lie to the south of Winnipeg, thence gaining Deer River and that Reindeer Lake which sends them forth into their unknown region beyond the Oujuragatchousibi. We, then, will make straight for the eastern shore, skirting upward to the interception of the ways, and we will surely meet the brigade." "And they will surely lend help, think you, to a factor of the Company in such grave plight?" "Surely, Ma'amselle." So the hours of day and darkness slipped by with dip of paddle and with portage, with snatched rest and fare of the wild. In a plentiful forest and on an abundant stream Dupre was at no loss for food. Trout, sparkling and fresh from the icy water, roasted on forked sticks stuck in the ground beside a bed of coals, made fare for an epicure, and the young trapper, watching Maren as she knelt to tend them, shielding her face with her hand, thought wistfully of a cabin where the fire leaped on the hearth and where this woman passed back and forth at the tasks of home. "'Tis too great a thing to ask of le bon Dieu," he said in his heart; "'tis not permitted even that one dream of such joy,—'twould be heaven robbed of its glory." So he fished and hunted for her, as the primal man has hunted and fished for his woman since time began, tended her fires and guarded her sleep, and the wistful sadness within him grew with the passing days. Down that northbound river the lone canoe with its two people hurried after the great flotilla, silent and determined, like a starved wolf on the flanks of a caribou herd. Out on the breast of the great blue lake it, too, was shot by the rushing waters, lone little cockleshell, to head its prow to the eastward, where the green shore curved away, to take its infinitesimal chance of victory against all odds. When the sun came out of the eastern forest, a golden ball in a cloud of fire, it saw the light craft already cutting the cool waters of Winnipeg. When it sank into the western woods the bobbing dot was still shooting forward. Child of the wilderness by birth was Dupre, child of the wilderness by dream and desire was Maren, and its simple courage was inborn in both. The Indians were a day and night ahead, hurrying by dawn and dusk to the north, that the body of the dead chief, cured like a mummy by the smoke curling from the big tepee at every stop, might have burial, the earth-bound spirit begin its journey to the shadowy hunting-grounds. When—". Aye, verily, this was the unknown. She was looking down the lake with the sun on her uncovered head, on the soft whiteness of the doeskin garment, and to young Dupre she had never seemed so near the divine, so far and unattainable. "Ma'amselle," he said presently, "if these newcomers speak us, heed you not what I may say. There are times in the open ways when a man must lie for the good of himself—or others." The girl turned her eyes from the canoes, some twenty of them, to his face. It was grave and quiet. "Assuredly," she said after a moment's scrutiny. "Had I best hide in the bushes, M'sieu?" "No, they have seen us." Sweeping forward, the brigade of the Nor'westers, for such it proved to be, headed near in a circle and the head canoe turned in to shore. "Friend?" called a man in the prow; whom Dupre knew for a wintering partner by the name of McIntosh of none too savoury report. "Hudson's Bay trapper, M'sieu," he said politely, going a step nearer the water. "I wait, with Madame my wife, the coming of our brigade from York, now one day overdue." "Ah,—my mistake. I had thought the H. B. C.'s this fortnight gone down. As ever, they are a trifle behind." While he addressed Dupre his bold eyes were fastened on Maren, where she hung a dressed fish on a split prong. "Not behind, M'sieu," said the young man gently. "They but take the time of certainty. A Saulteur passing this way at daylight reported them as at McMillan's Landing." "Then your waiting is short. I am glad,—for Madame. So lone a camp must be hard for a woman." With the words the Nor'wester scanned the girl's face with a glance that pierced her consciousness, though her eyes were fixed on her task. Not a tinge of deeper colour came to her cheeks. There was no betrayal of the part Dupre had assigned her, and with a word of parting the canoe swung out to its place, though McIntosh's eyes clung boldly to her beauty so long as he could see her. "Ah-h,—a close shave!" thought the trapper as he picked up a splinter and once more fell to upon the boat. Twenty-four hours later there came out of the north the thrice blessed brigade of the H. B. C., bound down the lake to Grand Rapids, where the canoes would separate into two parties, one going up the Saskatchewan to Cumberland House, the other down to the country of the Assiniboine. Eager as a hound for the quarry Maren stood forth beside Dupre to hail them. Head of the brigade was Mr. Thomas Mowbray, a gentleman of fine presence and of gentle manners. In answer to the hail from shore he came to, and presently he stood in the prow of his boat listening to an appeal that lightened his grave eyes. "Men we must have, M'sieu," Maren was saying passionately; "men of the Hudson's Bay. Against all odds we go of a truth, but strategy and wit accomplish much, and the Nakonkirhirinons have no thought of rescue. Besides, the farther north they get the less keen will be their vigilance. With men, M'sieu, we may retake, by strategy alone of course, the factor of Fort de Seviere. Therefore have we come across your way, In the Name of Mary, M'sieu, I beg that you refuse me not!" She was like some young priestess as she stood in the westering light on the green-fringed shore, one hand caught in the buckskin fringe at her throat and her eyes on Mr. Mowbray's upright face. "Upon my word, Madame—?" he said when she had finished. "Ma'amselle, M'sieu," she corrected simply. "Ma'amselle,—your pardon,—upon my word, have I never seen such appalling courage! Do you not know that you go upon a quest as hopeless as death? This tribe,—I have heard a deal too much about them, and once they came to York two seasons back,—are unlike any others of the Indians of the country. Ruled by a peculiar justice which takes 'a skin for a skin'—not ten or an hundred as do the Blackfeet or the Sioux,— they yet surpass all others in the cruelty of that taking. Have you not heard tales of this surpassing cruelty, Ma'amselle?" "Aye, we have heard. It hastens our going. M'sieu the factor awaits that cruelty in its extremest manner with the reaching of the Pays d'en Haut." "Mother of God!" said Mr. Mowbray wonderingly. "And yet,—I see!" "And he is Hudson's Bay, M'sieu," said the girl sharply; "a good factor. Would the Company not make an effort to save such, think you?" Mr. Mowbray stood a moment, many moments, thinking with a line drawn deep between his eyes. Out on the burnished water the canoes lay idly, the red kerchiefs of the trappers making bright points of colour against the blue background. Presently he said slowly "What yon ask is against all precedent, Ma'amselle, and I may lose my head for tampering with my orders,—but I will see what can be done." The brigade drew in, and when dusk fell upon the wilderness a dozen fires kept company with the lone little spiral from Dupre's camp. Sitting upon the shingle with her hands clasped hard on her knees, Maren shook her head when the young trapper brought her the breast of a grouse, roasted brown, along with tea and pemmican from the packs of the H. B. men. "I thank you, my friend," she said uncertainly; "but I cannot—not now. Not until I know, M'sieu. Without many hands at the paddles how can we overtake the Nakonkirhirinons?" Thus she sat, alone among men, staring into the fire, and it seemed as if the heart in her breast would burst with its anxiety. A woman was at all times a thing of overwhelming interest in the wilderness, and such a woman as this drew every eye in the brigade to feast upon her beauty, each according to the nature of the man, either furtively, with tentative admiration, or openly, with boldness of daring. And presently, after the meal was over, she saw Mr. Mowbray gather his men in a group. For a few moments he spoke to them, and a ripple of words, of ejaculations and exclamations, went across the assemblage like a wave. "Nom de Dieu! Not alone?" "To the Pay d'en Haut,—those two?" "A woman? Mother of God!" Wondering eyes turned to the figure in the glow of the fire, to the brown hands hard clasped, the face with its flame-lit eyes. "Five men and a good canoe I send with them," said Mowbray quietly; "who goes? Know you it is a quest of death." "Who goes, M'sieu?" cried a French trader. "I! 'Tis worth a year of the fur trade!" "And I!" Once more she had made her appeal to man, man in the abstract, and once more he had come to her, this maid of dreams. Mr. Mowbray had lost half his brigade had he not fixed on those who were the strongest among the volunteers, the best canoe-men, the best shots. Such were these men of the wilderness, excitable, ready for any hazard, drawn by the longest odds, and to serve a woman gave the last zest to danger. Seldom enough did a woman appeal to them in such romantic wise. "Brilliers,—Alloybeau,—Wilson," picked out Mr Mowbray, with a finger pointing his words; "McDonald,—Frith,—make ready the fourth canoe, Take store of pemmican and all things necessary for light travel and quick. From to-morrow you will answer to Ma'amselle. When she is through with you report to me, either at Cumberland or York, according to the time." And he left his men to walk over and seat himself beside Maren Le Moyne on the shingle. It was dark of the moon and the night was thick with stars and forest sounds. Out on the lake beyond the ranged canoes at the water's edge, the fish were slapping. "Ma'amselle," said Mr. Mowbray gravely, "I have detailed you five men, a canoe, and stores. May God grant that they may serve your purpose" A long sigh escaped the girl's lips. "And may He forever hold you in His grace, M'sieu!" she said tremulously; "and bless you at the hour of death!" "And now, Ma'amselle," he said gently, "tell me more of this strange adventure. How comes it that a young maid, alone but for a youthful trapper, goes to the Pays d'en Haut after a factor, of the Company? Why did this duty not fall to the men of the post?" "They said, as you, M'sieu, but an hour back, that it was a quest of death. They love life. I love the factor." She made her explanation simply, in all innocence, looking gravely into the fire, and Mr. Mowbray gasped inwardly. "I see. So Anders McElroy is your lover. A fine man, worthy of the love of such a woman, and blessed above men in its possessing if I may make so bold, Ma'amselle." "Nay,—you mistake." Maren shook her head. "Not my lover. I but said that I love the factor He does not love me, M'sieu." "What? Heaven above us! What was that? Does not love you! And yet you go into the Pays d'en Haut after the North Indians? You speak in riddles." "Why, what plainer? Life would die in me, M'sieu, did I leave him to death by torture. I can do no less." Mr.. Like an embodiment of that very absurdity of courage so dear to the hearts of these men, the girl sat in the prow, taking a hand in the work with the best of them, beaconing the way as she had done before her venturers of Grand Portage, firing them with her calm certainty, binding them to her more firmly with each day. To each bit of courtesy done eagerly to her there was her grave "I thank you,"—at each portage and line her hand to the rope, her shoulder to the pack, and all in the simple unconsciousness of her womanhood that made her what she was,—a leader. Before forty-eight hours had passed they would have followed her to the brink of death,—to the Pays d'en Haut, to the heart of an hostile camp. They fixed their eyes on her shining braids, bare to the sun, and anticipated her commands, obeyed her few words implicitly, and who shall say that many a dream did not weave itself around her in the summer days, for every man in the boat was young. Perhaps the Nakonkirhirinons had already yielded to the savage wrath that takes a "skin for a skin,"—perhaps they had passed somewhere in the forest, hidden from view from the water, the too well-known blackened stake, the trodden circle. Perhaps there was no factor of Fort de Seviere. Only Marc Dupre, nearest Maren in every change and arrangement, had no such thoughts. Dreams enough he wove in all surety, but they had to do with the blinding heights of sacrifice, the wistful valleys of renunciation. His heart was full to overflowing with idolatry. From shadow and fireglow his dark eyes looked upon her with a love that had passed far beyond the need of word or touch, that buoyed her up and supported her in strength and purity, like the silver cloud beneath the feet of the Madonna. And Maren, too, dreamed her dreams, for she had dreamed since the days of the forge in Grand Portage, and they were sad as death. No more did she list the sound of a western wind in the bending grass of a far country, the rush of virgin rivers, the whisper of pine-clad hills. The joy of the great quest was dead within her, the love of forest and stream, the lure of trail and trace. Sadness sat upon her like a garment. She only knew the pain that had birth that night in De Seviere when she sought McElroy to disclaim the giver of the red flower and found him kissing the red-rose cheek of the little Francette. So went forth this little barque o' dreams. Meanwhile what of the two men who journeyed ahead? With each day they lost a little of the love of life, for with the cunning which gave them their hazy fame the Nakonkirhirinons were tightening the screws of cruelty. Work beyond a man's strength was meted out to them. Alone in a long canoe heavily laden, McElroy and De Courtenay were forced to keep the pace set by the boats, each of which carried five men. Blisters came in their hands, broke and rose again, sweat poured from their straining bodies, and if they fell slow a spear-prod from the boat behind sent them forward. How much more exquisite could be made the torture of a victim already worn to the ragged edge, how much sooner the scream be wrung from his throat. With each passing league that brought them nearer the end of the journey could be seen the fiendish eagerness rearing in the glittering eyes. Turn and turn they took, these two, of the hindmost seat in the canoe, for the back of each was unspeakable from the spear-prods. Without a word McElroy took his punishment as the lagging became more pronounced from arms overtaxed at the paddles, but the long-haired adventurer from the Saskatchewan taunted them to their faces. Taunt and fling were unavailing. Of an unearthly poise were these savages from the distant north. With grinning good humour they withheld their anger, knowing full well that time would doubly repay. Here and there among them appeared those worst monsters of the wilds, INDIANS WITH BLUE EYES AND SQUARED-OUT TOES. Far up ahead went forward the canoe of the dead chief, with Edmonton Ridgar sitting in silence among the blackened warriors. Never once did he glance backward, never once at the night camps did he come near his factor. Throughout the long days McElroy pondered this in his heart and turned it over and over without satisfaction. Unable to form any conclusion he fell to thinking of their friendship and of the gentle nature of the man, the unbending faith of him. It was all a sorry riddle. "Brace up, M'sieu," De Courtenay would laugh, even in the midst of exhaustion; "sing,—smile,—perhaps it will be only the stake, not something worse. Console yourself, as do I, with—memories." And McElroy would say nothing, trying in his heart to hold back his wrath against this man for whose death he was to be responsible. So went the uneven chase. Day's march of the savages and night's rest on the green shores, mummying fires in the big tepee and the captives lying in the sleep of exhaustion with one guard pacing the lodge opening,—day's pursuit of the lone canoe, brief landings for tea made at a micmac fire, scanning of lake and river and forest, night's unceasing forging .ahead with Maren asleep in the prow, her head on Dupre's blanket. When the last hard portage was made which carried them into Deer River, the girl looked to the west with a sudden fire of the old passion in her eyes. "So, M'sieu?" she said to Dupre, "it lies yonder, the Land of the Whispering Hills? Would God our course lay there!" And Dupre, wondering, answered, "Aye, at the Athabasca," for it was to McElroy alone that she had uncovered her soul concerning the great quest. In Deer River the signs began to be plainer and fresher, showing the passing of the Indians,—here a camp but two days deserted, there scraps of refuse not yet cleared away by forest scavengers, and the pursuers knew they drew close to danger and excitement. All day the men of Mowbray's brigade bent to the paddles in growing eagerness, and at the evening's stop Maren spoke to them, gathered around with cold rations in their hands, for no fire was lighted now. "To-morrow we will overtake the Nakonkirhirinons," she said simply, as if that meant no more than speaking a brother brigade of Hudson's Bays, "and then will come the time of action. At night-camp we will make our effort of deliverance. You, Alloybeau, and you, McDonald, will keep within my call whatever happens, while Frith and Brilliers and Wilson will stay with the canoe, ready for instant flight. M'sieu," she laid a hand on Dupre's arm and her voice deepened softly, "is scout and captain and he goes at my side. More I cannot say until we know the lie of land to-morrow." So they again took boat, this little band of venturers than whom there were no more daring threaders of the wilderness in all the vast unknown country; and Maren sat in the prow, her hands idle in her lap, for she had paddled since four by the sun. Beside her, huddled half under the feet of Wilson on the foremost thwart, Dupre watched the stars as they came out in a turquoise sky, for the sleep that was due him would not come. He thought of the morrow and what it would bring, and the sadness in his heart grew with the deepening shades. The fringed garment of white doeskin lay under his elbow and a fold of it brushed his cheek, and, boy that he was, its touch brought the quick tears to his eyes. "Ma'amselle," he said presently, when the turquoise had faded to purple and the purple to velvet black, with the stars like a dowager's diamonds thickset upon it, "Ma'amselle, what think you is behind the stars?" Maren turned her face to him like a sweet young moon, pale in the night. "Behind the stars? Why, Heaven, M'sieu, where all is glory; Heaven assuredly." "Aye. Where all is glory. Yes, for those who keep the holy mandates, whose hearts are pure as that heaven itself. For such as you. Oh, Holy Mother!—" his voice fell to a whisper; "there is no heaven, Ma'amselle, so pure as the white heart of you! But for him whose days have gone like the butterfly's flight from one prodigal joy to the next, whose heart has known neither love of God nor love of a good woman, save for a little space, whose tongue has boasted and blasphemed, and whose life has been worth no jot of good,—what, think you, a waits so lost a man as this?" The light "whoosh,—sst—whoosh" of the dipping paddles, the occasional rattle of a handle on a gunwale, formed a blending background against which his low words were distinguishable only to the girl beside him. She looked long into his upturned face. The wistfulness sat heavy upon it. The youthfulness of this dashing trapper of the posts and settlements came out plain in the starlight. She saw again the pliant strength beneath the slender grace, caught the suggestion of contradicting forces that she had felt one day in Marie's doorway when young Dupre swung up the main way of Fort de Seviere, and beneath it all she saw that which had caused her to say on that first morning of the long trail when he faced her in the hidden cove, "Would it had been given me to love you, M'sieu!"."." As they lay watching the unearthly orgy at the fire a plan slowly took shape in McElroy's mind. They were unbound as they had been for many days, the silent guard proving sufficient surety for their retention, and they were two to one in the wild confusion of the growing excitement. What easier than a swift grapple in the dusk, one man locked in combat with the sentinel and one lost in the forest and the night? It was a desperate chance, but they were desperate men with the post, the hatchet, and the matete before them. As the thought grew it took on proportions of possibility and the factor threw up his head with the old motion, shaking out of his eyes the falling sun-burnt hair. "M'sieu," he said, in a low voice, carefully modulated to the careless tone of weary speech which was their habit of nights; "M'sieu, I have a plan." The cavalier looked up quickly. "Ah!" he said; "a plan? Of what,—conduct at the stake? The etiquette of the ceremony of the Feast of Flame?" "Peace!" replied McElroy sternly; "you jest, M'sieu. We are in sore straits and a drowning man snatches at straws. It is this. The fire of liquor is rising out there. Hear it in the rising note of the blended voices. How long, think you, will they be content with the dance and the chanting, the tom-toms and the empty fire? How long before we are dragged in, to be the centre of affairs? In this plan of mine there is room for one of us, a bare chance of escape. This guard behind,—he is a powerful man, but, with every warrior wild in the circling mass yonder, he might be engaged for the moment needed for one to dart into the darkness and take to the river. Once there, the mercy of night and bending bushes might aid him. What think you?" "Truly 'tis worth the try. My blood answers the risk. At the most it would but hasten things. But give the word and we'll at it." "Nay,—we must understand each other, lest we bungle. As the plan was mine, I take the choice of parts. There is a stain upon my conscience, M'sieu." McElroy spoke simply from his heart, as was his wont. "Throughout this long journey it has lain heavy. Though I hold against you one grave offence, yet I grieve deeply that it was through my hasty anger you were brought to such sorry plight. As I am at fault, so would I heal that fault. This the way I find given me. When I spring for our friend of the painted feather, do you, M'sieu, waiting for nothing, take to the bush with all the speed there is in you. And before we part know that, were we free, I would punish you as man to man for that moment before the gate of De Seviere with all pleasure." "Ah! You refer to Ma'amselle Le Moyne? By what right?" "By the right of love, whose advances were more than half-reciprocated before the advent of your accursed red flowers,—the right of man to fight for his woman." "Nom de Dieu!" De Courtenay threw back his head and laughed, the flecks of light from the fire flittering across his handsome features. "You speak a lost cause, my friend! She was mine since that first morning by your well when the high head bent to my hand. What a woman she is,— Maid of the Long Trail, Spirit of the Woods and Lakes! A lioness with a dove's heart! I have seen the Queen of the World in this God-forsaken wilderness; therefore is it worth while." "Stop!" cried McElroy sharply; "let the old wound be. Only make ready to act at once." "Aye,—I am ready now." "Then rise with me,—swiftly as possible,—when I count to three. One— " The two men strained their bodies, leaning forward, for both had risen to sit facing the fire when the dance began. "Two,—" breathed McElroy, "ready, M'sieu,—three!" With one accord they leaped to their feet, and the factor in a flash was upon the Indian just passing behind him. He had leaped high, for the Nakonkirhirinon was taller than a common man, and he clutched the muscled neck in a grasp of steel, pressing his shoulder against his adversary's face, to still the outcry he knew would come. The orgy at the fire was lifting its tone of riot into one of savagery and menace, the tom-toms beat more swiftly with gaining excitement, and the yapping yells were growing more frequent. It was an auspicious moment and the heart of McElroy throbbed with a savage pleasure, but suddenly he felt other hands disputing his grip on the astonished Indian, who was raining blows upon him having dropped his gun in the first shock. Over the bare shoulder of the warrior, shining like bronze in a gleam of light, he saw the face of De Courtenay, its blue eyes alight. In a flash his grip was torn from behind, and, as the Indian reared his head and threw back his great shoulders, lifting him clear of the earth, he heard the joyous voice of the cavalier. "Run!" it cried, as he fell clear; "run! And tell Maren Le Moyne that her name is last upon my lips,—her face last before—" Out above the words there rang the shrill cry of the guard, his mouth uncovered by McElroy's shaking off. The Indian had whirled and grappled with De Courtenay, and, before McElroy could tear him loose, fighting like a madman, out from the yelling circle there poured an avalanche of lunatics, jerked from Gehenna by that ringing cry. Foremost was Bois DesCaut, his evil eyes glinting like a witch's omen. Yelling, jumping, flaming with the liquor of the Bois-Brules, they fell upon the two men and dragged them, half-falling, half-running, toward the circle, into it, and up to the fire. "Ho-ho! ho-ho-o! Ha-ha! ha-ha-a! ha-ha!" Faces wild as the devil's dreams pushed close, hands plucked at them, and suddenly a dozen painted braves caught up handfuls of live coals and flung them upon them. In the midst of it McElroy looked stupidly at De Courtenay. "For the love of God!" he said, "why did you not run?" "Why didn't you?" The cavalier was laughing. "I could not, M'sieu," he added; "the charm of the hazard was too great." And that was the last word he offered the man who would have delivered him, turning to face the savages. "Dogs!" he cried in French; "dogs and sons of dogs!" Stooping suddenly, he snatched a horned headdress from the crown of an aged medicine man, scooped it full of glowing brands, and tossed its contents straight into the wild faces before him. Then he straightened, crossed his arms, and smiled upon them in contempt. Pandemonium was loose. In breathless swiftness the captives were stripped to the skin, tied hand and foot, and fastened to stakes set hastily up on either side the fire. "It begins to look, M'sieu," called De Courtenay, across the space and the roaring flames, "as if the Nor'westers and the Hudson's Bays must scratch up a new wintering partner and a fresh factor,—though, 'ods blood! this one is fresh enough! Will they cure us as as they have Negansahima?" At mention of the dead chief a dozen missiles cut the night air and struck the speaker. One, a lighted torch, landed full in his face, and McElroy groaned aloud. If De Courtenay hoped by his taunts and his jeers to reach a swifter end, he was mistaken in that hope. No fire was kindled at their stakes, no sudden stroke of death maul or tomahawk followed his words. The Nakonkirhirinons had keener tortures, torments of a finer fibre than mere physical suffering, and the Bois-Brules' liquor had stirred the hidden resources. Again the dancing commenced, but this time it was not the harmless measure of the stamp-dance. Instead of the bending bodies, the rhythmic stamping of soft-shod feet, the extended palms, there were unspeakable leapings, writhings, and grimaces revolting in their horror, brandishing of knives, and yelling that was incessant. McElroy closed his eyes and forced his mind to the Petition for Mercy. Through the tenor of the beautiful words there cut from time to time De Courtenay's voice, cool, contemptuous, a running fire of invective, now in French, now in English, and again in the Assiniboine tongue, which was familiar to the Nakonkirhirinons, they being friends with that tribe. As the hubbub rose with the liquor two slabs were brought, rough sections of trees hastily smoothed with axe and hatchet, of the height of a man and the thickness thereof, with a slight margin at top and sides. These were set up behind the stakes that held them, thus forming a background, and the two naked forms stood out in the firelight like pictures in white frames. A wise old sachem, hideously painted, drew a line on the ground at thirty feet, facing the central fire, and with a bony finger picked out a certain number of warriors. Full fifty there seemed to McElroy when he opened his eyes to see them ranged before the line, all armed with knives that shone in the glow, and (grim irony of fate!) in the blades of some there was a familiar stamp—H. B. C.! . A shout of derision greeted this throw, and two more took the place of the retiring braves, this time a Runner of the Burnt Woods, wearing the garments of the white man, but smeared with bars of red and yellow paint across the cheeks, and a white renegade. "A Nor'wester's man once," thought McElroy; "another DesCaut." Again the "whut-t" of the whimpering blades, again the little impact in the wood behind, this time with more indifferent aim; for never was white man yet who sank or rose to Indian level in the matter of spear or tomahawk. They were brave men, these two, and they faced the singing knives without a quiver of muscle, a droop of eye, while the joy of the savages, at last turned loose, rose and rose in its wildness. For an hour the mob at the line threw and shifted, the vast circle sitting or standing in every attitude of keenest enjoyment. The slabs bristled with steel, to be cleaned and decorated anew, while the fire in the centre leaped and crackled with an hundred voices. A stone's-throw away the grim tepee of the dead chief glimmered now out of the shadow, now in, and to the east behind a rocky bluff, through which led a narrow gorge, the river hurried to the north. Blood-painted brilliant splotches here and there against the white pictures, but neither man was limp in his bonds, neither fair head drooped, neither pair of blue eyes flinched. De Courtenay's long curls hung like cords of gold against his bare shoulder, enhancing the great beauty of him, while his brilliant smile flashed with uncanny steadiness. McElroy's face was grave, lips tight, eyes narrow, and forehead furrowed with the thought he strove in vain to make connected. Suddenly every shade of colour drained out of his countenance, leaving it white as the virgin slab behind. On the outskirts of the concourse, just at the edge of shadow and light, Edmonton Ridgar stood apart and the look on his face was of mortal agony. As his eyes met those of his factor all doubt was swept away. This was his friend, McElroy knew in that one swift moment, even as he watched his torture, his friend on whose faith and goodness he would stake his soul anew. It was strange what a keen joy surged through him with that subtle knowledge, what smart of tear-mist stung his eyes. Long their gaze clung, filled with unspeakable things, things that were high as Heaven itself, that pass only between men clean of heart on the Calvaries of earth. Then,." !" "Hush!" said Maren, catching the hand at her knee, a shaking hand more slender than her own; "hush, my friend! You break my heart anew. I know the inmost grace of you, the glory of the love you tell, and be it of heaven or earth, of angel or man, I would to the Good God there was yet life enough within me to buy it with my own! I have seen naught so holy, so worth all price, in the years of my life. It is dear to my heart as that life itself. Dear as yourself, my more than friend." In all tenderness she stooped from her fair height and laid her arm around the shoulders of the youth, drew his head against the beadwork of McElroy's gift, and kissed him upon the lips,—once, twice, yearningly, as a mother kisses a weakling child. At that moment there came, borne on a waking breeze of the night, the sound of the tom-toms, the yapping of many throats. "The gods beckon," she said sadly; "this life and love is all awry and we who are bound against our will must but abide the end." "Aye," whispered young Dupre, from the warm depths of her shoulder, and his voice was like gold for joy; "aye,—the end." He rose swiftly. "Forgive the passion that could forget the great business of the night," he said, and they went forward, though Maren's fingers still rested in his clasp. Through the thinning wood which neared the stream presently there came a glow and then the shine of a great fire ahead, with massed figures that leaped and sprang, fantastic as a witch's carnival, and a roar of frightful voices. "Stay now, Ma'amselle!" begged Dupre, at last, for he had caught a sight that shook him through and through; "stay you here in the wood while I go forward!" But his protest was lost on the maid. Eagerly she was pushing on, hid by the shadows,—nearer and nearer, until suddenly she stopped and stared upon the scene, the fingers in his clasp gripping Dupre's hand like steel. "God! God! God!" breathed Maren Le Moyne at the forest's edge as she looked once more upon the face of the factor of Fort de Seviere. Unspeakable was that scene. All reason had fled from the North savages. What small veneer of docility had been spread over them by their three years' dealing with the Hudson's Bays and their intercourse with the quiet and tractable Assiniboines, had vanished. They were themselves as nature made them, cruel to the point of art. The work of the day was visible upon the captives tied to their stakes on either side the fire. Half-clothed, for they had been thrown into a lodge to recuperate for the night's festivities, they stood in weariness, that from time to time drooped one head or the other, only to lift again with taunt and jeer. De Courtenay, his thin face between the curls thinner, was still facing the mob with the smile that would not down. McElroy was as Maren had ever known him, patient and strong, and from time to time he tossed up the light hair falling in his eyes. "We. She. The. They drew a line upon the earth as they had done before, squabbling over its distance from the painted post; Bois-Brules, their keen eyes gleaming, haggling for a greater stretch, and presently Maren stood upon that line and they had pressed into her hand a bright new hatchet, one of those bought from McElroy himself in the first days of trading. Then an Indian, naked and painted like a fiend, whose toes turned out, stepped forth and spoke in good English. "Woman Who Follows," he said distinctly, "one of these two dogs is a murderer,—having killed the Great Chief when his people came in peace to trade at the Fort. Therefore, one of them must die. The Nakonkirhirinons take a skin for a skin,—not two skins for one. So did the Great Chief teach his people. But none know which hand is red with his blood. For two sleeps and a sun have the braves given them the tests,—the Test of the Flying Knives, the Test of the Pine Splinters, the Test of the Little Lines, but neither has shown Colour of the Dog's Blood. Therefore, justice waits. Now has Wiskend-jac, the Great Spirit, sent the White Doe from the forest to decide. Throw, White Woman, and where the tomahawk strikes shall Death sit. Hi-a-wo!" The renegade stepped back and a silence like death itself fell upon the assembly. Then did the colour drain out of the soft cheeks under the berry stain and the girl from Grand Portage stand fingering the bright hatchet in her hand. Her eyes went to McElroy's face and then to that of the cavalier leaning forward between his swinging curls, and both men saw the shine that was like light behind black marble, so mystic was it and thrilling, beginning to flicker in them. "Bravo!" cried De Courtenay, his brilliant face aglow with the splendid hazard. "Bravo! We are akin, Ma'amselle,—both venturers, and my blood leaps to your spirit! Throw, Sweetheart, throw! And may the gods of Chance guide your hand!" "Think not of me, Maren!" cried McElroy, in deadly earnest. "You owe me naught! Throw for M'sieu, whose peril is my doing!" For many moments she stood so, fingering the white handle of the weapon, and there was no sound in all the vast assemblage save the crackle of the flames. Then they saw her muscles tauten throughout her whole young body, saw her draw herself up to her full height, and again for a second's space she stood still. In that moment she had deliberately put herself back in the surging turmoil of Grand Portage, was listening to the words of old Pierre Vernaise: "Well done, Little Maid! Again now! Into the cleft! Into the cleft! Ah-a! Little One, well done! Alas, but you beat your old teacher!"—was feeling again the surge of a childhood triumph which scorned to bring nearer that wilderness of her dreams. With a swift motion her arm shot up and forward and the tomahawk left her hand, flying straight as an arrow for the target. It struck with a clean impact and stood, the handle a little raised and the point well set in the green wood. There was a rush of the medicine men, who seemed to act as judges, and then a silence. Peering, bending near to look closer, they gathered with confusion of voices and presently stepped back, that all might see. Neither in black nor red, but directly between the two, the blade cleaved cleanly down the dividing-line. They surged forward, gathering round like flies with buzzing and excitement, examining it from all sides, while the girl stood upon the line with her hands shut hard beside her. She did not glance again at the two men beside the fire. A sachem pulled out the hatchet and carried it back to her, while the circle formed and widened again. Again she stood at poise, again they saw the tension of her body, again the little wait, while the two men held their breath and De Courtenay's eyes were shining like stars. "A fitting close!" he was saying to himself, in that joy which was of his venturer's soul and knew not time or place. "Heart of my Life! What a close to a merry span!" Again the swift, sure motion, unmeasured of the brain, coming out of habit and pure instinct, again the "thud" of the strike, again the rush, and again the wondering buzz of talk. Once more the hatchet stood upon the line between the black and the red, directly in its own cleft! There was wondering comment, gesticulation, and swarthy faces turned upon the woman on the line. Once more the sachem in his waving feathers and tinkling ornaments drew the blade from the post and gravely carried it back to her. Excitement was riding high in the eager faces bending forward on all sides, and everywhere a growing admiration. A tribe of prowess themselves, the Nakonikirhirinons knew a clever feat when they saw it. For the third time the tall woman in the beaded garment took the hatchet and squared her shoulders. "What does it mean?" McElroy was thinking wildly; "why does she not save him while there is time?" And, even as the words went through his brain, something snapped therein and he was conscious of the circle of faces in the forest edge waving in grotesque undulations, of the arm of Maren as it straightened forward, of the flash of the hatchet as it flew for the painted post, and then of great darkness sewn with a thousand stars. As Maren had raised her hand for the throw, from somewhere out of the darkness behind the fire a stone death-maul had hurtled, aimed at her wrist, but he who threw was sorry of sight as a drunken man, for it struck the head of McElroy instead and he sagged down against the moosehide thongs, even as the hatchet once more clicked snugly in its former cleft. Then from all the concourse there went up a shout, half in anger and half in wild applause. "Nik-o-men-wa!" they cried; "the Thrower of the Seven Tribes! But the White Doe plays with the decree of Gitche Manitou! Bring the spear! Fetch forth the spears, oh, Men of Wisdom!" But in the midst of the excitement a figure walked slowly forth in the light and held up a hand for silence. It was Edmonton Ridgar. Reluctantly. "Fool woman!" he said in his heart; "sweet, brave, loving fool with the woman's heart and the man's simple courage!" CHAPTER XXIV THE STONE TO THE FOOT OF LOVE Long Ridgar lay in the darkness listening to the hushed sounds that came from lodge and dying fire—vague, awed sounds, that presently died into silence as night took toll of humanity and sleep settled among the savages. Here and there low gutturals droned into the stillness, and at the west there was oath and whispered comment where the Bois-Brules camped together. Not wholly under the spell of mystery were these half-breeds, but restless and suspicious under the conflicting promptings of their mixed blood. Slower than the Indians were they to obey the mandate of silence and peace that the Spirits of Dreams might descend upon the forest, but at last they were quiet, the tires burned down to red heaps of coals, then to white ashes, the great fire in the centre flamed and died and flamed again like some vindictive spirit striving for vengeance in the grip of death, and the utter stillness of the solitude fell thick as a garment on all the wilderness. It seemed to Ridgar that only himself in all the earth was awake and watching, save perhaps the two guards pacing without a sound the lodge of the captives, and those two within, so oddly brought near. As for McElroy, his friend of friends, an aching fear tugged in his heart that he had waited too long for the chance to help, that the patient strength was sapped at last, that the end had come. He had seen the flight of the maul, the sagging of the sturdy figure. Who had thrown it, if not that brute DesCaut? Who save DesCaut was so keen on the trail of the factor and the girl? True, De Courtenay was his latest master, and his spoiling of Maren's aim might as easily send the blade into the black as the red, but in either case he would cause her to decide the death she was trying so bravely to postpone. DesCaut, surely. The stars wheeled in their endless march, the well-known ones of the forenight giving place to strangers of the after hours, and Ridgar had begun to move with the caution of the hunted, inch by inch, out from the shelter of the lodge, when he felt a hand steal from the darkness and touch him with infinite care. He lay still and presently a voice whispered, "M'sieu Ridgar? "Aye?" breathed Ridgar. "'Tis I,—Marc Dupre from De Seviere." "Voila! Another! Are there more of you?" "I would know first, M'sieu,—where is your heart, with savage or Hudson's Bay?" "Fair question, truly. I but now am started for yonder lodge on quest of their deliverance, though without hope. Your appearance lends me that." "Sacre! 'Tis done already. Listen, M'sieu, with all your ears. Just beyond earshot, up the river to the south there lies a big canoe, with at its nose for instant action two men of Mowbray's brigade, while a hundred yards inland another waits, armed and ready to cover a hurried flight. There needs but loosing of those yonder, M'sieu, and here are we. Two Indians pace the lodge.... You one, me one. What easier? "Many! And she had but hastened the end she had come to avert! "Jesu mia," she prayed, from the shelter of her arms, "help! Help Thou —Lord of Heaven, give him to be spared!" And not once did she think of the great quest, broken by a meagre waiting by the way; no thought crossed her mind in this crisis of the Land of the Whispering Hills, of an old man, dreaming his dreams in the wilderness. Thus had love set aside like a bauble the thing for which her life had been lived, for which she had grown and prepared herself in the attainments of men. She had felt the magic touch of the great mystery, and henceforth she was captive, servant to its will, and its mandate had been service. And here was the end— A hand touched her shoulder, a hand infinitely soft of prcssurc, infinitely gentle. "Ma'amselle," whispered the cavalier in her ear, "one more turn of the wheel of Fate,—and we take the plunge together. Kin are we, truly; kin of the tribe of Daring Hearts. A lioness are you, oh, maid with the Madonna face! No woman, but a creature of the wild, superb in courage and unknown to fear! I saw it in your face that day in De Seviere,—the something alien to the common race, the spark, the light; oh, I know not what it is, save that it is Divine and yet splendidly of the earth! We are matched in heart. Venturers both, and like true venturers we shall take the longest trail with a laugh and our hands together,—and trust to the Aftermath to give us largess of that love which has its beginning in such glorious wise. Pledge me, oh, my Queen of the World!" With a grace beyond compare he drew her into his arms, silent and velvet soft, light and inimitable in his love way. In utter astonishment Maren felt his silken curls sweep her cheek, his lips on hers. Her tears were wet on his face. She put up her hands and pushed him loose. "M'sieu!" she said, "what do you do?" "Do? Why, bow to the One Woman of my heart," he said; "my Maid of the Red Flower, whom love has led to share my fate." "In all pity! M'sieu, you do mistake most grievously!" "What? Was it not confession at the post gate when this painted rabble fell upon us? Or is it still the maiden within fearing the word of love? In such short space, Sweetheart, there is no time for girlish fears. Be strong in that as in the courage of the lone trail. Speak!" "Speak?" said Maren, with her old calmness; "of a surety, M'sieu. Though I have thrilled at your careless bravery, your laughing daring which, as you say truly, is kin of my heart,—though I have taken your red flowers, yet there is in me no spark of love for you, no thought beyond the admiration of a true son of fortune. That alone, M'sieu." De Courtenay was staring at her in the blackness of the lodge, his arm fallen loose about her shoulders. "Name of God!" he whispered wonderingly, "it is not love? Then what, in the living world, has brought you over the waste to this camp of hostile savages?" "This," said Maren, and she reached a hand to the body of McElroy. "Sancta Maria! This factor? This heavy-blooded man?.... But he did speak of half-requited—Oh, Saints of Heaven! What a jest of the world! The threads of tragedy are tangled into a farce!" De Courtenay threw up his head and took a silent laugh at the ways of Fate. "Three fools together! And the riddle's key too late! At least I can set it straight for one—" He broke his laughing whisper to listen to new sounds without, a dull blow, muffled and heavy, the slight whisper of garments sliding against garments, the crunch and rustle of a body eased down to earth,—nay, two blows, coming at a little interval, and from either end the beat walked by the two guards, and from the southern end there came a grunt, a cry choked in the throat that uttered it. Instantly the venturer was up and. at the flap, peering outside. A figure loomed against the stars, paced slowly by with an audible step, passed and turned and passed again. It was Marc Dupre, an eagle feather, snatched from the quivering form of the guard lying in the darkness by the wall of the lodge, slanting from his head against the heavens. A little way beyond at the ashes of a fire a warrior stirred, lifted a head, and peered toward the tepee of captives; then, satisfied that all was well, lay down again to slumber. Back and forth, back and forth paced the solitary watcher. De Courtenay within was quivering from head to foot with the knowledge that something was happening. As he stood so the pacing figure halted a moment before the opening. "S-s-t!" it whispered; "warn Ma'amselle!" then walked away. Swift on the words another figure crept noiselessly to the lodge door. "M'sieu," said Edmonton Ridgar, beneath his breath, "give me the factor's shoulders. Do you take his feet and follow,—softly, for your life. Bring the maid." De Courtenay stepped back, groped for Maren, took her head in his hands, and brought her ear up to his lips. "Rescue!" he breathed; "Ridgar and Dupre. We carry our friend of the fort here. Follow." He loosed her and bent to lift McElroy. With all her courage leaping at the turn, Maren quietly raised the flap and in a moment they were all outside among the sleeping camp. With measured tread Dupre came up to them, walked with them as they moved silently back, and was on the turn when Maren touched his arm. "This way," she whispered; "straight ahead." One more step,—two,—the youth took beside her. It seemed that the heart within him was breaking in his agony. The shadows of the wood were drawing very near, the chances of escape multiplying with every step. Another sweet moment of nearness and the misty white figure beside him would fade into the darkness forever, pass forever out of his sight. Dearer than all the joys of Paradise was that black head, that wondrous face with its strength and its tenderness so adoringly mingled. The one supreme thing in all the universe was this woman,—and she was passing. With an involuntary motion he touched her softly and she stopped instantly, even at that great moment. It thrilled through him, that quick perception of his desire. "Ma'amselle," he whispered, "fare thee well!" She caught his hand swiftly, pulling him forward. "Eh?" she said. "What mean you?" There was startled anxiety in her voice and the heart of Dupre leaped exultantly. "Naught," he lied bravely, "save that I must hang behind for a moment or so to cover any sound with my sentry's step, but I cannot part from you even so small a space without,—God-speed. Hurry now, Ma'amselle! They pass from sight!" He pushed her gently after, but she turned against his hand. "Come!" she commanded; "I will not leave you!" "Nay,—how long, think you, before utter silence awakes that mob? You must be at the water's edge before I follow. Go now,—quick, for love of Heaven!" He pushed her away and turned back toward the camp, pacing slowly by the huddled heap that attested Ridgar's hand, past the empty lodge, and on to the northern turn, where lay that other figure prone upon the earth, yet still quivering in every muscle. He died hardly, this strong North warrior, and Dupre almost regretted the need, though the trapper of the Pays d'en Haut took without thought whatever of life menaced his own and considered the deed accomplishment. Back and forth, back and forth he walked the beat of the watcher and a holy joy played over his soul like a light from the beyond. He turned his mind to that hour in the woods, to the memory of the lips of Maren Le Moyne, the warm sweetness of her beaded breast, the tender affection of her embrace, and the present faded into that land of dreams wherein walk those who love greatly. Meanwhile Ridgar and De Courtenay pushed silently forward with the limp body of McElroy swinging between, while the girl stepped softly in their trail, straining her ears for sounds from the camp, and carrying the only weapon among them, a rifle which Ridgar had taken from the Indian he had killed. "To the east," she whispered, "down the little defile to the river, then south along the shore,—it is shingled and open,—to the canoe. Walk fast as you can, M'sieu." It was riskful going through the strip of woods, but when they entered the little canon that cleft a ridge of cliffs, rising impudently out of a level land, they mended their pace. Here was solid, dry rock beneath them, walls of rock on either side, and a narrow strip of star-strewn sky above. "Thank God!" Ridgar was saying, under his breath, "the distance widens!" But no sooner were the words out of his mouth than a cold chill shot through him, and Maren pushed forward with compelling hands on De Courtrnay's shoulders. "Hurry,. Her. "Only. They.". These, 'A?" "I?" said Maren, swaying where she stood. "I followed, M'sieu." "Followed? From the Assiniboine? Alone?" "Nay. There was one came with me,—a youth,—a trapper,—my comrade, my friend. He died yonder in that surging purgatory—" The tears were welling to her weary eyes. "The Nor'wester, Alfred de Courtenay, also—We only of that venture are escaped alive,—a sorry showing. The five men who man my boat belong to the brigade under Mr. Mowbray, which we met on Winnipeg. Such is our small history, M'sieu, and all we ask is your protection out of the reach of the Nakonkirhirinons. I take him back to De Seviere,—God knows if he will live to reach it. He lies so still. But I must get him back—" She ceased and passed her hand across her eyes. "I must get him back,—I must get him back." "Aye, aye. Ye come with me. Ye need a woman's hand, girl. Ye're well in yerself." There was a huskiness to the sharp voice and the man took her by the arm, turning her toward the fire and the two women. She stumbled a step or two in the short stretch. "I must go back to him, M'sieu!" she protested. "He will need—will need—broth—and a wet cloth to his bruised head—" "We'll see to him, don't ye fret. It's shlape ye need yerself. Sheila, whativer do ye think o' this! Here's a colleen shlipped through the fingers of those bow-legged signboards and fair done wid heroism an' strategy, an' Lord knows what all, an' off her feet wid tire! Do ye take her an' feed her. Put her to bed on th' blankets an' do for her like yerself knows how, darlint! 'Tis an angel unaware, I'm thinkin'— an' her on Deer River!" One of the women, a little creature with dark hair and blue eyes, Irish eyes "rubbed in with a smutty finger," came forward and looked up into Maren's stained face, streaked with her tears, her eyes dazed and all but closing with the weariness that had only laid its hand upon her in the last few moments, but whose sudden touch was heavy as lead. "Say ye so!" she said wonderingly; "a girl! So this was what caused the rumpus in the night! But come, dearie, 'tis rest ye want, sure!" She laid her and on Maren's arm and there was in its gentle touch something which broke down the last quivering strand of strength within the girl, striving to stand upright. "Yes, Madame," she said dreamily. "Yes, but he must have—he must have —broth—and a bandage,—wet" "Sure, sure,—he shall,—but come to the blankets!" As Maren went down with a long sigh, her limbs shirking the last task of straightening themselves upon the softness of the unwonted couch, the little woman looked up across her at the man with a world of questions in her face. "Poor darlin'!" she said softly. "Whativer is it, Terence?" "A heroine, if all she says be thrue, an' as unconscious of it as a new-born babe!" When Maren awoke the sun was straight overhead and some one had been calling from a distance for a very long time. "Come, come, asthore! Opin yer eyes! That's it! A little more, now. Wake up, for love av Heaven, or we'll all be overtaken be th' Injuns!" Ah! Indians! At that she opened her eyes and looked into the pretty blue ones she remembered last. The little woman was kneeling beside her with an arm about her shoulder, trying to lift her heavy head and falling short in the endeavour. Maren was too much in her muscled height for the bird-like creature. She sat up at once and looked around. The canoes were in the water, all the miscellaneous luggage had been put aboard, and every one was ready for a new start. Only herself, the blanket bed, and the little woman were unready. Just below, her own canoe, with Brilliers, Wilson, Frith, McDonald, and Alloybeau in place, waited her presence. She could see, from the elevation of the shore, the stretched form of McElroy in the bottom, a bright blanket beneath him and his fair head pillowed on a roll of leaves. A shelter of boughs hid his face, and for one moment her heart stopped while the river and the woods, the people and the boats whirled together in a senseless blur. She sprang to her feet. "Is he—" she faltered thickly, "is he—" "No, no, dearie! He is like he was, only they have fixed him a bit av a shelther from th' sun. Do ye dhrink this now," she coaxed in her pretty voice; "dhrink it, asthore,—ye'll nade it f'r th' thrip." She held up a bowl of broth, steaming and sweet as the flesh-pots of Egypt, and Maren took it from her. "But—did M'sieu—Oh, I have slept when I should have tended him!" "Ye poor girl. Dhrink,—he has been fed like a babe be me own hands. There!" There were tears in the little woman's eyes, and Maren took the bowl and drained it clear. "You are good, Madame," she said, with a long breath. "Merci! How good to those in need! But now am I right as a trivet and shamed that I must fail at the last. Are you ready?" She picked up the blankets, smiled at the tall man who came for them, and walked with them down to the canoes. "In th' big boat, lass, wid th' women," said the leader; "'tis more roomy-like." "I thank you, M'sieu, but I have my place. I cannot leave it." And she stepped in her own canoe. "Did ye iver behold such a shmile, Terence?" cried the little woman, when the flotilla had strung into shape and the green summer shores were slipping past. "'Tis like the look av th' Virgin in th' little Chapel av St. Joseph beyant Belknap's skirts,—so sad and yet as fair as light!" And so began with the slipping green shores, the airy summer sky laced with its vanity of fleecy clouds, the backward journey to safety and De Seviere. The large party travelled at forced time, short camps and long pulls, for, as the little woman told Maren at the next stop, they were hurrying south to Quebec. "Where th' ships sail out to th' risin' sun, ochone, and Home calls over th' sea,—the little green isle wid its pigs an' its shanties, its fairs an' its frolics, an' the merry face av th' Father to laugh at its weddin's an' cry over its graves. Home that might make a lass forget such a haythen land as this, though God knew if it would ever get out av th' bad dreams at night! "An' now will ye be afther tellin' us th' sthory av yer adventures, my dear?" Maren was cooking a broth of wild hen in the little pail of poor Marc Dupre, across the fire, and the little woman was busy watching a bit of bread baking on a smoothed plank. Her companion, a tall, fair-haired woman with pale eyes, light as the grey-green sheen sometimes seen on the waters before a storm, was reclining in tired idleness beside her. This woman had not spoken to Maren, but her cold eyes followed her now with an odd persistence. "Or is it too wild and sad? If it gives ye pain, don't say a word,— though, wurra! 'tis woild I am to hear!" Maren looked up, and once more the smile that was stranger to her features played over them in its old-time beauty. "Nay,—why should I not tell so good a heart as yours?" said the girl simply, and she began at the beginning and told the sorry tale through to its end. "And so he died, this young trapper with the soul of pearl, and I alone go back to De Seviere with—with M'sieu the factor," she concluded heavily. "Mother av Heavin! An' which,—forgive me lass,—which man av the three did ye love? For 'tis only love could be behind such deeds as these!" The ready tears were swimming in the Irishwoman's blue eyes, straight from her warm heart, and she was leaning forward in the intensity of her sympathy and excitement. "Which, Madame? Why, M'sieu the factor, surely." And Maren looked into the red heart of the fire. With a sudden impulse this daughter of Erin dropped her plank in the ashes, and coming swiftly forward, fell on her knees with her arms around the girl's neck. "Saints be praised!" she cried, weeping openly. "Saints be praised, ye have him safe! An' there can nothin' ha'arm ye now, with us goin' yer ways so close! An' there'll be a weddin' av coorse whin th' poor lad comes round! F'r a flip av ale I'd command Terence to turn aside an' go triumphant entry-in' to this blessid fort av yours and witness th' ceremonies!" Maren smiled sadly and laid her hand on the black head tucked into her neck. It was a caress, that touch, tender and infinitely sweet, for with the quick heart of her she knew the little woman to be of the gold of earth, and she was conscious of a longing to keep her near, who was so soon to sail "into the risin' sun" and who had been so short a time her friend. Friend, assuredly, for friendship was not a thing of time, but hearts alike, and they had turned together with the first look. So they sat a while, these two from the ends of the earth, and the warm Irish heart cleared itself of tears, like April weather, to come up laughing in another moment. "An' to think ye niver told us your name, asthore!" she said, wiping her eyes; "nor yer home place! Were ye raised in this post av haythins?" "Maren Le Moyne of Grand Portage. My father—was a smith." "Of Grand Portage! An' ye are so far inland! I am Sheila O'Halloran, av all Oirland, an' wife to Terence th' same,—yer fri'nd for always, asthore, f'r niver will I be forgettin' this time!" She turned to the fair woman, smiling and alight. "Did ye iver dhrame av such romance, my dear?" she asked. "An' isn't it just wonderful to find a real live heroine in th' wilderness?" The woman was toying with a bunch of grass, winding the slim green blades around her pale fingers, and she looked back with peculiar straightness. "It is all very wonderful, Sheila, and commands admiration, of course; but, for my part, a strange woman alone on the rivers with a party of men must have something beside her own word to vouch for her before I should take her in with open arms. You are too ready to believe anything. How do you know this venturess is not a—Jezebel?" For a moment an awful silence fell upon the three, and they could hear the myriad sounds of the evening camp round about. Then Maren, her eyes wide in amaze, said stupidly: "Eh,—Madame?" And the Irishwoman cried: "Frances! For shame!" But the other was very much composed. "I am right, all the same,—what woman of modesty would follow a man to the wilderness, confessing brazenly her love? You haven't noticed any hysterics on my part over it,—nor will you. I think it all a very open scandal." The little woman was flying into a rage of tumbled words and hopeless brogue, but Maren Le Moyne, the blood red to her temples, rose silently, took the pot of broth, and walked away, and never in her life did she hold herself so tall and straight. As she knelt beside the blanket bed of McElroy, and lifted his helpless head, her eyes were burning sombrely. "This, too?" she was saying dumbly, within herself. "Is this, too, part of the lesson of life?" And all through the days that followed, long warm days, with the songs of birds from the gliding shores, the ripple of waters beneath the prow of a canoe, she sat beside the unconscious man and looked at him with dumb yearning. For love of him,—what would she not have done, what would she not do still for love of him,—he who had sold her for a kiss; and for it there came something,—she could not define it,—something that seemed to live in the atmosphere, to taint the glory of the sunshine, to speak under every word and whisper.. "Don't ye worry, dear, he'll not die. 'Twouldn't be accordin' to th' rights av life,—not afther all ye've done f'r him. He'll opin his blessid eyes some day an' know ye, an' Heaven itself will not be like thim f'r glory." But Maren only looked tragically down upon him. What would they say, those eyes that she had thought so earnest, so all-deserving in their eager honesty, if they should open to her alone? Would they lie as they had done before, with the thought of Francette behind their blue clearness? Ah, well,—it was all in the day's march. This day at noon camp she came upon, close to a fallen tree, a wee red flower nodding on its slender stalk. She sighed and broke it. "In memory of a brave man," she said sadly. "Oh, a very brave man!" CHAPTER XXVII RETURN Eastward through the little lakes, across the portages where McElroy was carried by means of pole and blanket swung from sturdy shoulders, they went at hurried pace, and never a man of Maren's small command but watched the sadness of her face, that seemed to grow with the days and to feel an aching counterpart of it within his own heart. "Take my coat for your head, Ma'amselle," when she rested among the thwarts,—"Let me, Ma'amselle," when she would do some little task. Thus they served her from the old desire that sight of her face had ever stirred in the breasts of men, she who had never played at the game of love, nor knew its simplest trick. Southward, presently, up the rivers hurrying to the great bay at the north, and at last out upon the broad waters of Winnipeg, and never for an hour had McElroy's wandering soul come back to his suffering body. Day by day Maren tended him, feeding him as one feeds a helpless babe, shielding him from the sun by her own shadow when the branches gathered at morn withered ere noon, wetting the fair head with its waving sunburnt hair with water dipped from overside, and praying constantly for his life. As they neared the southern end, where Winnipeg narrows like the neck of a bottle, his tongue loosened from its silence and he began to babble and talk in broken sentences, and it was all about De Courtenay and a remorse that ate the troubled soul. "I owe you apologies, M'sieu,—'tis a sorry plight and I alone am to blame. And yet I have a score,—gladly would I take my will of you for that one fault,—another time,—another place. Still have I no right, save as one man who,—But I have a plan,—one may escape,—listen—when I grapple with this guard, do you make for the river—with all speed— My God! My God! M'sieu! Why did you not run?" And so he muttered and sighed, and Maren bent above with wide eyes. Something there was between these two, some enmity that followed even into the land of shadows and yet held them gentlemen through it all, offering and rejecting some chance of escape. A weary, weary tangle. Again he would fancy himself back in De Seviere and always there was De Courtenay with his smiling face and tantalizing beauty. "Welcome, M'sieu, to our post! Seldom do we meet so gay a guest!" Often the wandering words would stumble among his accounts at the factory and he would give directions to the clerks, and then Ridgar's name would come, only to carry him instantly to the camp of the savages on Deer River. "Edmonton,—friend of my heart,—alone! and you pass me without speech! Ah,—that look! That look! I'd stake my soul—" And once in the cool twilight of an ended day, with the tall trees above and the river lapping below, he cried out her name, "Maren!" and once again, "Maren!" with a world of change between the two words. The first plunged the girl's heart to her throat with its passion, the second chilled her like a cool wind. And all at once he said, after a pause, "What is it, little one?" So passed the days of the return. Hour by hour the bright waters of the lake spoke to the girl with voices of regret and sadness. The blue sky above seemed to mirror the dark face of Marc Dupre, the wind from the shores to be his low voice, each passing shadow among the trees his slender figure returning from the hunt for her. Her heart was sore that Fate had willed it so, and yet, looking down at the face of this man at her feet, she knew it had to be and that she would do again all that she had done. And ever before her passed the scornful face of the fair woman who had set the little undertone to all the world. It troubled her, and for hours together she sat in silence reasoning it all out, while Mowbray's men dipped the shining blades and here and there the voyageurs and Indians who wore no feathers sang snatches of song, now a chanson of the trail and rapid, again a wordless monotony of savage notes. The evening camps were short spaces of blessed quietude and converse when Sheila O'Halloran sat beside her and they talked of many things,— chiefly the dear little Island whose green sod would soon again receive the feet of "herself an' Terence." "'Tis thankful I am, me dear, to be out av this forsaken land alive wid me hair on me head instid av on a hoop painted green wid little red arrows on th' stretched shkin inside! 'Tis a sorry counthry an' fit f'r no woman, but whin Terence must come on some mysterious business av th' government,—an' niver, till this minute, accushla, do I know whut it is,—a cryin' shame 'tis, too, wid me, his devoted wife!—I must come along or die. Wurra! Many's th' time I thought I'd do th' thrick here! But now are th' dangers passin' wid ivery mile,—hark to th' men singin'! 'Tis bad business whin men do not sing at th' day's work. 'Tis glad I am f'r safe deliverance from that counthry av nightmares wid its outlandish name,—Athabasca,—where Terence must moon from post to post av th' Hudson's Bay—" "Athabasca!" Maren's head was up and she was looking at the little woman with an eager wistfulness. "The Land of the Whispering Hills!" "Thrue,—'tis th' Injun word,—but a woild, woild land f'r all that." "But beautiful, Madame,—oh! it is beautiful, is it not?" "Fair,—wid high hills an' a great blue lake an' woildness!—Ah!" But the tall leader was calling and camp was breaking for another stretch. And under the travelling stars of that night there awoke in the heart of the maid of the trail something of the old love, the old longing for that goal of her life's ambition. She had turned aside from it, only to be taught a lesson whose scars would stay deep in her soul so long as life lasted. At last came an hour when the party under O'Halloran must turn to the east, where the bottle-neck of Winnipeg split in two, going down that well-worn way which led to Lake of the Woods, Rainy River, and at last to the wide lakes, whose sparkling waves would waft them on to the great outside world. There was a scene at parting, when the warmhearted Irishwoman clung to Maren and wept against her bosom, calling her all the hundred words for "darling" in the Celtic and vowing to remember her always. The fair woman, wife of a Scotchman who acted as some sort of secretary to O'Halloran, sat apart in cold silence. "M'sieu," said Maren, at the last, "I have no words to thank you for this that you have done. I but cast it into the balance of God, which must hang heavy with your goodness." She had given her hand to the leader, and that impulsive son of the ould sod kissed it gallantly. "'Tis little we did, lass, for you and your poor lad yonder, and 'twas in our hearts to do more. But here's luck to you both,—an early weddin' an' sturdy sons!" And, as the morning sun glittered on the ripples of the departing boats, Maren stood long looking after them, a mist in her eyes and her full lips quivering. She looked until the gathering dimness hid the waving kerchief of the only woman friend who had ever truly reached her heart. Then she sat down and took up a paddle. "Last lap, Messieurs," she said, above the mutter of McElroy at her feet, and they turned toward where the familiar river came rushing to the lake. The summer lay heavy on the land when they reached the Assiniboine. Deep green of the forests, deep green of fern and bush and understuff, told of the full tide of the year. Here and there a leaf trailed in the shallows, yellow as gold in an early death. She thought of the spring, so long past, when she had first come into this sweet land, and it seemed like another time, another life, another person. This day at dusk they passed the hidden cove where she had found Marc Dupre waiting to build her fire. The abandoned canoe still lay hidden where he left it. Cool blue dawn, hushed and wide-reaching, still with that stillness which precedes the sunrise, lay over the river, when the lone canoe rounded the lower bend and Anders McElroy, factor of Fort de Seviere, came back to his own again. In the prow there knelt a weary figure in a soiled and sun-bleached garment of doeskin, its glittering plastron of bright beads broken here and there, the ragged ends of sinews hanging as they were left by briar and branch, and the haggard eyes went with eager swiftness to the stockade standing in its grim invincibility facing the east. The row of wonted canoes lay upturned upon the shelving shore at the landing, the half-moon at the right still glowered with its puny cannon which had spoken no word to save their master on that fateful day, and all things looked as if but a day had passed between. The great gate with its studded breast was closed, the bastions at the corners were empty of watchers, for peace folded its wings above the past. Without sound the boat cut up to the landing, Brilliers leaped out and steadied it to place, and Maren stepped once more upon the familiar slope. They lifted McElroy, swinging in his blanket, and the tread of the moccasined feet was hollow on the planks. Thus there passed up to the gate of De Seviere a triumphal procession of victory, whose heart was heavy within it, and whose leader in her tattered dress was the saddest sight of all. She raised her hand and beat upon the gate, and a voice cried, "Who comes?" "Open, my brother," she called, for the voice was that of Henri Baptiste, whose turn at the gate it was. There was an ejaculation, a swift rattle of chains, and the heavy portal swung back, while the blanched face of young Henri stared into the dawn. Maren motioned to the men and they stepped in with their burden. "Holy Mary! Maren! Maren! Maren!" cried Henri Baptiste, and took both her arms in a gripping clasp. He looked into her face with fear and wonder, as if the girl had returned from the dead, while joy unspeakable began to lighten his features. "Sister! Holy Mary!" And then, when the touch of her in the flesh had dispelled his first horror, when the sight of the factor swinging grotesquely in the blanket had taken on the sense of reality, he raised his voice in a stentorian call. From every door it brought the populace running, half-dressed and startled, and in scant space a ring of faces stared upon the strangers in stupid awe. "Ma'amselle Le Moyne!" they whispered, fearfully. "Mother of Heaven! The factor!" "Our factor! Out of the hands of Death!" "Mon Dieu! One of them! And the maid!" And in the midst of the awed and hushed excitement that was growing with each passing moment, there cut the voice of McElroy, babbling from the blanket. "Throw!. "Yes?" !" "Then," whispered Maren, apart from the clerk's listening ears, "take you this letter. Keep it until M'sieu the factor is in his right mind, then give it him with your own hands. If he—if he should—burn it, Rette, unopened." And she gave into the woman's keeping the only letter she had ever written to a man. It was in French, and the script was fine and finished. This was what she had said, alone in the little room with its eastern window at the end of the Baptiste cabin: "MONSIEUR MCELROY, Factor of Fort de Seviere, ave atque vale." (The tender word of Father Tenau when he blessed her that last time in Grand Portage) "The time has come when I must take my people out of your post, must break their contract and their word. Forgive them, M'sieu, and lay not the fault to them, for I, and I only, am to blame. But the time I promised is too long.... I can no longer hold back the tide of longing which drives me to that land of which we spoke once...." (Here there was a break in the letter, a smudge on the page, as if the quill had caught the paper or a drop of moisture run into the ink.) "I must go forward, and at once, to the Athabasca. The great quest is strong at my heartstrings again. I thank you, M'sieu, for all kindness done my people, and I promise that, should fortune favour them and me in that far land to which we journey, they shall send what trade lies with them to De Seviere. For one thing I ask,—if it be possible, M'sieu, give to certain men who will be found by word to Mr. Mowbray of York, such stipend as you can, for they were good and faithful,— namely, Frith and Wilson and McDonald, Brilliers and Alloybeau.... Adieu, M'sieu. God send you health. (Signed) "MAREN LE MOYNE, of Grand Portage." Laroux was worth his word. Forty-eight hours later there stood at the portal of Fort de Seviere, ready for the trail, that small band of wanderers who had come into it in the early spring. They were fuller of hope, more eager to face the wilderness than on that day, for joy after sorrow sat blithely on their faces, turned to the tall young woman at their head. And they were fully equipped for travel. Three canoes held wealth of supplies, while six huskies whined in leash, nervous under new masters, touched with the knowledge of coming change. Not a man in De Seviere who had not given gladly, nay, vied with his neighbour to give, to the helping of this woman. Had they not their factor back from death and its torments? There was God-speed and hearty handclasp from the men, and Maren smiled into their faces, reading their simple hearts. With the women it was different. They hung, gazing, on the outskirts, calling farewell to Marie, who wept a little at sight of her deserted cabin, to Anon and Mora and Ninette, but there was no reflection of the feeling of their masters for this girl with her weary beauty, her steady, half-tragic eyes. Nor was there great regret over Micene. Too sharp had been her tongue, too keen her perception of their faults. True, the autumn was near at hand. Winter would come with its myriad foes before they could hope to be ready for it, and Maren, looking far ahead, saw it and its dangers, and her heart sickened a bit with the thought of her people; but the thing within was stronger than all else. She must leave De Seviere at once. Therefore, she raised her head with her face to the west. It was early dawn again. It seemed that it had ever been dawn when fateful things had happened in this post, every log and stone of which was suddenly dear to her. She stood in the opened gate and looked back upon it, on the cabins, the well where De Courtenay had placed his first red flower in her hair, the storehouses, and the factory. The factory! With sight of it once more the wave of anguish swept over her. She saw the small plain room at the back, the figure of a man prone in his helplessness, a fair head with blue eyes, pleading in their honest clearness, and her lips trembled. "Ready?" she said, and the deep voice slipped unsteadily. "Aye," answered Prix Laroux, and picked up the last pack of chattels. At that moment there was a flurry among the pressing men around, a sound above the many voices wishing them luck, and little Francette broke through. "Ma'amselle!" she cried, looking up into Maren's eyes with conflicting expressions on her small face, misery and solemn joy and hatred that strove to soften itself beneath a better emotion; "Ma'amselle,—I would thank you! Oh, bon Dieu! I am not all bad! Here" She seized Loup by the ears and dragged him forward, snarling. "Take him, Ma'amselle! I love him! Do you take him,—and—and-understand!" All her red-rose beauty had gone from the little maid along with her dancing lightness. These long weeks had turned her into a woman with a woman's heart. They drew back and looked on with wonder, and then smiles of amusement, but Maren, gazing into the tragic little face, saw deeper. "Why,—little one," she said gently, unconsciously falling into McElroy's words after a trick she had, "I—I understand. You need not give up the dog,—I know what you would say." "No!" cried Francette fiercely. "No! Take him! Take him! I will make you take him! I will!" She was whimpering, and Maren, stooping, laid a hand on the husky's collar. Without more words she turned and followed her people down to the landing, half-dragging the brute, who hung back and turned his giant head to the little maid, standing with her hands over her face. He snarled and bit at Maren's wrist, but she picked him up and flung him, half-dragging on the ground, for he was a mighty beast, into the first canoe. "Push off," she said; and, taking her place in the prow, she raised her face to the cool blue sky, and turned once more to that West whose voice had called from her cradle, but, with some strange perversity of fate, her heart drew back to the squat stockade slowly fading into the distance. The sweet wind of the Whispering Hills was very faint on her soul. CHAPTER XXIX BITTER ALOES. Glorious fires burned in the cooling skies and the sweet breath of autumn tingled in the air. There was comment, and the shaking of heads among the old trappers. The wrong time of year to take the long trail with women,—the wrong time, but, bon Dieu! who was to stop that woman with the sombre eyes? Voila! A woman to thrill the blood in any man who was still warm with life! "Love awakened in her would be a thing of flame and fury, they had thought, that long past day," thought Pierre Garcon to himself; "he and that friend of his heart, Marc Dupre,—it had been a thing of patient servitude, of transcendent daring, and Marc Dupre; ah! He had been a part of it. But there was much of mystery about it all, and no one knew, nor would any know, all that it had meant." So the changes came and passed, and when Anders McElroy again opened his eyes to reason, the world was white against the pane of the one window of the little room,—the long snows had arrived. Winter was upon the Northland. It was on a night when the wind without howled like a lost soul shut out from the universe and the sucking of the chimney-throat roared to heaven. Edmonton Ridgar sat at the hearth gazing into the leaping flames, and Rette de Lancy passed and repassed among the shifting shadows, busy at some kindly task. Long he lay, this man returned from the Borderland of the Unknown, and stared weakly at the familiar sights that were yet touched with a puzzling strangeness. It seemed that this was all as it should be, and yet there was something lacking,—a great gap, whose images and happenings were wiped out as a cloth wipes clean a slate,—a space of darkness, of blankness, whose empty void held prescience of some great sadness. He lay on his side facing the fire, and twice he thought to speak to Ridgar with a question of this strangeness, and each time he was conscious of a vast surprise that the man did not answer. His lips, so long unused to sane direction, had made no sound in the roar of the night. And then Ridgar, drawn by that intangible sense of eyes upon him, raised his head; and, as their glances met, that great void flashed suddenly into full panoply of life peopled with a ring of painted faces against the background of a night forest, a leaping fire, and the heroic figure of a tall woman who stood in the dancing light and threw a hatchet at a painted post. Rid." Ridgar paused a moment, and his eyes took on a look of distant things "Have you not wondered how it was, lad, that a man should live long as I have lived in the wilderness, alone, without ties other than those which bind him to the Great Company, without love of woman, without the joy of children?...I have not always lived so..... She lived it one day,...nay, died it—when I had some words with a young man of the tribe, who drew a spear before I knew what he meant and hurled it at me. She...leaped between. God!" He ceased again, and McElroy could hear his breathing, see the whitened knuckles of his hands grasping the poker from the hearth where he had absently stirred the leaping fire. "It went quite through her,—a foot beyond her swelling breast, full for my only child, unborn.... She was Negansahima's daughter.... We mourned together, the old chief and I, and our hearts were bound close as the tree and its bark. In a far high hill of the Pays d'en Haut we put her to sleep with that last look of love on her dark face...and we made a pact to lie beside her when our time should come, he who out- lived the other to see the rites of the Death Feast. He has joined her. I saw his rites. So for this end, reaching far back, I did not return when you came back to De Seviere, going on with that rabble who dared not harm me who am to share the Sleep of Chiefs some day.... "So! "Now for the rest. I know no more of Maren Le Moyne than that first tragic sight of her, hauled into the light by the brute DesCaut. I only know that she stood before those savages as fearless as a lioness and threw again and again, her black head up and sane, her young body under her own command in every taut cord and muscle, and that again and again and yet again the flying hatchet landed in its own cleft,—a wonderful performance!—putting off with coolness and skill the death they would see her decide, choosing neither man of you." "But," cried McElroy, "it was De Courtenay she came to see,—to save,— to die with,—she loved him, man!" "Aye,—maybe. But I know only that that young trapper, Marc Dupre, gave his life as gallantly as might be to cover our retreat while we, the Nor'wester and I, slipping among the sleepers, carried you to the river; that they woke, those devils, before we had cleared the little gorge, and that M'sieu de Courtenay, brave man and gay cavalier, gave your knees to this woman who helped me get you to the canoe, himself taking the only gun and meeting what fate was his in the narrow seam among the rocks. She had with her men of Mr. Mowbray's brigade, that she had got somewhere on Winnipeg, and we put you in their waiting canoe. She was dragged in among the thwarts,—while I—slipped back among the shadows, circled the camp, and was at my death-watch inside the big tepee when peering eyes looked in. I saw no more of the dashing Nor'wester, save a flash of long gold curls at a headman's belt. What fate was meted out to him was swift and therefore merciful. Peace be to him! "No more I know, my friend, save that, when I returned to De Seviere, I found you ill with some fever of the brain." "But, Ridgar, for love of Heaven, what of Maren?" "She had brought you here, and Rette says the women hung off from her and laughed in corners, whispering and talking, and that her face was worn and greatly changed, as if with some deep sorrow." McElroy turned his head upon the pillow and weak tears smarted under his lids. "Me! It was I she saved when it was I who slew her lover! God forgive me, for I cannot forgive myself!" "Nay, boy, hush! It is all as God wills. We are but shuttles in the web of this tangled life." "But—tell me,—what does she now? How looks her dear face?" Ridgar was silent a moment, and McElroy repeated his question, with his face still turned away: "Does she pass among them,—the vipers? Does she seem to care for life at all now?" "Lad," said Ridgar gently, "I know not, for she is gone." "Gone!" The pale man on the pillow sprang upright, staring at the other with open mouth. "Aye, softly, boy; softly! She has been gone these many weeks; even while summer was here she gathered her people, outfitted by our men, all of whom were so glad for your deliverance that they gave readily to their debt, and took up again her long trail to the Athabasca. Rette, I believe, has a letter which she left for you.... Would you read it now?" McElroy nodded dumbly, and Ridgar went out in the night to Rette's cabin for this last link between the factor and the woman he loved. When he returned, and McElroy had taken it in his shaking hands, he sat down and turned his face to the fire. There was silence while the flames crackled and the chimney roared, and presently the factor said heavily: "I cannot! Read..." So Ridgar, bending in the light, read aloud Maren's letter. At its end the man on the bed turned his face to the wall and spoke no more. From that time forth the tide of returning life in him stopped sluggishly, as if the locks were set in some ocean-tapping channel. The bleakness of the cold north winter was in his heart and life was barren as the eastern meadows. So passed the days and the weeks, with quip and jest from Ridgar, whose eyes wore a puzzled expression; with such coddling and coaxing from Rette as would have spoiled a well man, and, with not the least to be counted, daily visits to the factory of the little Francette, who defied the populace and came openly. With returned consciousness to McElroy, there came back to the little maid much of her damask beauty. The pretty cheeks bloomed again and she was like some bright butterfly flitting about the bare room in her red kirtle. Sometimes McElroy would smile, watching her play with a young bob-cat, which some trapper had brought her from the woods, and whose savage playfulness seemed to be held in leash under her small hands. The creature would mouth and fawn upon her, taking her cuffs and slaps, and follow her about like a dog. Rette tolerated the two with a bad grace, for, since the day when Maren Le Moyne had stood at the door with her haggard beauty so wistfully sad, her sympathies had been all with the strange girl of Grand Portage. Light and flitting, sparkling as an elf, full to the brim of laughter and light, little Francette was playing the deepest game of her life. With the cunning of a woman she was trying to woo this man back to the joy of earth, to wind herself into his heart, and so to fill his hours with her brightness that he would come to need her always. So she came by day and day, and now it would be some steaming dainty cooked at her father's hearth by her own hands, again a branch of the fir-tree coated with ice and sparkling with a million gems, that she brought into the dull blankness of the room, and with her there always came a fresh sweet breath of the winter world without. McElroy smiled at her pretty conceits, her babbling talk, her gambols, and her gifts. "What have you done with Loup, little one?" he asked, one day. "Does he wait on the steps to growl at this usurper purring at your heels?" The little maid grew pearly white and looked away at Rette fearfully, as if at sudden loss, in danger of some betrayal. "Nay," she said, "Loup...is an ingrate. He has ceased to care." And always after she avoided aught that could excite mention of the dog. But, in spite of all her effort, McElroy lay week after week in the back room, looking for hours together into the red heart of the fire, silent, uncomplaining, in no apparent pain, but shiftless as an Indian in the matter of life. The business of the factory was brought to him nightly by Ridgar and the young clerk Gifford, and he would look over things and make a few suggestions, dispose of this and that as a matter of course and fall back into his lethargy. "What think you, M'sieu?" asked Rette anxiously, of Ridgar. "Is there naught to stir him from these hours of dulness?" "I know not, Rette. Would I did! The surgeon says there is nothing wrong with the man, save lack of desire to live. He has lost the love of life." And so it seemed. Weeks dragged themselves by and months rolled after them, and still he lay in a great weakness that held his strong limbs as in a vice. Winter was roaring itself away with tearing winds, with snow that fell and drifted against the stockade wall, and fell again, with vast silences and cold that glazed the surface of the world with ice. January dragged slowly by, with dances for the young couples in the cabins at nights, and little Francette, for the first time in her life, refused to share in the merry-making of which she had always been the heart and soul. Instead, she lay awake in the attic of the Moline cabin and cried in her hands, listening to the whirl of the nights without. Alone in those long vigils instinct was telling her that she had failed. Failed utterly! The young factor cared no more for her than on that night in spring when he had kissed her and told her to "play in the sunshine and think no more of him." She had played for a man and failed. Moreover, she had not played fairly, and for her wickedness he lay now as he had lain so long, drifting slowly but surely toward that land of shadows whence there is no return. She clinched her small hands in the darkness and wept, and they were woman's tears. Back to her led all the threads of tragedy, of death and danger and heartbreak, that had so hopelessly tangled themselves in Fort de Seviere. But for that one hour at the factory steps what time she lay in McElroy's arms and saw Maren Le Moyne pause at the corner, all would be well. Young Marc, Dupre would be singing his gay French songs with his red cap tilted on his curls, that handsome Nor'wester of the Saskatchewan would be going his merry way, loving here and there,—instead of bleaching their bones in some distant forest, as the whispers said; and, last of all, this man she loved with all the intensity of her soul would be brown and strong with life, not the weary wreck of a man who gazed into the fire and would not get well. So the long nights took toll of the little Francette and a purpose grew in her chastened heart, a purpose far too big for it. At last the purpose blossomed into full maturity, hastened by the dark shadows that were beginning to spread beneath McElroy's hopeless eyes, as if the spirit, so little in the body, were already leaving it to its earthly end, and one day at dusk, trembling and afraid, she went to the factory for the last time. "Rette," she said plaintively, "will you leave me alone with M'sieu the factor for an hour? Think what you will," she added fiercely, as she saw the woman's look; "tell all the populace! I care not! Only give me one hour! Mon Dieu! A little space to pay the debt of life! Leave me, Rette, as you hope for Heaven!" And Rette, wondering and vaguely touched, complied. McElroy was looking, after his habit, at the leaping flames and his thin hands played absently and constantly with the covering of the bed, when the door opened and closed and the little maid stood shrinking against it. He did not look up for long, thinking, if his dull mind could form a thought through his melancholy dreams, that Ridgar had come in. At last a sigh that was like a gasp pierced his lethargy and he raised his eyes. She: "Oh! O God! Rette!" She screamed and sprang up, to run back and crouch against the empty chair beside the hearth. The figure upon the bed, half-risen, worked its lips and then fell back, and the little maid raised her voice and screamed again and again in mortal terror. It brought Rette running from where she had waited in the trading-room. She raised him, and her face was red with rage. "What have you done! You evil cat! What have you done to the man?" But McElroy's breast had heaved with a great breath, sweet as the wind over a harvest field to a tired man, and he looked up at Rette with eyes that seemed to be suddenly flooded with life. "Done?" he whispered; "done, Rette? The child has given me salvation!" And then he held out a shaking, thin hand. "Come here," he said softly; "come here." Fearful, trembling, tear-stained Francette crept back, and the factor took both her small hands in a tender clasp: "I thank you, little one," he said, "from my heart I thank you,—there is nothing to forgive. We are all sinners through the only bit of Heaven we possess,—love. Go, little one, and cease this crying. Know that I shall sleep this night in a mighty peace. You have given me— life!" CHAPTER XXX THE LAND OF THE WHISPERING HILLS Springtime once more kissed all the wilderness into tender green. From the depths of the forest, lacing its myriad branches in finest fluff of young leaves, came the old-new sound of birds at the mating, rivers and tiny streams rushed and tumbled to the lakes, and overhead a sky as blue and sweet as the eyes of loved rocked its baby clouds in cradles of fresh winds. They blew over vast reaches of forest and plain, these winds, wimpling the new grass with playful fingers, and whispering in the ear of bird and bee and flower that spring was come once more. They came from the west, sweeping over sweet high meadows, over rushing streams, and down from fair plateaus, and their breath was fresh and cool with promise to one who faced them, eager in his hope, for they brought the virgin sweetness of the Land of the Whispering Hills. By streams, clear as crystal, he passed with a swinging stride, this lean young man in the buckskins of the forest traveller, over meadows soft in their green carpets, through woodlands whose flecked sunshine quivered and shook on the young moss beneath, and ever his face was lifted to the west with undying hope, with calmness of faith, and that great joy which is humble in its splendour. Thus he swung forward all through the pleasant hours of that last day. Before him, raised against the sky, there loomed the magic Hills themselves, fair to the eye of man, clothed in the green of blowing grass and girdled about below with the encroaching forest. At dusk he set foot upon their swelling slopes, and knew himself to be near the goal of his heart's desire. Over. At the head of the mound towered a gigantic totem pole, carved and painted with scenes of a most minute history, while at the foot of a smaller stake, alike carved and coloured, bore, one upon another, twelve rings of bone, each one of which stood for the circle of a year. Crossed and shielded with infinite care, in the centre there lay a set of smith's tools, crudely fashioned and well worn, tongs and a heavy hammer and a small anvil. But beyond all this, a thing that held his wondering gaze and brought the fur cap from his head, there stood an altar, rude as the rest, but still an altar of God, with a black iron crucifix, whose pale ivory Christ glimmered in the gathering evening, upright upon it. Before the crucifix, and at either end, were the burnt-out evidences of tallow candles, while flanking the holy Symbol there stood two wooden crosses, their pieces held together by bindings of thread. Before one there lay a heap of little withered flowers, frail things of the forest and the spring, and every one was snowy white. Across the other hung a solitary blossom, first of its kind to open its passionate eyes to the sun, and it was blood-red, counterpart of that wee star which Alfred de Courtenay had snatched from the stockade wall one day in another spring. The earnest blue eyes of the man were very grave, touched with a deep tenderness. "Maren!" he whispered reverently; "maid of the splendid heart!" So deep was he in contemplation of the things before him and his own holy thoughts that he did not hear a soft sound behind him, the fall of a light step. A breath that was half a gasp turned him on his heel. Leaning through the parted curtain of the hanging vines, one hand at her throat, the other holding three candles, and her dark eyes wide above her thinned brown cheeks, she stood herself. At her knee there hung the heavy head of the great dog, Loup. She, as she had been when first he looked upon her, yet intangibly changed, the same yet not the same. They stood in silence and looked into each other's eyes as if void of speech, of motion, held by the mighty yearning that must look and look with insatiable intensity, the half unreal reality of the moment. And then the stopped breath in the girl's throat caught itself with a little sound that broke the spell. The man sprang forward and took her in his arms, not passionately, strongly, as he had done once before, but with a love so high, so chastened, so humble that it gentled his touch to reverence. "I have come, Maren," he said brokenly; "I have followed you to the land you sought. Maid of my heart! My soul!" Without words, without question, she yielded herself to his embrace, lifted her face to him and gave into his keeping that which was his from the beginning. "Mother Mary! I thank Thee!" he heard her whisper, and when he loosed her to look once more into her level eyes, they were dim with tears. . . . . . . . . . Night!"
http://vickysands.com/01/11/351.htm
CC-MAIN-2018-05
refinedweb
43,269
85.02
I am unable to bind an existing service to my new cluster. Running the following command displays the available services as expected. bx service list I then attempt to bind one of the existing services to my new cluster called myfirstcluster, but it fails to bind bx cs cluster-service-bind myfirstcluster default rabbitmqservice The error response is as follows: Binding service instance to namespace... FAILED The specified IBM Cloud service could not be found. If you just created the service, wait a little while and then try to bind it again. To view available IBM Cloud service instances, run 'bx service list'. (E0023) Incident ID: c076ea66-0ee1-4a40-8db6-5a8fb880b177 Note the service exists and has previously been bound to a cloudfoundy app, I am now attempting to bind the service to a k8 cluster. Hi there @cnid. Just to get the basics out of the way, have you tried everything in these steps already? What region did this occur in? Also, when did you create your account? 135 people are following this question. Unable to bind a service to a K8S Cluster 2 Answers Ingress for Bluemix standard kubernetes cluster not working. 5 Answers Error registering Datapower Gateway IDG.2018.4.1.1 in API Connect 2018.1 0 Answers Can we enable ssl-passthrough 1 Answer How approach the public id ( approach web service ) of kubernetes cluster ? 2 Answers
https://developer.ibm.com/answers/questions/437735/$%7Bauthor.url%7D/
CC-MAIN-2019-30
refinedweb
232
65.93
Hi body, i just want to test gets with rspec, I see something on stackoverflow but doest work to me I would like to know too When i run the tests a method that should be tested has called gets method and it run when i test, so i have to push ENTER to pass the gets method ever time i test the app. Someone know how can i solve this? Thanks everone. Hi body, i just want to test gets with rspec, I see something on Hallo Body? Who? Some Body? Anyway, if you would like help, then you really need to include your program and the error message. Sounds also, like a look at the documentation for gets would help: Ruby’s irb is also a useful tool to try things out with, especially when you just want to see what a core method or class does. $ irb irb(main):001:0> gets this that the other => “this that the other\n” irb(main):002:0 gets _get_s a _s_tring, mostly from the user. The input string is terminated by pressing the return key. puts _put_s a _s_tring, mostly to the user. You probably don’t need to test gets, but you may want to test what your program is doing to the input from gets, which is a good reason to separate this part of your program into two methods, the first gets the user input, the second method takes a string argument and does something to it. This second function can be tested. RSpec.describe TalkBack do it ‘says everything backwards’ do expect(talk(‘stressed’)).to eql(‘desserts’) end end – class TalkBack def getStringFromUser talk(gets.chomp) end def talk(user_said) “#{user_said.reversed}” end end
https://www.ruby-forum.com/t/test-gets-with-rspec/244817
CC-MAIN-2021-49
refinedweb
289
77.16
Code. Collaborate. Organize. No Limits. Try it Today. Some of the following code is adapted from projects I’ve worked on and some is code I specifically wrote to help people studying for the Sun Certified Programmer Exam for Java 6 to see how well they understood a topic. Let’s start with a relatively easy one and save the tougher ones for later. While working on a project, I had to convert a String variable to Long. Knowing the Long class (like the other wrapper classes for primitives) has static methods that do just the thing, I started typing in my IDE and found that there are four methods that might do the job. Here’s a list of the candidates: String Long Long static Long.decode(String nm) Long.getLong(String nm) Long.parseLong(String s) Long.valueOf(String s) Given that each of these takes a String and returns a Long, what does the following code return? (Note: The longValue() method returns the value of the Long object as a primitive long.) longValue() public long getValueFromString() { String aLong = “23”; Long retrievedLong = Long.getLong( aLong ); return retrievedLong.longValue(); } Here’s the list of possible answers: Before you continue reading, what do you think the right answer is? Finished so soon? Alright then, let’s take a look at the possible answers and see how you did.Now it seems reasonable that Long’s getLong() method should return the value of the String as a Long, so answer ‘A’ looks pretty good. Then again, if it were that easy why would I bother including this? Answer ‘B’ doesn’t seem very reasonable - unless getLong() isn’t really converting the value of the String. So that leaves answer ‘C’ as the primary suspect. It’s not obvious and seems rather vague. It’s just the sort of answer you might expect from a puzzle - which could be reason enough to go back to answer ‘A’. <grin> getLong() String OK, enough thinking. Time to give you the answer so we can keep going - the correct answer is ‘C’. - it depends. It turns out that Long’s getLong() method doesn’t try to convert the value of the passed in String directly. Instead, it takes the value and looks for a System property with the same name. If it finds one, it retrieves the associated value and converts that to a Long. Which means that what the getLongValue() method returns depends on the value of the System property “23″. System getLongValue() 23 So what happens if there is no System property named “23″? In that case, getLong() will return a null and the getValueFromString() method will throw a NullPointerException when it tries to call the getValue() method because retrievedLong is null. Ouch! null getValueFromString() NullPointerException getValue() retrievedLong null I found this the hard way. I needed to convert a String and picked a likely method from the list provided by my IDE. I was greatly surprised when my unit test failed, so I looked up the JavaDoc on it and realized my mistake. There are a two morals to this story: Ready for the next puzzle? It’s called... I was modifying some legacy code (defined as any code with no unit tests) and found something unexpected when I tried to use it. The original code was rather complicated (possibly because there were no tests), but this simplified version has the same odd behavior. public class Greeting { static { initName(); } static String name = "Sue"; static Test instance = new Test(); public static String getName() { return name; } private static void initName() { name = "Bond, James Bond"; } public static void main(String[] args) { System.out.println("My name is " + Test.getName() + "."); } } Before we get to the question, let’s take a look at the Greeting class. There’s one static variable, three static methods and one static initializer. (That’s the block of code that starts with “static” and calls the initName() method.) Other than the static initializer, it looks like a pretty simple class that's easy to understand, doesn’t it? Greeting static initName() In case you’re not familiar with static initializers, let me paraphrase a bit of Sun’s Java Tutorial: "A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. They can appear anywhere in the class body, and the Java runtime guarantees they are called in the order in which they appear in the source code." "A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. They can appear anywhere in the class body, and the Java runtime guarantees they are called in the order in which they appear in the source code." That sounds kind of cool, but what’s the point? Why would you use one? Well, a static initializer executes when the class is loaded into memory and it is normally used to do some kind of one-time processing for the class. In this case, the initializer calls the initName() method when the Greeting class is loaded into memory -- before it’s main() method executes. initName() main() So, getting back to the question at hand (What does the above code do when you run the class?), here are the possible answers: I recommend taking some time to figure out your own answer before reading any further. You’ll get more out of this if you do. Don’t worry, I don’t mind the wait. Ready to look at the answers? Good.First things first. Answer C, "Nothing, because it doesn't compile" is not correct. I just included it so I can tell you that I don’t like that kind of answer on a puzzle, or Java certification exam for that matter. While it may have been a useful skill years ago, when our only tools were stone knives and bearskins, we’ve had better tools for so long now that it seems unreasonable to ask a question where “it won’t compile” is the right answer. OK, enough ranting - back to the puzzle. What about answer B? Well, having read this far you should know the whole point of this is to show you code that looks simple but behaves strangely. So you probably didn’t pick answer B , and you would be right in doing so. The code does not print “My name is Bond, James Bond.”What about the ever popular “None of the above.” Sorry, not this time. Answer D is not correct either. By the process of elimination, the correct answer must be A. But it doesn’t make sense for it to print “My name is Sue.” - does it? Don't trust me on this, copy the code into a file and run it yourself, then come back for the explanation. To say I was surprised when I saw this for the first time would be an understatement. I didn’t believe the results; it didn’t make any sense to me so I stepped through it in the debugger. If you do the same, you can see that the initName() method does get called before the main() method, and that when initName() finishes, the value of “name” is “Bond, James Bond” - just as we expected. name Bond, James Bond So what’s going on? How does “name” get set to “Sue”? If you continue stepping through the code, you’ll find out. Notice that right after the static initializer, we declare and initialize the “name” variable. Which seems kind of odd because the initName() method already set “name” to a value - so it must already exist, right? Sue Sort of. The compiler sets aside space for the variable and includes code to initialize it. But, because “name” is a static variable, its initialization happens when the class is loaded into memory instead of when the class constructor is called. It also appears that, like a static initializer, static variable initialization happens “in the order in which it appears in the source code.” So after the static initializer is called, the code that declares and initializes “name” to “Sue” executes and overwrites the value we expected to see. And that is why answer A is correct. Believe it, or not. For the final puzzle, let’s take a look at something I found while preparing to lead a study group focusing on the Sun Certified Programmer Exam for Java 6. There’s not much code, but this puzzle involves autoboxing and unboxing combined with the prefix increment operator (just to make it interesting) as we compare two variables. public class Bitwise { public static void main(String[] args) { Integer a = 5; Integer b = 5; System.out.println(++a == ++b); Integer c = 12345; Integer d = 12345; System.out.println(++c == ++d); } } What does this code do when you run it? true false OK, let’s work through this. All the variables are of type Integer, so when we compare them using ‘==’, we’re really comparing the reference values, not their primitive values. So even though ‘a’ and ‘b’ have the same primitive values (as do ‘c’ and ‘d’), they’re each referring to a new Integer instance - thanks to autoboxing. That means the references should be different and the ‘==’ comparison should resolve to ‘false’, which means the answer should be B. Integer == a b c d Integer false’ Obviously that would be too easy, so let’s look at the other possibilities. While it doesn’t make sense that two newly created Integer instances would have the same reference, answer A is consistent and that seems a little more plausible than answers C and D. While it may make sense, the truth is that answer A is not correct and neither is answer B. What? Am I telling you that sometimes you can create two new Integer instances and they’ll point to the same object in memory? Yes, that’s exactly what I’m saying. You might feel better running the code and looking at the results before you continue reading, just so you know I’m not making this up. What’s happening is that in order to save memory (according to Kathy Sierra and Bert Bates - authors of the SCJP 6 Study Guide), Java reuses wrapper objects when the primitive value fits in a byte. So if two Booleans or Bytes have the same primitive value, their reference is the same too. The same thing is true for Characters whose value is between \u000 and \u007F, and Shorts and Integers whose value is between -128 and 127. Short So when Integers ‘a’ and ‘b’ were set to 5, they both referred to the same Integer instance and the ‘==’ comparison was true. But since 12345 is outside the magic range, variables ‘c’ and ‘d’ got their own Integer instances so the ‘==’ comparison was false. Strange, but true. 5 12345 Java is a wonderful language, but there are instances of unusual behavior that can really mess with your mind. Don’t let that stop you. Write it down and share it so we can all benefit from your discovery. If you’ve got any feedback on this, please post a comment. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) CurtainDog wrote:if you mistakenly use decode everything will work fine until you try a string that starts with a 0 (and even then it might still work). long octalNumber = 023; // This is 19 in decimal long hexNumber = 0x23; // This is 35 in decimal long decimalNumber = 23; // The real 23; Integer a = 5; Integer b = 5; Integer a = new Integer(5); Integer b = new Integer(5); new General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/36088/Java-Mini-Puzzler?msg=3033566
CC-MAIN-2014-23
refinedweb
1,984
71.24
I'm making an Android app with Unity3D and it works with click detection already, but not with touch. I need touch though for multitouch detection. What I want: I have my player and 2 images of arrows. One arrow points right and one left. When I touch the left arrow the player should start moving left, when I touch the right arrow the player should start moving right. But how do I detect which arrow is touched (and held)? All the code I found on Google is too old and not working anymore. I'm working with C# scripts and it's a 2D game. All of the above is A BIT RIDICULOUS guys :) Klausar, what you're looking for is ......... it's that easy! click "add Canvas". (You very likely want "scale to screen size" - select that option.) click "add Button". there is no "three" .. go drinking. In your code, have a routine like public void UserClickedRight() { Debug.Log("click right whoo!"); } and same for left. Go to your right Button in the editor. Just drag the script to it and select UserClickedRight. This is explained in millions of tutorials if you have not seen it before. It's the absolutely basic mechanism and paradigm of Unity - dragging a certain script to a "slot" for it in the Editor. Incredibly easy right?! You DO NOT need to go to the level of touch handling to achieve this. It's incredibly easy, you just need to know a couple of things about the Unity "event" system. Notice that in "Button", Unity "give you" a link to "OnClick" right there in the Inspector panel. You completely know how to use that now, right? So, Unity put that one "right there in the panel" for convenience since you use it on most buttons. The good news is that Button has other terrific events, you can use. You ask, what are these other awesome events? Always simply look at the doco to find out: As you can see there are terrific events like OnPointerDown and OnPointerUp. That's what you want in your case. Again, looking at this image... To repeat, Unity "give you" OnClick right there in the editor. You may say "well, why aren't the others in there?" No mystery - it's just that OnClick is used so commonly. Say in a year or two Unity found that everyone used OnPointerDown all the time, and everyone was always yelling at them to add it in there. In that case, they'd probably add it in there for convenience. Conversely, you can imagine that they may have simply not bothered putting OnClick in there, perhaps to make that panel smaller. The point is OnClick, OnPointerDown and so on are all events, just the same - it's just that as it happens they have "thrown in" OnClick right there on that panel, since it's popular. Indeed, some would say this is a bit confusing: if Unity did NOT put OnClick right in there, you'd have to learn what I'm just about to explain, right? You'd have to do the following, just to use OnClick ... see what I mean? So to use the other events is extremely simple, you just and, it's that easy. So. You're going to be using Unity's event system, so you'll have to do this: using UnityEngine.EventSystems; Next,. You know that a script normally starts like this... public class FancyButton:MonoBehaviour The "MonoBehaviour" part just means that it's a c# script which will be "driving a GamObject", it will be "part of a GameObject". But in this case we have to further alert the engine that you will be using the down and up click events. So you add this. ,IPointerDownHandler,IPointerUpHandler So. So far we have this using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler { Now the easy part. You just type the two routines which Unity will run for you when the things happen. using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler { public void OnPointerDown(PointerEventData data) { Debug.Log("holy! someone clicked down!") } public void OnPointerUp(PointerEventData data) { Debug.Log("whoa! someone clicked up!") } } Now all you have to do is put that script on the Button. Do so and give it a test. So don't forget to actually put that script on the button in question. And don't forget that, in fact, you can put it on any button you like to make that button work that way. (It's common that you have a script like this, which, you put on every button in your project, or perhaps on a prefab.) Next, click on Obi-wan to see where we're at so far! Finally, it sounds like you want to do something "when the button is being held down". That's just a general programming issue - you'd have a boolean which you turn on and off as the button goes up and down. Let's do it. using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler { [System.NonSerialized] public bool mouseIsDownRightNow; public void OnPointerDown(PointerEventData data) { mouseIsDownRightNow = true; } public void OnPointerUp(PointerEventData data) { mouseIsDownRightNow = false; } } You could access that variable from another script, or whatever you want. Add the following if you want to run a routine while the button is down: void Update() { if (buttonIsDownRightNow) WhileButtonIsDown(); } private void WhileButtonIsDown() { Debug.Log("THE #$@#$ BUTTON IS DOWN!!!!!!!! WHOA!"); } Try that and watch the console as you hold the button down and up. Here's an example of something like continually increasing a value while the button is down: using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler { [System.NonSerialized] public bool buttonIsDownRightNow; private int countSomething; public void OnPointerDown(PointerEventData data) { buttonIsDownRightNow = true; } public void OnPointerUp(PointerEventData data) { buttonIsDownRightNow = false; } private void WhileButtonIsDown() { ++countSomething; } void Update() { if (buttonIsDownRightNow) WhileButtonIsDown(); Debug.Log("value is now " +countSomething.ToString()); } } That's all there is to it. Once you really understand events in Unity, there is not much more to understand. The only other important topics are Mecanim, shader writing, touch, coroutines, threading, PhysX, native plugins, sprites, networking, dynamic mesh, navigation, VR, AR, animation, inverse kinematics, particles, terrain, IAP, lighting, baking, shadows, MMP, character controllers...and audio. Enjoy!
https://codedump.io/share/ws3CixAFnWec/1/how-do-i-get-touch-working-in-unity3d
CC-MAIN-2016-50
refinedweb
1,064
67.65
Ok, community. We'll top 100 responses to this thread any second now. We need to start curating some of the data so the feedback is captured. I have attempted to kick start something a bit wiki-like that can be updated via PRs: - Things that need doing: - A full audit of each spec's "other" javax usage (PRs welcome!!) - A list of each spec jar and its full transitive dependencies: - A careful eye to review this informational list of "not affected" namespaces - You to clean up and submit your uniquely awesome proposal in this format: On proposals, if you image a variant that is more specific or slightly different that the two above, definitely submit it. -David
https://www.eclipse.org/lists/jakartaee-platform-dev/msg00130.html
CC-MAIN-2019-26
refinedweb
118
50.7
how to print only digits from file line separated by hyphen in python This is the input file Below is the output expected 1 1800 555 555 8821 I tried using re but couldnt get what exact i want. 2 answers - answered 2017-11-12 20:20 DRPK Try This ( i wrote a function for you ): def re_make_string(get_string): buffer_last = [] for chars in get_string: if chars == "-" or chars == " ": buffer_last.append(" ") try: int(chars) except: pass else: buffer_last.append(chars) re_data = ''.join(buffer_last).replace(" ", " ").replace(" ", " ").strip() return re_data print(re_make_string(""""")) - answered 2017-11-12 20:58 Ni Nisan Nijackle while True: data = input() # you could also switch input for the data you have above #put whatever you want to the script to look for below for a specific character digitOne = '1' digitTwo = '2' digitThree = '3' digitFour = '4' digitFive = '5' digitSix = '6' digitSeven = '7' digitEight = '8' digitNine = '9' for i in range(0, len(data[:14])): if data[i] == digitOne or data[i] == digitTwo or data[i] == digitThree: print(data[i], end = "") elif data[i] == digitFour or data[i] == digitFive or data[i] == digitSix: print(data[i], end = "") elif data[i] == digitSeven or data[i] == digitEight or data[i] == digitNine: print(data[i], end = "") else: print("", end = "") #print('\n') not necesary ,but if you want to start the input on the new line You could fix whatever you want by changing the values you want the machine to look for ,but that's how you get the data of digits only even with hyphens. Also I am not really a fan of this question because it only asks for digits from a file ,but then you post the details that contradicts it. I am only answering the question. That isn't exactly the most efficient of code ,but it's editable. The :14 in the for loop limits the amount of data the machine prints ,since it seems like what you wanted is there. You can change the limit as you please. You really don't need the while loop it's just good for testing. if you want a space in between each number then simply insert a space for each end = "" then it will give you that if you want no limit and you want all the data to be printed then just remove the :14. The out put should be this when you type in the all the numbers
http://quabr.com/47253256/how-to-print-only-digits-from-file-line-separated-by-hyphen-in-python
CC-MAIN-2018-30
refinedweb
400
57.74
table of contents NAME¶ process_vm_readv, process_vm_writev - transfer data between process address spaces SYNOPSIS¶ #include <sys/uio.h> ssize_t process_vm_readv(pid_t pid, const struct iovec *local_iov, unsigned long liovcnt, const struct iovec *remote_iov, unsigned long riovcnt, unsigned long flags); ssize_t process_vm_writev(pid_t pid, const struct iovec *local_iov, unsigned long liovcnt, const struct iovec *remote_iov, unsigned long riovcnt, unsigned long flags); process_vm_readv(), process_vm_writev(): DESCRIPTION¶ These system calls transfer data between the address space of the calling process ("the local process") and the process identified by pid ("the remote process"). The data moves directly between the address spaces of the two processes, without passing through kernel space. The process_vm_readv() system call transfers data from the remote process to the local process. The data to be transferred is identified by remote_iov and riovcnt: remote_iov is a pointer to an array describing address ranges in the process pid, and riovcnt specifies the number of elements in remote_iov. The data is transferred to the locations specified by local_iov and liovcnt: local_iov is a pointer to an array describing address ranges in the calling process, and liovcnt specifies the number of elements in local_iov. The process_vm_writev() system call is the converse of process_vm_readv()—it transfers data from the local process to the remote process. Other than the direction of the transfer, the arguments liovcnt, local_iov, riovcnt, and remote_iov have the same meaning as for process_vm_readv(). The local_iov and remote_iov arguments point to an array of iovec structures, defined in <sys/uio.h> as: struct iovec { void *iov_base; /* Starting address */ size_t iov_len; /* Number of bytes to transfer */ }; Buffers are processed in array order. This means that process_vm_readv() completely fills local_iov[0] before proceeding to local_iov[1], and so on. Likewise, remote_iov[0] is completely read before proceeding to remote_iov[1], and so on. Similarly, process_vm_writev() writes out the entire contents of local_iov[0] before proceeding to local_iov[1], and it completely fills remote_iov[0] before proceeding to remote_iov[1]. The lengths of remote_iov[i].iov_len and local_iov[i].iov_len do not have to be the same. Thus, it is possible to split a single local buffer into multiple remote buffers, or vice versa. The flags argument is currently unused and must be set to 0. The values specified in the liovcnt and riovcnt arguments must be less than or equal to IOV_MAX (defined in <limits.h> or accessible via the call sysconf(_SC_IOV_MAX)). The count arguments and local_iov are checked before doing any transfers. If the counts are too big, or local_iov is invalid, or the addresses refer to regions that are inaccessible to the local process, none of the vectors will be processed and an error will be returned immediately. Note, however, that these system calls do not check the memory regions in the remote process until just before doing the read/write. Consequently, a partial read/write (see RETURN VALUE) may result if one of the remote_iov elements points to an invalid memory region in the remote process. No further reads/writes will be attempted beyond that point. Keep this in mind when attempting to read data of unknown length (such as C strings that are null-terminated) from a remote process, by avoiding spanning memory pages (typically 4 KiB) in a single remote iovec element. (Instead, split the remote read into two remote_iov elements and have them merge back into a single write local_iov entry. The first read entry goes up to the page boundary, while the second starts on the next page boundary.) Permission to read from or write to another process is governed by a ptrace access mode PTRACE_MODE_ATTACH_REALCREDS check; see ptrace(2). RETURN VALUE¶ On success, process_vm_readv() returns the number of bytes read and process_vm_writev() returns the number of bytes written. This return value may be less than the total number of requested bytes, if a, -1 is returned and errno is set appropriately. ERRORS¶ -¶ These system calls were added in Linux 3.2. Support is provided in glibc since version 2.15. CONFORMING TO¶ These system calls are nonstandard Linux extensions. NOTES¶ The data transfers performed by process_vm_readv() and process_vm_writev() are not guaranteed to be atomic in any way. These system calls were designed to permit fast message passing by allowing messages to be exchanged with a single copy operation (rather than the double copy that would be required when using, for example, shared memory or pipes). EXAMPLES¶ The following code sample demonstrates the use of process_vm_readv(). It reads 20 bytes at the address 0x10000 from the process with PID 10 and writes the first 10 bytes into buf1 and the second 10 bytes into buf2. #include <sys/uio.h> int main(void) { struct iovec local[2]; struct iovec remote[1]; char buf1[10]; char buf2[10]; ssize_t nread; pid_t pid = 10; /* PID of remote process */ local[0].iov_base = buf1; local[0].iov_len = 10; local[1].iov_base = buf2; local[1].iov_len = 10; remote[0].iov_base = (void *) 0x10000; remote[0].iov_len = 20; nread = process_vm_readv(pid, local, 2, remote, 1, 0); if (nread != 20) return 1; else return 0; } SEE ALSO¶ COLOPHON¶ This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at
https://dyn.manpages.debian.org/unstable/manpages-dev/process_vm_writev.2.en.html
CC-MAIN-2022-21
refinedweb
873
62.58
Basics of Model-View-Controller (MVC4) Description:Followings tips will be helpful for you at the time of making application using MVC4.0 where you have to take multiple controls. If you are beginner then you can easily use these tips as per requirements. 1) How to create listbox in view(.cshtml) in which user can select more than one values? @Html.ListBoxFor(m=>m.property_of_model, ViewBag.name_of_viewbag as MultiSelectList, new {size = "8"}) 2) How to call post method from view (.cshtml) ? @using (Html.BeginForm("your action name", "your controller name", FormMethod.Post, new { id = "id you want to pass" })) 3) How to use grid in view (.cshtml) page? var objgrid = new WebGrid(Model, rowsPerPage: 10); @objgrid.GetHtml(htmlAttributes: new {id ="MyGrid"}, columns: objgrid.Columns( objgrid.Column("", header: "", format: (col) => @Html.Raw(col.propoertyname)))) 4) How to make action link for Edit? @Html.ActionLink("Edit", "Edit", new { id = your_propertyname }) Through id field you can retrieve data and update. You have to write code in Edit actionlist to make it work. 5) How to make action link for delete? @Html.ActionLink("Delete", "Delete", new { id = your_property_name }) You have to write code in Delete actionlink to make it work. 6) How to apply different css to controls at button click event using JQuery in MVC4.0? btnSubmit is id of the button. $('#btnSubmit').click(function () { $.post('/your_namespace_name/controller_name/action_name', function (data) { $('#controlid').css('display', 'none'); $('#controlid').css('display', 'block'); }); });
https://www.dotnetspider.com/resources/44779-Basics-Model-View-Controller-MVC4.aspx
CC-MAIN-2020-40
refinedweb
237
52.76
Mysql & java - JDBC to connect to mysql 5.1 using java. But it shows error about: Class.forName...) { System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName jdbc import java.sql.*; public class MysqlConnect{ public static void main(String[] args) { System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306 how JAVA & MYSQL - JDBC JAVA & MYSQL How can we take backup of MySQL 5.0 database by using...;Hi Friend, Please visit the following page for working example of MySQL backup. This may help you in solving your problem. mysql problem - JDBC = "jdbc:mysql://localhost:3306/test"; Connection con=null; try...mysql problem hai friends please tell me how to store the videos in mysql plese help me as soon as possible thanks in advance   mysql installation problem - JDBC mysql installation problem Hi, when i installing mysql server on my pc in MySQL Server Instance Configuration Wizard,I enter the root pw... information. mysql problem - JDBC mysql problem hai friends i have some problem with image storing in mysql. i.e while i am using image(blob) for insert the image it says... of creation of table in mysql. it will take any image and store in database "); Connection connect = DriverManager.getConnection("jdbc:mysql://localhost...").newInstance(); String connectionURL = "jdbc:mysql://localhost:3306/test";; Connection...retrieve the value from database into dropdown list using JDBC SQL 2005  Java and Mysql Java and Mysql Sir, I want to connect my java program with mysql...("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql... the following link: JDBC Tutorials sir mysql server is on another system problem connect jsp and mysql - JSP-Servlet problem connect jsp and mysql hello, im getting an error while connecting jsp and mysql. I have downloaded the driver mysql-connector...: 15: <% 16: String url="jdbc:mysql://localhost/test"; 17: mysql jdbc connectivity mysql jdbc connectivity i want to connect retrieve data from mysql using jdbc jdbc - JDBC = null; String url = "jdbc:mysql://localhost:3306/"; String db... information on JDBC-Mysql visit to :... of columns even the developer don't know how many columns,(using java script new text cannot connect to database - JDBC cannot connect to database Iam using eclipse in my system ,when connecting the database mysql version 5.0 to the eclipse iam getting an error as ""Creating connection to mysql has encountered a problem.Could not connect to mysql java runtime exception - JDBC (String args[]) { System.out.println("MySQL Connect Example."); Connection con = null; String url = "jdbc:mysql://localhost:3306...java runtime exception while i executing this source code:- import regarding jdbc - JDBC regarding jdbc how to connect mysql with java example you have... = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase", "your username", "your... code and details having the error to solve the Problem. Thanks   install in linux any software making connection between java and MySQL. Or how can i...MySql ClassNotFoundException Dear sir, i am working in Linux platform with MySQL database , actually i finished all installation in MySQL mysql andservlets - JDBC mysql andservlets I have two tables with primarykey fields.I need... in mysql?and what is the code in servlets? Hi friend, For solving the problem visit programming problem - JDBC java programming problem Hi, Request you to provide a solution... problem to the following mail id : Problem : upload excel file data into oracle database using java / j2ee. mail id : raichallp@yahoo.co.in how to connect swings with jdbc... - Java Beginners how to connect swings with jdbc... Hi friends, Is it possible... you a code that will insert and retrieve data from MySql database using java..."); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test jdbc - JDBC management so i need how i can connect the pgm to database by using jdbc... at Thanks Hi, You can use following code to connect to Database with the help of JDBC API java error - JDBC [] args) { System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName...java error Why am I getting errors in the follwing program how to connect jsp to mysql - Java Beginners how to connect jsp to mysql I m new in Mysql and JSP i m... with mysql .java file is compiled but this not connected with my sql plz anyone help me hw to conncet jsp with mysql this is connection file package connect jdbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root...jdbc how can i store the image file and retrive the images from the database using java with querys also import java.sql.*; import JDBC Drive For Mysql JDBC Drive For Mysql  .... Once the driver is loaded ,you connect the front end of the Java application...; jdbc driver for mysql is specified in string driver. JdbcDriveForMysql JDBC Training, Learn JDBC yourself will learn how to connect the MySQL database with Java file. We need to establish... JDBC Connectivity Code in Java. JDBC Drive For Mysql... JDBC Connection Pooling Accessing Database using Java and JDBC Learn how Connecting to remote mysql server using jdbc. Connecting to remote mysql server using jdbc. How to Connect to remote mysql server using jdbc Connectivity with sql in detail - JDBC unable to connect the sql with Java. Please tell me in detail that how to connect...) { System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName database connectivity - JDBC database connectivity example java code for connecting Mysql... java : import java.sql.*; public class MysqlConnect{ public static void main(String[] args) { System.out.println("MySQL Connect Example Connect JSP with mysql Connect JSP with mysql  ...; This query creates database 'usermaster' in Mysql. Connect JSP with mysql : Now in the following jsp code, you will see how to connect connectivity - JDBC driver for JDBC and set in the Tomcat/lib folder and if any more problem give full...connectivity I hav MySQL 5.0, JDK 1.5, Tomcat 5.0 in my system when I tried to connect to database and insert data it is showing exeception - JDBC in a database System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName jdbc - JDBC ("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost... con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ram","root","root...(Exception l) { d.println(l); } } } For any more problem on JDBC jdbc - JDBC = null; String url = "jdbc:mysql://localhost:3306/"; String dbName... primary key solve this problem.. how to drop and delete values from table.... Thanks JDBC connection JDBC connection ![alt text][1]I got exception in Connecting to a MySQL Database in Java. The exception is ClassNotFoundException:com.mysql.jdbc.Driver wat is the problem jdbc - JDBC : Retrieve Image using Java... = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root... and retrive it using a java program? plz help me with the code. Hi Connecting to MYSQL Database in Java ("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost/"; String dbName = "textbook"; String driver... the following link: JDBC MySQl Connectivity I have mysql-connector jdbc - JDBC Deletion Example"); Connection con = null; String url = "jdbc:mysql://localhost...jdbc jdbc Expert:Ramakrishna Statement st1=con.createStatement... table; " here rs10.getString(1) " is the only primary key solve this problem jdbc - JDBC ("jdbc:mysql://localhost:3306/ram","root","root"); System.out.println("Connect... information. Thanks exception at runtime - JDBC java.sql.*; public class MysqlConnect { public static void main(String args[]) { System.out.println("MySQL Connect Example."); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "bank"; String Prepared statement JDBC MYSQL Prepared statement JDBC MYSQL How to create a prepared statement in JDBC using MYSQL? Actually, I am looking for an example of prepared statement. Selecting records using prepared statement in JDBC - JDBC = "jdbc:mysql://localhost:3306/"; String dbName = "register"...); out.println("Successfully connect to the database"); conn.close< MYSQL Java Connector Library Where to download the MYSQL Java Connector Library and get the jar file This article discuss 'how to connect Java and MYSQL using MYSQL connector'.../connector/ MYSQL Java Connector Library or Mysql JDBC connector is simply a Jar JDBC JDBC How to connect JAVA Servlet with the database Problem in uploading image to to mysql database Problem in uploading image to to mysql database Hi, need some help... connection = null; String connectionURL = "jdbc:mysql... have no problem in saving the image in the folder, my problem is it can't save mysql datasource - JDBC mysql datasource hello there......... i'm a real beginner for mySql can any one tell me how i do configurations in my windows machine after installing mysql(version 5.1).. i've added the Connector/J to the calss path connect jdbc to an Excel spreadsheet connect jdbc to an Excel spreadsheet hello, How can I connect to an Excel spreadsheet file using jdbc? Hello Friend, Follow... excel) Click "Ok" and restart your compiler. Compile the following java code JDBC Example with MySQL , you will learn how to connect the MySQL database with Java file. We need... JDBC Example with MySQL Mapping MySQL Data Types in Java Data types of MySQL Connect JSP with mysql Connect JSP with mysql  ... you how to connect to MySQL database from your JSP code. First, you need... database in my sql command prompt) 2. Connect JSP with mysql:  jdbc (); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost... information, visit the following link: JDBC Tutorials jdbc driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test...jdbc i had written jdbc connection in method and i need to get connection in another class? import java.sql.*; class error - JDBC ,i got a errors d:temp> java DBConnect db Connect Example...(String[] args) { System.out.println("db Connect Example."); Connection conn = null; String url = "jdbc:oracle:thin:@localhost:1521:xe"; String creating jdbc sql statements - JDBC ) Hi friend, i think, connection problem. i am sending jdbc... static void main(String[] args) { System.out.println("MySQL Connect Example."); Connection con = null; String url = "jdbc:mysql://192.168.10.211 Database Connection - JDBC Database Connection In java How will be connect Database through JDBC? Hi Friend, Please visit the following link: JDBC = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root JDBC CONNECTIVITY execution finished."""""") what may the problem? Java Mysql..."); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abhi...JDBC CONNECTIVITY import java.sql.Connection; import java program - JDBC , Please give details to solve the problem. For read JDBC connection to visit.... program i have a DBschema, in that i have schema name and set java - JDBC java how to get connectoin to database server from mysql through java programme Hi Friend, Please visit the following link for more detailed information JDBC ("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql How to connect to MySql Database from Servlet? will learn the JDBC steps necessary to connect to the MySQL Database and execute... and then connect it through JDBC to show all the records present there. MySql Table...; font-weight: bold; } How to connect to MySql Database from Servlet JDBC - JDBC :// Thanks...JDBC JDBC driver class not found:com.mysql.jdbc.Driver..... Am getting an error like this...... i have added the jar files for mysql inside java runtime error - JDBC java runtime error when i m running my jdbc program it is giving the problem as class not found exception.so, please suggest me what may be the solution regarding this. Hi friend, The problem is of Jar JDBC - Java Beginners JDBC How to connect to mysql database from an applets or GUI components (on J2SE) using Eclipse Servlets - JDBC = "jdbc:mysql://localhost:3306/"; String dbName = "register"...Java Servlet Documentation Can anyone please provide the Java...); out.println("Successfully connect to the database"); conn.close java - JDBC have to use JDBC and oracle. plz send the details for connecting "java... for database connectivity:... sending data inserting code into database using JDBC with jsp handles any internal exception generated(eg;SOLException). PROBLEM JAVA(JDBC) - JDBC JAVA(JDBC) Hello friends, please tel me, how can we retrieve..."; String driverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql... for more information. jdbc problem jdbc problem hi my name is mohit...i am making a project in java... in the database....pls help me guys...i am new to java...pls help me learn... thanks...(this is made in java class) public class loginconnection { public static void JDBC - Java Beginners JDBC To connect java with mysql database i used the proper class... as "class not found error". Is there any steps to connect mysql with java... where your mysql connector jar file available thats allj ar file name = mysql
http://www.roseindia.net/tutorialhelp/comment/97766
CC-MAIN-2014-35
refinedweb
2,115
51.65
Land cover is a key variable in the context of climate change. In particular, crop type information is essential to understand the spatial distribution of water usage and anticipate the risk of water scarcity and the consequent danger of food insecurity. This applies to arid regions such as the Aral Sea Basin (ASB), Central Asia, where agriculture relies heavily on irrigation. Here, remote sensing is valuable to map crop types, but its quality depends on consistent ground-truth data. Yet, in the ASB, such data is missing. Addressing this issue, we collected thousands of polygons on crop types, 97.7% of which in Uzbekistan and the remaining in Tajikistan. We collected 8,196 samples between 2015 and 2018, 213 in 2011 and 26 in 2008. Our data compiles samples for 40 crop types and is dominated by “cotton” (40%) and “wheat”, (25%). These data were meticulously validated using expert knowledge and remote sensing data and relied on transferable, open-source workflows that will assure the consistency of future sampling campaigns. A crop type dataset for consistent land cover classification in Central Asia, Ruben Remelgado Remelgado, Ruben; Zaitov, Sherzod; Kenjabaev, Shavkat; Stulina, Galina; Sultanov, Murod; Ibrakhimov, Mirzakhayot; et al. (2020): A crop type dataset for consistent land cover classification in Central Asia. figshare. Dataset. from radiant_mlhub import Dataset ds = Dataset.fetch('idiv_asia_crop_type') for c in ds.collections: print(c.id) Python Client quick-start guide
https://mlhub.earth/data/idiv_asia_crop_type
CC-MAIN-2022-27
refinedweb
234
56.35
TextPrinter.Print does not properly handle text with newline characters.Posted Monday, 27 April, 2009 - 02:20 by Kamujin Description textPrinter.Print("Line1\nLine2\nLine3", font, Color.Black); ...prints all 3 lines to the same line. Additionally, textPrinter.Measure("Line1\nLine2\nLine3", font).BoundingBox; ...returns a rectangle as if the text were 2 lines of text. #1 Which OS? Does this occur when you use System.Environment.NewLine? '\n' is not a valid newline character on Windows. #2 Ubuntu 9.04. "\n" is a valid newline in .NET as well as for many most Win32 controls. Console.WriteLine("Line1\nLine2") yields output on 2 lines on both mono and .NET runtimes. If you are thinking of the "\r\n" pairs often used in windows files, it is still worth noting that the '\r" mean carriage return and the "\n" means newline. Regardless of how you choose to implement this, I think it would be worth the time to look at for the following reasons. 1) The current implementation treats the "\n" character as carriage return (without a newline) and overwrites the previous text. 2) textPrinter.Measure("Line1\nLine2\nLine3", font).BoundingBox; returns a HEIGHT property equal to 2 lines of height. Hope this helps and thanks. #3 This issue is slightly more complicated than it looks. Ideally, newlines would be processed by GDI+ (which we use for text measurements / output). Unfortunately, the GDI+ implementation on Mono cannot handle newlines at this point and .Net is awfully slow when measuring strings with newlines. The current workaround is to split text into an array of strings (something equivalent to string[] lines = text.Replace('\r', '').Split('\n')) and processes each line separately. The real solution would be to bypass GDI+ completely and use GDI on Windows and Mono.Pango on Linux / Mac OS X. Unfortunately, I cannot dedicate the time for this right now. I don't doubt that you have encountered a bug. Text printing with newlines seems to work on .Net and Mono 2.2+ (subject to some limitations on Mono), but I haven't tested with Mono 2.0. I'll try to reproduce on Ubuntu 9.04 and fix this. Edit: The fact that several WinForms controls can cope with '\n' does not make it any more valid. Many other controls cannot (like the TextBox or the MessageBox) - better play safe and treat this as an implementation detail (which actually changed during the 1.1 -> 2.0 transition). AFAIK, the console is a completely different beast. #4 Ok, I can reproduce the problem. Investigating. #5 This is a duplicate of issue #847: TextPrinter layout when width, height are zero..
http://www.opentk.com/node/814
CC-MAIN-2014-52
refinedweb
440
68.87
Serializing Java Objects with XStream August 18,. XStream is being actively developed by a small project team with over a dozen contributors. It promises to become a very useful tool for persistence and transport; and I think it embraces, as does Joe Walnes, some virtues of agile programming. Joe Walnes explained the following in private correspondence: XStream's primary purpose is for serialization. It allows existing Java objects to be converted to clean XML and then restored again, without modifications. This is particularly useful as a form of persistence (no complicated database mappings required) or for sending objects over the wire. It has been optimized for this and is in heavy use on production systems. XStream offers a two-minute tutorial and JavaDocs. Unfortunately, the XStream distribution doesn't yet provide example programs, though there is a test suite. This article demonstrates several example Java programs that should help you get started with XStream today. The current, stable version of XStream is 1.0.1, which was released at the end of May 2004. This article, however, uses the latest snapshot available in late July 2004. Programs were compiled and run with Sun's Java 1.4.2_05 and included an XStream JAR ( xstream-SNAPSHOT.jar) in the classpath at compile time. The examples also use Aleksander Slominski's speedy XML Pull Parser or XPP ( xpp3-1.1.3.3_min.jar) at runtime. Both the stable and snapshot versions of XStream includes JARs. Download both the XStream archive and the example programs to a working directory. A Simple Program Let's start with a simple program that shows the basics of XStream serialization. The program Hello.java follows. It is available in the sample archive for this article. The program uses XStream to output a string in XML: import com.thoughtworks.xstream.XStream; public class Hello { public static void main(String[] args) { XStream xstream = new XStream(); String salutation = "Hello, World!"; String xml = xstream.toXML(salutation); System.out.print(xml); } } The public class Hello imports only one class, com.thoughtworks.xstream.XStream. It calls a constructor for XStream, creating the object xstream. Then it uses the toXML method to store the string salutation as XML, and writes the XML to the console using the System.out.print method. Compile the program using this command line at a shell prompt in the working directory: javac -classpath .;xstream-SNAPSHOT.jar Hello.java This shows the current directory and the XStream JAR in the classpath explicitly. (Of course, use colons instead of semicolons if you are on Unix.) Once Hello.java compiles successfully, run it with this line: java -cp .;xstream-SNAPSHOT.jar;xpp3-1.1.3.3_min.jar Hello This line adds the XPP JAR to the command line; it should output the following: <string>Hello, World!</string> XStream automatically wraps the Java String salutation in the XML element string. The string element appears to be an example of XStream's style of XML reflection. If you really want to see this in action, try Reflect.java: import com.thoughtworks.xstream.XStream; public class Reflect { public static void main(String[] args) { XStream xstream = new XStream(); String xml = xstream.toXML(xstream); System.out.print(xml); } } This program serializes the object xstream into XML, producing over 7,000 lines of "reflection." If you want to avoid the dependency on XPP, you can use DOM instead, like this ( HelloDom.java): import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class HelloDom { public static void main(String[] args) { XStream xstream = new XStream(new DomDriver()); String salutation = "Hello, World!"; String xml = xstream.toXML(salutation); System.out.print(xml); } } The differences between Hello.java and HelloDom.java are highlighted in bold: HelloDom.java imports the additional class com.thoughtworks.xstream.io.xml.DomDriver and then uses DomDriver in the XStream constructor. When you run HelloDom, you can drop the reference to the XPP JAR on your classpath. Using Another Class The next program, Instant.java, uses a non-public outer class, Date, to represent some data for a date: import com.thoughtworks.xstream.XStream; class Date { int year; int month; int day; } public class Instant { public static void main(String[] args) { XStream xstream = new XStream(); Date date = new Date(); date.year = 2004; date.month = 8; date.day = 15; xstream.alias("date", Date.class); String decl = "<?xml version=\"1.0\"?>\n"; String xml = xstream.toXML(date); System.out.print(decl + xml); } } The class Date holds three fields, all of which are integers. After the Date constructor, each of these fields is given a value, e.g. date.year = 2004;. The alias method creates an alias XML element name for the Date class, changing the default name from Date to date. XStream uses the fully qualified class name for the element name, including the package name, so the alias method will come in handy for tweaking names. The program also creates an XML declaration and uses it in its output. Compile and run the program, and you will get this output: <xml version="1.0"?> <date> <year>2004<year> <month>8<month> <day>15<day> <date> Deserializing XML to Objects The final program, Deserialize.java, shows you how to deserialize XML to an object, and then to reuse it: import com.thoughtworks.xstream.XStream; class Date { int year = 2004; int month = 8; int day = 15; } public class Deserialize { public static void main(String[] args) { XStream xstream = new XStream(); Date date = new Date(); xstream.alias("date", Date.class); String xml = xstream.toXML(date); System.out.print(xml); Date newdate = (Date)xstream.fromXML(xml); newdate.month = 12; newdate.day = 2; String newxml = xstream.toXML(newdate); System.out.print("\n\n" + newxml); } } Note this line from Deserialize.java: Date newdate = (Date)xstream.fromXML(xml); The line creates a new object newdate using the fromXML method to convert the string xml back to an object (also casting it as Date). After compiling and running Deserialize.java, you will see this output (two XML documents): <date> <year>2004<year> <month>8<month> <day>15<day> <date> <date> <year>2004<year> <month>12<month> <day>2<day> <date> The second instance of date comes from the object created from deserialized XML. Conclusion.
http://www.xml.com/pub/a/2004/08/18/xstream.html
CC-MAIN-2018-05
refinedweb
1,029
59.9
Details Description After investigating high CPU usage on some producers in production, we found out that a lot of time was passed in string construction for logging of DEBUG and TRACE level. This patch removes most of the logging calls, on our systems it cuts CPU usage down to half of what it used to be. Note that this is a significant boost in performance for environment where there are thousands of msg/s. Activity - All - Work Log - History - Activity - Transitions This is not the problem. Even if I change the log level, the construction of the string passed to the logging subsystem is the root cause, i.e. all calls of the form "Message %s is... ".format(...) . Scala is not a lazy evaluation language, the only ways to fix this problem are: 1. Wrap all the trace/debug calls with if (logging.debugEnabled()...) so that it doesn't get evaluated. This is the lazy way. or 2. Remove any debug/trace calls in this critical code path. This is clearly the remnant of `print foo' debugging, it shouldn't be committed to the trunk branch. Ah got it. Good point. Thanks for the patch. Are you sure that scala doesn't do lazy evaluation? I did the following test. It seems that it does? scala> import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger scala> val c = new AtomicInteger(1) c: java.util.concurrent.atomic.AtomicInteger = 1 scala> def a(msg: => String, isRun: Boolean){ if (isRun) println(msg) } a: (msg: => String,isRun: Boolean)Unit scala> a("test %d".format(c.incrementAndGet), false) scala> c res3: java.util.concurrent.atomic.AtomicInteger = 1 You are right, and by looking at the code the trace/debug logging functions are defined with lazy arguments. By debugging a bit further, I did not have any log4.properties in the producer classpath. The library does give me a WARN about missing log4.properties file. After this warning message, the program does not output any more log. Internally I'd assume the logging still we're set to TRACE without any appender to stdout/stderr. I'll take WARN more seriously next time. Maybe a put message in the producer documentation that not providing log4j configuration will have a serious impact on performance. On another note, I believe trace/debug message shouldn't be committed to production code, but this is only a personal hunch. So this is a non-issue right? Please re-open if you have any other concerns. A lot of the trace/debug messages are often extremely important for live debugging. i.e., we set the level to debug/trace to avoid log flooding but when we do need to trouble-shoot a production issue we can enable those messages using the JMX operations exposed by kafka.utils.Log4jController However if you see any log statements that can be improved/cleaned-up please let us know. Hi Francois, You can change the logging level in config/log4j.properties to avoid printing DEBUG and TRACE level log entries.
https://issues.apache.org/jira/browse/KAFKA-1115
CC-MAIN-2016-36
refinedweb
508
59.4
Performance Comparison of Primitive Lists in Java Last modified: May 7, 2019 1. Overview In this tutorial, we’re going to compare the performance of some popular primitive list libraries in Java. For that, we’ll test the add(), get(), and contains() methods for each library. 2. Performance Comparison Now, let’s find out which library offers a fast working primitive collections API. For that, let’s compare the List analogs from Trove, Fastutil, and Colt. We’ll use the JMH (Java Microbenchmark Harness) tool to write our performance tests. 2.1. JMH Parameters We’ll run our benchmark tests with the following parameters: @BenchmarkMode(Mode.SingleShotTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Measurement(batchSize = 100000, iterations = 10) @Warmup(batchSize = 100000, iterations = 10) @State(Scope.Thread) public class PrimitivesListPerformance { } Here, we want to measure the execution time for each benchmark method. Also, we want to display our results in milliseconds. The @State annotation indicates that the variables declared in the class won’t be the part of running benchmark tests. However, we can then use them in our benchmark methods. Additionally, let’s define our lists of primitives: public static class PrimitivesListPerformance { private List<Integer> arrayList = new ArrayList<>(); private TIntArrayList tList = new TIntArrayList(); private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(); private IntArrayList fastUtilList = new IntArrayList(); private int getValue = 10; } Now, we’re ready to write our benchmarks. 3. add() First, let’s test adding the elements into our primitive lists. We’ll also add one for ArrayList as our control. 3.1. Benchmark Tests The first micro-benchmark is for the ArrayList‘s add() method: @Benchmark public boolean addArrayList() { return arrayList.add(getValue); } Similarly, for the Trove’s TIntArrayList.add(): @Benchmark public boolean addTroveIntList() { return tList.add(getValue); } Likewise, Colt’s IntArrayList.add() looks like: @Benchmark public void addColtIntList() { coltList.add(getValue); } And, for Fastutil library, the IntArrayList.add() method benchmark will be: @Benchmark public boolean addFastUtilIntList() { return fastUtilList.add(getValue); } 3.2. Test Results Now, we run and compare results: Benchmark Mode Cnt Score Error Units addArrayList ss 10 4.527 ± 4.866 ms/op addColtIntList ss 10 1.823 ± 4.360 ms/op addFastUtilIntList ss 10 2.097 ± 2.329 ms/op addTroveIntList ss 10 3.069 ± 4.026 ms/op From the results, we can clearly see that ArrayList’s add() is the slowest option. This is logical, as we explained in the primitive list libraries article, ArrayList will use boxing/autoboxing to store the int values inside the collection. Therefore, we have significant slowdown here. On the other hand, the add() methods for Colt and Fastutil were the fastest. Under the hood, all three libraries store the values inside of an int[]. So why do we have different running times for their add() methods? The answer is how they grow the int[] when the default capacity is full: - Colt will grow its internal int[] only when it becomes full - In contrast, Trove and Fastutil will use some additional calculations while expanding the int[] container That’s why Colt is winning in our test results. 4. get() Now, let’s add the get() operation micro-benchmark. 4.1. Benchmark Tests First, for the ArrayList’s get() operation: @Benchmark public int getArrayList() { return arrayList.get(getValue); } Similarly, for the Trove’s TIntArrayList we’ll have: @Benchmark public int getTroveIntList() { return tList.get(getValue); } And, for Colt’s cern.colt.list.IntArrayList, the get() method will be: @Benchmark public int getColtIntList() { return coltList.get(getValue); } Finally, for the Fastutil’s IntArrayList we’ll test the getInt() operation: @Benchmark public int getFastUtilIntList() { return fastUtilList.getInt(getValue); } 4.2. Test Results After, we run the benchmarks and see the results: Benchmark Mode Cnt Score Error Units getArrayList ss 20 5.539 ± 0.552 ms/op getColtIntList ss 20 4.598 ± 0.825 ms/op getFastUtilIntList ss 20 4.585 ± 0.489 ms/op getTroveIntList ss 20 4.715 ± 0.751 ms/op Although the score difference isn’t much, we can notice that getArrayList() works slower. For the rest of the libraries, we have almost identical get() method implementations. They will retrieve the value immediately from the int[] without any further work. That’s why Colt, Fastutil, and Trove have similar performances for the get() operation. 5. contains() Finally, let’s test the contains() method for each type of the list. 5.1. Benchmark Tests Let’s add the first micro-benchmark for ArrayList’s contains() method: @Benchmark public boolean containsArrayList() { return arrayList.contains(getValue); } Similarly, for the Trove’s TIntArrayList the contains() benchmark will be: @Benchmark public boolean containsTroveIntList() { return tList.contains(getValue); } Likewise, the test for Colt’s cern.colt.list.IntArrayList.contains() is: @Benchmark public boolean containsColtIntList() { return coltList.contains(getValue); } And, for Fastutil’s IntArrayList, the contains() method test looks like: @Benchmark public boolean containsFastUtilIntList() { return fastUtilList.contains(getValue); } 5.2. Test Results Finally, we run our tests and compare the results: Benchmark Mode Cnt Score Error Units containsArrayList ss 20 2.083 ± 1.585 ms/op containsColtIntList ss 20 1.623 ± 0.960 ms/op containsFastUtilIntList ss 20 1.406 ± 0.400 ms/op containsTroveIntList ss 20 1.512 ± 0.307 ms/op As usual, the containsArrayList method has the worst performance. In contrast, Trove, Colt, and Fastutil have better performance compared to Java’s core solution. This time, it’s up to the developer which library to choose. The results for all three libraries are close enough to consider them identical. 6. Conclusion In this article, we investigated the actual runtime performance of primitive lists through the JVM benchmark tests. Moreover, we compared the test results with the JDK’s ArrayList. Also, keep in mind that the numbers we present here are just JMH benchmark results – always test in the scope of a given system and runtime. As usual, the complete code for this article is available over on GitHub.
https://www.baeldung.com/java-list-primitive-performance
CC-MAIN-2019-22
refinedweb
976
50.23
Enhanced version of Python's SimpleHTTPServer that supports HTTP Range I've just uploaded a small personal project to GitHub here. It's basically a very crude webserver that allows me to share audio files on my Linux boxes to my iOS devices, using Mobile Safari. The main reason for noting this is that the code may be of more general interest because it implements an improved version of Python stdlib's SimpleHTTPServer module, that implements basic support for the Range header in HTTP requests, which is necessary for Mobile Safari on some MP3 files. During early development, I found that some MP3 files would refuse to play in Mobile Safari when served by SimpleHTTPServer. The same file would play fine if served by Apache. Because debugging mobile web browsers is a PITA (caveat: I've haven't kept up with the latest-and-greatest in this area), I ended up resorting to Wireshark to see what was going on. Wireshark indicated that Mobile Safari would request chunks of the MP3 file (initially just the first couple of bytes), but SimpleHTTPServer would always serve the entire file, because it never checked for the existence of the Range header. On certain files, this wouldn't bother Mobile Safari, but on others it would cause the audio player widget to show an unhelpful generic error. Once I understood what the problem was, I found that I'm not the first person to get caught out by this, and that Apple themselves state that servers need to support Range to keep Mobile Safari happy. To solve the problem, I wrote a new class HTTPRangeRequestHandler that is a direct replacement for SimpleHTTPServer. In my app code proper, I then (try to) pull in my enhanced handler as follows: try: import HTTPRangeServer inherited_server = HTTPRangeServer.HTTPRangeRequestHandler except ImportError: logging.warning("Unable to import HTTPRangeServer, using stdlib's " + "SimpleHTTPServer") import SimpleHTTPServer inherited_server = SimpleHTTPServer.SimpleHTTPRequestHandler ... class MySpecificHandler(inherited_server): ... def main(port=12345): Handler = EnhancedRequestHandler httpd = SocketServer.TCPServer(("", port), Handler) Arguably it might be better for the code to die if HTTPRangeServer cannot be imported, but as the stdlib SimpleHTTPServer is good enough for many browser clients, it doesn't seem too unreasonable to use it as a fallback. This code is currently OK for most uses, but currently it doesn't support all variations of the Range header as described at aforementioned W3C spec page. It does however support all the requests variants I've seen in my - admittedly very cursory - browser testing, and any requests that it can't parse will instead get the full file served, which is the same behaviour as SimpleHTTPServer. The musicsharer application that's built on this class is even rougher, but as it's really just intended for my own personal use, you shouldn't hold your breath waiting for me to tart it up...
https://www.john-smith.me/tag/mobile-safari.html
CC-MAIN-2019-04
refinedweb
474
54.66
As you probably noticed by now, we've been using a lot of JSX in the previous tutorials. What we really haven't done is taken a good look at what JSX actually is. How does it actually work? Why do we not just call it HTML? What quirks does it have up its sleeve? In this tutorial, we'll answer all of those questions and more! We will do some serious backtracking (and some forwardtracking!) to get a deeper look at what we need to know about JSX in order to be dangerous. Onwards! OMG! A React Book Written by Kirupa?!! To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.BUY ON AMAZON What Happens with JSX? One of the biggest thing we've glossed over is trying to figure out what happens with our JSX after we've written it. How does it end up as HTML that we see in our browser? Take a look at the following example where we define a component called Card:> ); } }); We can quickly spot the JSX here. It is the following four lines: <div style={cardStyle}> <Square color={this.props.color}/> <Label color={this.props.color}/> </div> The thing to keep in mind is that our browsers have no idea what to do with JSX. They probably think you are crazy if you ever even try to describe JSX to them. That is why we have been relying on things like Babel to turn that JSX into something the browsers understand: JavaScript. What this means is that the JSX we write is for human (and well-trained cats) eyes only. When this JSX reaches our browser, it ends up getting turned into pure JavaScript: return React.createElement( "div", { style: cardStyle }, React.createElement(Square, { color: this.props.color }), React.createElement(Label, { color: this.props.color }) ); All of those neatly nested HTML-like elements, their attributes, and their children all get turned into a series of createElement calls with default initialization values. Here is what our entire Card component looks like when it gets turned into JavaScript: var Card = React.createClass({ displayName: "Card", render: function render() { var cardStyle = { height: 200, width: 150, padding: 0, backgroundColor: "#FFF", WebkitFilter: "drop-shadow(0px 0px 5px #666)", filter: "drop-shadow(0px 0px 5px #666)" }; return React.createElement( "div", { style: cardStyle }, React.createElement(Square, { color: this.props.color }), React.createElement(Label, { color: this.props.color }) ); } }); Notice that there is no trace of JSX anywhere! All of these changes between what you wrote and what our browser sees is part of the transpiling step we've talked about in the Building Your First React App tutorial. That transpilation is something that happens entirely behind-the-scenes thanks to Babel where we've been using it to perform this JSX->JS transformation entirely in the browser. We'll eventually look at using Babel as part of a more-involved build environment where we will just generate a transformed JS file, but more on that when we get there in the future. But yeah, there you have it. An answer to what exactly happens to all of our JSX. It gets turned into sweet SWEET JavaScript. JSX Quirks to Remember As we've been working with JSX, you probably noticed that we ran into some arbitrary rules and exceptions on what you can and can't do. In this section, let's put all of those quirks together in one area and maybe even run into some brand new ones! You Can Only Return A Single Root Node This is probably the first quirk we ran into. In JSX, what you return or render can't be made up of multiple root elements: ReactDOM.render( <Letter>B</Letter> <Letter>E</Letter> <Letter>I</Letter> <Letter>O</Letter> <Letter>U</Letter>, document.querySelector("#container") ); If you want to do something like this, you need to wrap all of your elements into a single parent element first: ReactDOM.render( <div> <Letter>A</Letter> <Letter>E</Letter> <Letter>I</Letter> <Letter>O</Letter> <Letter>U</Letter> </div>, document.querySelector("#container") ); This seemed like a bizarre requirement when we looked at it before, but you can blame createElement for why we do this. With the render and return functions, what you are ultimately returning is a single createElement call (which in turn might have many nested createElement calls). Here is what our earlier JSX looks like when turned into JavaScript: ReactDOM.render(React.createElement( "div", null, React.createElement( Letter, null, "A" ), React.createElement( Letter, null, "E" ), React.createElement( Letter, null, "I" ), React.createElement( Letter, null, "O" ), React.createElement( Letter, null, "U" ) ), document.querySelector("#container")); Having multiple root elements would break how functions return values and how createElementworks, so that is why you can specify only one return one (root) element! You can now sleep better knowing this. You Can't Specify CSS Inline As we saw in the Styling in React tutorial, the style attribute in your JSX behaves differently from the style attribute in HTML. In HTML, you can specify CSS properties directly as values on your style attribute: <div style="font-family:Arial;font-size:24px"> <p>Blah!</p> </div> In JSX, the style attribute can't contain CSS inside it. Instead, it needs to refer to an object that contains styling information instead: var Letter = React.createClass({ render: function() { var letterStyle = { padding: 10, margin: 10, backgroundColor: this.props.bgcolor, color: "#333", display: "inline-block", fontFamily: "monospace", fontSize: "32", textAlign: "center" }; return ( <div style={letterStyle}> {this.props.children} </div> ); } }); Notice that we have an object called letterStyle that that contains all of the CSS properties (in camel-cased JavaScript form) and their values. That object is what we then specify to the style attribute. Reserved Keywords and className JavaScript has a bunch of keywords and values that you can't use as identifiers (aka variable or property names). Those keywords look as follows: break, case, class, catch, const, continue, debugger, default, delete, do, else, export, extends, finally, for, function, if, import, in, instanceof, new, return, super, switch, this, throw, try, typeof, var, void, while, with, yield. When you are writing JSX, you should be careful to not use these keywords as part of any identifiers that you create as well. That can be difficult when certain really popular keywords like class are commonly used in HTML despite also being in JavaScript's reserved keywords list. Take a look at the following: ReactDOM.render( <div class="slideIn"> <p class="emphasis">Gabagool!</p> <Label/> </div>, document.querySelector("#container") ); Ignoring JavaScript's reservations about class (like what we've done here) won't work. What you need to do is use the DOM API version of the class attribute called classNameinstead: ReactDOM.render( <div className="slideIn"> <p className="emphasis">Gabagool!</p> <Label/> </div>, document.querySelector("#container") ); You can see the full list of supported attributes here, and notice that all of the attributes are camel cased. That detail is important, for using the lowercase version of an attribute won't work. If you are ever pasting a large chunk of HTML that you want JSX to deal with, be sure to go back to your pasted HTML and make these minor adjustments to turn it into valid JSX. This brings up another point. Because of these minor deviations from HTML behavior, we tend to say that JSX supports an HTML-like syntax as opposed to just saying that JSX supports HTML. This is a deliberate React-ism. The clearest answer to the relationship between JSX and HTML comes from React team member, Ben Alpert, who stated the following as part of a Quora answer: ...our thinking is that JSX's primary advantage is the symmetry of matching closing tags which make code easier to read, not the direct resemblance to HTML or XML. It's convenient to copy/paste HTML directly, but other minor differences (in self-closing tags, for example) make this a losing battle and we have a HTML to JSX converter to help you anyway. Finally, to translate HTML to idiomatic React code, a fair amount of work is usually involved in breaking up the markup into components that make sense, so changing class to className is only a small part of that anyway. Just like it is a good idea to comment your HTML, CSS, and JavaScript, it is a good idea to provide comments inside your JSX as well. Specifying comments in JSX is very similar to how you would comment in JavaScript...except for one exception. If you are specifying a comment as a child of a tag, you need to wrap your comment by the { and } angle brackets to ensure it is parsed as an expression: ReactDOM.render( <div class="slideIn"> <p class="emphasis">Gabagool!</p> {/* I am a child comment */} <Label/> </div>, document.querySelector("#container") ); Our comment in this case is a child of our div element. If you specify a comment wholly inside a tag, you can just specify your single or multi-line comment without having to use the { and } angle brackets: ReactDOM.render( <div class="slideIn"> <p class="emphasis">Gabagool!</p> <Label /* This comment goes across multiple lines */ className="colorCard" // end of line /> </div>, document.querySelector("#container") ); In this snippet, you can see an example of what both multi line comments and a comment at the end of a line looks like. Now that you know all of this, you have one less excuse to not comment your JSX :P Capitalization, HTML Elements, and Components Capitalization is important. To represent HTML elements, ensure the HTML tag is lower-cased: ReactDOM.render( <div> <section> <p>Something goes here!</p> </section> </div>, document.querySelector("#container") ); When wishing to represent components, the component name must be capitalized: ReactDOM.render( <div> <MyCustomComponent/> </div>, document.querySelector("#container") ); If you get the capitalization wrong, React will not render your content properly. Trying to identify capitalization issues is probably the last thing you'll think about when things aren't working, so keep this little tip in mind. Your JSX Can Be Anywhere In many situations, your JSX will not be neatly arranged inside a render or returnfunction like in the examples we've seen so far. Take a look at the following example: var swatchComponent = <Swatch color="#2F004F"></Swatch>; ReactDOM.render( <div> {swatchComponent} </div>, document.querySelector("#container") ); We have a variable called swatchComponent that is initialized to a line of JSX. When our swatchComponent variable is placed inside the render function, our Swatch component gets initialized. All of this is totally valid, and we will do more such things in the future when we learn how to generate and manipulate JSX using JavaScript. Conclusion With this tutorial, we've finally pieced together the various bits of JSX information that the previous tutorials introduced into one location. The most important thing to remember is that JSX is not HTML. It looks like HTML and behaves like it in many common scenarios, but it is ultimately designed to be translated into JavaScript. This means you can do things that you could never imagine doing using just plain HTML. Being able to evaluate expressions or programmatically manipulate entire chunks of JSX is just the beginning. In future tutorials, we'll explore this intersection of JavaScript and JSX further.!
https://www.kirupa.com/react/meet_jsx_again.htm
CC-MAIN-2017-09
refinedweb
1,893
56.35
The first digit of a power of 2 is a 1 more often than any other digit. Powers of 2 begin with 1 about 30% of the time. This is because powers of 2 follow Benford’s law. We’ll prove this below. When is the first digit of 2n equal to k? When 2n is between k × 10p and (k+1) × 10p for some positive integer p. By taking logarithms base 10 we find that this is equivalent to the fractional part of n log102 being between log10 k and log10 (k + 1). The map x ↦ ( x + log10 2 ) mod 1 is ergodic. I wrote about irrational rotations a few weeks ago, and this is essentially the same thing. You could scale x by 2π and think of it as rotations on a circle instead of arithmetic mod 1 on an interval. The important thing is that log10 2 is irrational. Repeatedly multiplying by 2 is corresponds to adding log10 2 on the log scale. So powers of two correspond to iterates of the map above, starting with x = 0. Birkhoff’s Ergodic Theorem tells us that the number of times iterates of this map fall in the interval [a, b] equals b – a. So for k = 1, 2, 3, … 9, the proportion of powers of 2 start with k is equal to log10 (k + 1) – log10 (k) = log10 ((k + 1) / k). This is Benford’s law. In particular, the proportion of powers of 2 that begin with 1 is equal to log10 (2) = 0.301. Note that the only thing special about 2 is that log10 2 is irrational. Powers of 3 follow Benford’s law as well because log10 3 is also irrational. For what values of b do powers of b not follow Benford’s law? Those with log10 b rational, i.e. powers of 10. Obviously powers of 10 don’t follow Benford’s law because their first digit is always 1! [Interpret the “!” above as factorial or exclamation as you wish.] Let’s look at powers of 2 empirically to see Benford’s law in practice. Here’s a simple program to look at first digits of powers of 2. count = [0]*10 N = 10000 def first_digit(n): return int(str(n)[0]) for i in range(N): n = first_digit( 2**i ) count[n] += 1 print(count) Unfortunately this only works for moderate values of N. It ran in under a second with N set to 10,000 but for larger values of N it rapidly becomes impractical. Here’s a much more efficient version that ran in about 2 seconds with N = 1,000,000. from math import log10 N = 1000000 count = [0]*10 def first_digit_2_exp_e(e): r = (log10(2.0)*e) % 1 for i in range(2, 11): if r < log10(i): return i-1 for i in range(N): n = first_digit_2_exp_e( i ) count[n] += 1 print(count) You could make it more efficient by caching the values of log10 rather than recomputing them. This brought the run time down to about 1.4 seconds. That’s a nice improvement, but nothing like the orders of magnitude improvement from changing algorithms. Here are the results comparing the actual counts to the predictions of Benford’s law (rounded to the nearest integer). |---------------+--------+-----------| | Leading digit | Actual | Predicted | |---------------+--------+-----------| | 1 | 301030 | 301030 | | 2 | 176093 | 176091 | | 3 | 124937 | 124939 | | 4 | 96911 | 96910 | | 5 | 79182 | 79181 | | 6 | 66947 | 66948 | | 7 | 57990 | 57992 | | 8 | 51154 | 51153 | | 9 | 45756 | 45757 | |---------------+--------+-----------| The agreement is almost too good to believe, never off by more than 2. Are the results correct? The inefficient version relied on integer arithmetic and so would be exact. The efficient version relies on floating point and so it’s conceivable that limits of precision caused a leading digit to be calculated incorrectly, but I doubt that happened. Floating point is precise to about 15 significant figures. We start with log10(2), multiply it by numbers up to 1,000,000 and take the fractional part. The result is good to around 9 significant figures, enough to correctly calculate which log digits the result falls between. Update: See Andrew Dalke’s Python script in the comments. He shows a way to efficiently use integer arithmetic. 3 thoughts on “Leading digits of powers of 2” The performance limitation in your first version is likely the quadratic time to convert from Python’s native integer representation to base-10. If you use a decimal.Decimal then that overhead disappears. The following takes about the same time as your second, float version, and doesn’t have the accuracy concern. (Both return the same values for N=1 million.) Andrew: Very nice. I haven’t used decimalbefore. Your proof is flawed. The ergodic theorem doesn’t assert anything about a specific orbit (in this case the orbit of 0), only about almost every orbit. You need to use the fact that exp(2pi n alpha) is uniformly distributed around the circle when alpha is irrational.
https://www.johndcook.com/blog/2017/06/20/leading-digits-of-powers-of-2/
CC-MAIN-2017-26
refinedweb
832
73.47
Inspired by this Stack Overflow question. Give the asker an upvote if you have a minute. It often occurs when writing a T4 template that you need to reference some element of the project containing the template. However, simply trying to reference a variable or call a function can be very frustrating. Especially because the current lack of T4 IntelliSense requires you to regenerate your code over and over again, only to find out that the “type or namespace name could not be found”. The reason why this is so frustrating is because of a natural mistake people make, which is thinking that a T4 file is just like any other code file in your project. This isn’t true. A better way to think of a .tt is as an independent set of instructions used to drop a generated file into your project when it is run. Because the .tt is independent, <#= ConsoleApplication1.MyClass.MyVariable #> is meaningless without a reference to the assembly containing ConsoleApplication1.MyClass.MyVariable. To create this reference, add the following include statement to your T4: <#@ assembly name="$(TargetPath)" #> Don’t forget the namespace: <#@ import namespace="ConsoleApplication2" #> Now you’ll be able to reference public elements of your project. But there is one more “gotcha”. Because your .tt is referencing your project assembly, if your assembly is out of date or simply hasn’t been built yet, your T4 won’t generate correctly. This is especially frustrating when your generated file has compilation errors, because you’ll end up in a deadlock when your noncompiling generated file is preventing you from correcting the errors contained within it. The solution to this is to manually make just enough corrections in the generated file to eliminate all compile time errors and then rebuild your project. You can then regenerate your file which will hopefully be now free of errors and then rebuild the project once more to take into account the generated code.
http://www.levibotelho.com/development/referencing-project-elements-in-a-t4-file/
CC-MAIN-2018-34
refinedweb
325
52.8
08 May 2009 17:23 [Source: ICIS news] LONDON (ICIS news)--US specialty chemicals group Cytec does not expect its coatings resins business to return to pre-downturn performance until 2012-13, it said on Friday. In an interview with ICIS news, president of the specialty chemicals division, Frank Aranzana, said there were no signs of a sustained recovery from collapsed demand in important end-use markets such as automotive and construction. There was improved demand for coatings in Asia, particularly ?xml:namespace> “In “Car sales have increased in Aranzana said volumes in coatings resins were down 43% year on year in the first quarter. The downturn began last August for this segment, he said. “July was our best month ever with strong demand in Europe and Asia although the Since then, there has been no recovery. In the first quarter, the surface specialties division posted an operating loss of $20.7m (€15.5m) against an operating profit of $20.6m in same period last year, amid a 46% drop in sales to $243m. “Destocking is still taking place across the value chain. In automotive it might take all year to reduce inventory and there could be prolonged shutdowns. In construction, the prospects in He said the company “has taken permanent, structural actions to match supply to demand”. “We are working to consolidate assets, closing older capacity and moving production to larger assets,” he added. Cytec announced in January that it would cut 600 jobs or 10% of its workforce and close capacity in La Llagosta, In March the company increased this target to 12% - more like 700 people - saying extra steps were needed to maintain liquidity. Aranzana said the Belgian powder unit should be closed by the end of June, and the others by the end of the year. The coatings division was particularly badly hit by this reduction, suffering a 17% cut in workforce as older solvent-based capacity is closed. “We will have reduced capacity in solvent borne resins by 30% by the end of this year. Cytec’s total manufacturing capacity for coating resins will reduce from 720,000 tonnes per year to 630,000 tonnes/year by the end of 2009. Capacity utilisation across the company was only 50% in the first quarter of 2009,” he said. The company has also imposed a salary merit freeze, bonus reduction, cuts to dividends, reductions to pension payments in the Aranzana’s specialty chemicals division had 2008 sales of $2.4bn, accounting for 65% of Cytec’s total $3.6bn sales. His unit manufactures coating resins and additives, mining chemicals, phosphines, specialty and polymer additives. One main focus for growth is water-borne and Radcure resins, which are replacing less environmentally acceptable solvent-based resins. Cytec’s most profitable division is engineering materials, which makes composites for aerospace applications. ($1 = €0.75) To discuss issues facing the chemical industry go to ICIS connect For more on Cytec
http://www.icis.com/Articles/2009/05/08/9214793/cytec-sees-no-recovery-for-coatings-chems-until-2012-13.html
CC-MAIN-2014-10
refinedweb
489
52.49
XUL documents and elements have a getElementsByAttribute() method. It'd really be nice to support this for elements with non-null namespaces as well. (In reply to comment #0) >support this for elements with non-null namespaces as well. Err, I mean attributes, not elements. How about we fix GetElementsByAttribute to be live like nodelists are supposed to be, first? Hmm... mind posting a testcase or two for getElementsByAttribute and getElementsByAttributeNS? I have an idea.... Created attachment 145833 [details] testcase with DOM manipulations available Comment on attachment 145833 [details] testcase with DOM manipulations available The last green row in any set has an attribute foo2:foo instead of foo:foo. This is to test the namespace-aware method's requirement to not look at the complete nodeName. However, I didn't style it that way, so clicking on the last row of a set will cause an adjustment in the NS-aware function's return, but not in the NS-blind one. (In reply to comment #2) > How about we fix GetElementsByAttribute to be live like nodelists are supposed > to be, first? I vote for correcting nodelist too. I had a lot of problems until I understood nodelist with getElementsByAttribute if different from nodelist from getElementsByTagName and need totally different code. I also suggest adding into documentation how to write nodelist code to be backwards compatible between different versions (start from end and not from the beginning. > I vote for correcting nodelist too. What is there to correct in nodelist? > ------- Additional Comments From bzbarsky@mit.edu 2005-02-27 18:23 PST ------- > > >> I vote for correcting nodelist too. >> > > > What is there to correct in nodelist? > > I thought that was your comment also. Maybe I used wrong wording... Anyway, the nodelist returned by getElementsByAttribute() is not live so removing node item(0) several times always removes the same node. When you do the same with getElementsByTagName() the returned nodelist is live and removing node item(0) removes the nodes one after another and the length of the nodelist changes automatically as well. If you remove starting from the last node it does not make a big difference, but who would know that you need to do that without documentation? Marja The point is, getElementsByAttribute doesn't actually return a nodelist (since the object it returns does not properly implement the nodelist api). That's what needs to be corrected. As for documentation, getElementsByTagName() is certainly documented, in the DOM spec. getElementsByAttribute does need documentation. > > As for documentation, getElementsByTagName() is certainly documented, in the DOM > spec. getElementsByAttribute does need documentation. The xulplanet document says it returns a nodelist and W3C DOM says nodelist is live and even if not the same returned nodelist does a different thing when returned from getElementsByTagName and getElementsByAttribute But maybe there is better documentation somewhere in mozilla.org and I should not believe xulplanet? Marja As by Firefox 1.5 in the testcase not even .getElementsByAttribute works any more. Bug: It works fine when it's supposed to work -- for attributes in the per-element namespace partition. This bug is about having a way to work with other attributes. Note comment 0 of this bug. In pre-1.5 it worked (i used it occasionally, that is why i noticed the change). I understood .doWhatever (opposed to .doWhateverNS) as DOM L 1 non-namespace-aware methods, where "pref:localname" is a legal and normal xml name which can be found as such in the qualified form (DOM L 2 Core: "DOM Level 1 methods solely identify attribute nodes by their nodeName.", where nodeName is the qualified name). So at this point, this should be doable by just combining the GetElementsByTagNameNS code and the GetElementsByAttribute code; MatchAttribute should Just Work... Created attachment 236130 [details] [diff] [review] patch #1 Implementation of GetElementsByAttributeNS in nsXULDocument and nsXULElement. See comment #14. The testcase is only for nsXULElement::GetElementsByAttributeNS. If you want to test nsXULDocument::GetElementsByAttributeNS then replace in the testcase in window.addEventListener: master = document.getElementById("master"); with master = document; Comment on attachment 236130 [details] [diff] [review] patch #1 >Index: content/xul/content/src/nsXULElement.cpp >+ if (!aNamespaceURI.EqualsLiteral("*")) { >+ nsresult rv = >+ nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI, >+ nameSpaceId); Some weird indentation here... tabs or something? >Index: content/xul/document/src/nsXULDocument.cpp Same in this file. >Index: dom/public/idl/xul/nsIDOMXULDocument.idl >Index: dom/public/idl/xul/nsIDOMXULElement.idl Change both IIDs? Btw, the nsDocument and nsGenericElement versions of GetElementsByTagNameNS have some left-over null-checks of |list| that are not needed anymore. Want to remove them while you're looking at this code? Most importantly, I don't think this code handles "*" for the namespace correctly... Back when I wrote comment 14 I didn't realize we needed kNameSpaceID_Wildcard. That value needs special handling in nsXULDocument::MatchAttribute, I think.... Created attachment 237172 [details] [diff] [review] patch #2 Changes: indentation corrected, interface UIDs changed, unnecessary null-checks removed, handling of namespace "*" in nsXULDocument::MatchAttribute. Comment on attachment 237172 [details] [diff] [review] patch #2 >Index: content/base/src/nsDocument.cpp >+ list = NS_GetContentList(this, nameAtom, nameSpaceId).get(); Move the declaration of |list| here too? Same for nsGenericElement. r+sr=bzbarsky with that; this looks great! Created attachment 237314 [details] [diff] [review] patch #3 declaration of |list| moved in nsGenericElement::GetElementsByTagNameNS and nsDocument::GetElementsByTagNameNS Comment on attachment 237314 [details] [diff] [review] patch #3 r+sr=bzbarsky. I'll get this checked in Sunday morning. By the way, did you run the existing getElementsByAttribute tests? In a build with --enable-tests, go into content/test and run "make check". Speaking of which, we should add tests for getElementsByAttributeNS to content/test/unit/test_nodelist.js. I can do it if you'd rather not, I guess. You could use as a model (and change the XUL file as needed if it's not set up to test this new code well). (In reply to comment #21) > By the way, did you run the existing getElementsByAttribute tests? In a build > with --enable-tests, go into content/test and run "make check". No, sorry I just used test cases like the one in the 1st attachment. I'll have a try adding a getElementsByAttributeNS test. Created attachment 238191 [details] [diff] [review] unit test for XULElement::GetElementsByAttributeNS(.) OK here is a unit test for XULElement::GetElementsByAttributeNS. I think it covers all interesting situations (or did I forget something?). And it passes with patch #3. Comment on attachment 238191 [details] [diff] [review] unit test for XULElement::GetElementsByAttributeNS(.) This is great! >Index: test_nodelist.js >+ // Test null namespace. This should be the same like getElementsByAttribute. "same as". I'll fix it before checking in. Created attachment 238362 [details] [diff] [review] Combined patch with comment grammar nit fixed. Checked in. Thanks for the patch!
https://bugzilla.mozilla.org/show_bug.cgi?id=239976
CC-MAIN-2016-44
refinedweb
1,120
51.04
Building a React Native Mobile App with AWS Amplify and Expo Aman Mittal— May 09, 2019 There is a joke going in dev community about serverless tech stacks using servers?! Some of the trolls even take that this an offensive way. What are they missing out is the advantages Serverless computing has to offer. Advantages like reduced development time and operation costs are some of the factors that could not be overlooked. Spending time and energy writing and wiring your application is worth rather than continuously managing resources and then worry about them at the time of scaling. This might sound too hot to some but serverless is a pragmatic solution in some use cases. In this tutorial, you will be learning how to integrate a serverless computing service called AWS Amplify in a mobile app using React Native. AWS Amplify has a complete set of toolchain with authentication, a choice between wiring and managing GraphQL or REST API, data storage, push notification and analytics. TLDR; - What is AWS Amplify? - Requirements - Getting Started - Configure Amplify User - Initialize AWS Amplify - Add a GraphQL API - Publish API to AWS Cloud - Integrating Expo app with Amplify SDK - Adding a Todo Input Field - Adding a Mutation using Graphql API - Run Query to fetch data - Conclusion What is AWS Amplify? Amazon Web Service is a well-known technology that provides cloud services. Since its launch in 2017, Amplify has come a long way in terms of providing a definitive toolchain. The first attraction for me personally is that it is open source. Next, are the CLI plugins and services that you can enable with one click when integrating it in a framework like React Native (or any other). Services such as support for GraphQL and REST APIs, basic UI components to get you started, authentication HOCs, storage, hosting and many more are available in its toolchain. Requirements Here is a complete list of plugins, packages, services you are going to need in order to gain something from this tutorial. - NodeJS v8.x.xor higher installed along with npm/yarn watchmanthe file change watcher for React Native project - AWS account - Amplify CLI plugin - Expo CLI (_earlier known as create-react-native-app) Note: To use any Amplify service and to follow the rest of this tutorial, you need an AWS account (which is free). If you do not have one, please consider signing up for one here for the free tier. Getting Started After you have the first three requirements from the previous section let us install the last two. Both of them are command line plugins to scaffold and configure our React Native + AWS Amplify project. Open a terminal window and execute the following command. npm install -g @aws-amplify/cli expo-cli Once both of the CLIs are installed, make sure you are on the same version (at least the major one) as we are. amplify --version# Output1.6.6expo-cli --version# Output2.15.4 Next, let us create a new React Native project using Expo CLI. expo-cli init expo-amplify-demo It will then prompt for a few questions. The first and most important one is choosing a workflow. Choose the default option, that is blank. Then it will prompt you to enter the name of your app, you can leave it to default or enter a name. You can use yarn to install dependencies by pressing Y. After a few moments, a new project directory will appear on the desired location. Traverse inside it before we proceed to the next step. Configure Amplify User Once you are signed-in to AWS console, open up a terminal window and run the following command. amplify configure This will open up the AWS console dashboard. Go back to terminal and press enter to continue. Next, are going to be a bunch of questions in order to configure a user account to use Amplify with your React Native application. These questions are as following: - Choose a region: us-east-2 - Specify the username of the new IAM user: expo-amplify-demo On entering the username, press enter and it will open AWS console again in a browser window for you to add a user. In the above screen, make sure that Programmatic access is checked. It allows adding the newly created user to have access to create resources in the form of different APIs and tools by providing you with an access key and secret key. Then click on button Next: Permissions. In the above screen, you will notice that a policy has been selected by default. Let it be. This provides you the full access to AWS services by enabling the aws user (the current user you are creating) to be an administrator. Then, click on Next: Tags. Leave this one blank, and click on Next: Review. Click on Create user on the next page and you will be directed to a new page where you will find Access Key and Secret Key. Do not close this window yet. Go to your terminal window, press the Enter key and it will ask you for the Access Key and the Secret Key. Enter both of them sequentially. Lastly, it will ask you about the profile name. You can enter the project name or user name here. Pressing enter for the last time will create a new AWS user. This section is complete. Initialize AWS Amplify To integrate AWS Amplify with the React Native app run the following command and be ready to answer a few more questions 😄. I know, I know. But imagine, not having these questions. The amount of setup being performed right now just by answering a few questions and pressing enters' a few times adds a lot of value by saving developer time. Open a terminal window, and make sure you are inside the React Native/Expo directory. amplify init This command will help you setup amplify SDK inside the React Native app. First, a few sets of questions that are prompted can be seen below. Next, you will be prompted with a question on whether to use an AWS profile or not. You have to choose Yes and then on to the next question, choose the user name that you created in the previous steps when configuring amplify. If you are setting up for the time, you are probably going to have only one username in the list, unlike below. After the amplify SDK initialization process is complete, notice there are some new file changes inside the project directory. A new directory amplify/ and a new file aws-exports.js The amplify directory takes care of configuration files that required in order to setup and makes amplify SDK work with the current React Native app. These configuration files are further divided into two parts. One set of files are just for your local machine and another is for aws cloud. Please remember, whenever you make changes related to amplify SDK in your app, they are, by default, modifications made to the local part or development part. When you are done making modifications and are ready to deploy your changes to the cloud, you use special amplify commands such as push. After running this push command, only the changes are written in aws cloud. The file aws-exports.js contains details related to amplify cloud service and credentials for the SDK to be imported inside the React Native app. You will be using this file later on. // WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.const awsmobile = {aws_project_region: 'us-east-2'}export default awsmobile Add a GraphQL API The idea of this section is that in your React Native app, you will be having an API that performs CRUD operations. CRUD stands for Create, Read, Update and Delete. Amplify toolchain makes this process easier using its own backend and data storing capabilities. Amplify supports HTTP requests to REST and GraphQL endpoints. Using AWS AppSync, you can easily build data-driven applications in real-time with offline capabilities. To set up an entire API for the app all you have to do is execute the below command. amplify add api This CLI execution automatically creates a fully functional GraphQL API including data sources, resolvers with basic schema structure for queries, mutations, and subscriptions, downloads client-side code and configuration files that are required in order to run these operations by sending requests. The above command will prompt you to choose between what type of API you want to write in. Choose GraphQL, and enter a profile API name. Next, it will again, give you two options to choose as to how you want to authenticate your AWS AppSync API. In a real-time application, you will have different users accessing the database and making requests to it. For that, you will always go with Amazon Cognito User Pool. This is more of a pragmatic approach. That step needs authentication process and we will be covering that in a future post. For the current demo, choose the option API Key. Do note that this option is only for brief prototype sessions or development process. Any AppSync API key expires after seven days lifecycle. For the next question Do you have an annotated GraphQL schema? the answer is N or no. Amplify comes with pre-defined schemas that can be changed later. Press Y for the next question: Do you want a guided schema creation? single object with fields. Next, it will ask if you want to edit the GraphQL Schema. Say yes to that for now. This will open up a new file called schema.graphql which contains a schema of type Todo with a different set of fields. This step does create a new folder inside amplify/backend/api/ that further contains the metadata information related to GraphQL API. Here is the model inside schema.graphql file. type Todo @model {id: ID!name: String!description: String} If you are not familiar to GraphQL models and its types here is brief information about them. A type in a GraphQL schema is that piece of data that is stored in the database. Each type can have a different set of fields. You can think of a type as an object coming from the JavaScript background. For example, in the above schema for Todo model is the type that has three fields: id, name and description. Also, @model is used for storing types in Amazon DynamoDB. This is the database is used by Amazon when storing our app data. Every type in a database generates a unique identity to each piece of information stored to further identify and persist in CRUD operations through HTTP requests. The id in this case is generated by Amplify and has a value of a built-in type of ID which, in GraphQL terminology, is known as a scalar type. You can read more about the different types identified in a GraphQL schema here. The exclamation mark ! signifies that the field is required when storing the data and it must have value. In the above schema, there are two required fields: id and name for the Todo type. Save this file, go back to the terminal window and press enter. You will be prompted with a success message (probably, in green). All the changes you have just made are now saved locally. Publish API to AWS Cloud To publish all the changes you have made (or left it default) in the local environment to AWS Cloud, run the command amplify push. On running the command, as a prompt, you get a table in return with information about resources that you have used and modified or enabled. The name of these resources is described in the Category section. The Resource name in the above table is the API name you choose in the previous section. Next column is the type of operation for the API to be sent, that is currently, Create. The provider plugin column signifies that these resources are now being published to the cloud. Press Y to continue. Amplify CLI interface will now check for the schema and then compile it for any errors before publishing final changes to the cloud. In the next step, it prompts whether you want to generate code for your newly created GraphQL API? Press Y. Then choose javascript as the code generation language. If you are using TypeScript or flow, now is the time to pick one. In the above image, for the last question, press Y. This will create a new folder inside the src directory which contains GraphQL schema, query, mutations, subscriptions as JavaScript files. On operating the API, these files can be accessible for different operations later. Y to the next question that asks you to update all GraphQL related operations. Also, let maximum statement depth be the default value of 2. It will take a few moments to update the resources on the aws cloud and will prompt with a success message when done. At the end of the success message you will get a GraphQL API endpoint and a GraphQL API Key (which we learned previously that it expires on the 7th day). You do not have to save it somewhere on your desktop and panic. This information is added to aws-exports.js file automatically for you now. Integrating Expo app with Amplify SDK To make use of amplify SDK in the React Native app, install the following dependencies. yarn add aws-amplify aws-amplify-react-native The package aws-amplify allows making requests to auth and API services provided AWS. The other package aws-amplify-react-native is specific to React Native as a library that contains useful components to be used in a project. You can verify that both of these packages were installed by peeking into package.json file > dependencies. "dependencies": {"aws-amplify": "^1.1.26","aws-amplify-react-native": "^2.1.10","expo": "^32.0.0","react": "16.5.0","react-native": ""}, Open App.js and add the configuration keys from aws-exports-.js and make amplify SDK aware of them. // App.jsimport React from 'react'import { StyleSheet, Text, View } from 'react-native'// ---------This is the part to addimport Amplify from 'aws-amplify'import config from './aws-exports'Amplify.configure(config)// ----------------------------- That's it for the integration part. Now let us write some GraphQL interactions and make sure it works with our React Native app in real-time. Adding a Todo Input Field To capture the user input, we are going to use a component state as follows. Add the below before the render method inside the App component. //App.jsstate = {name: '',todos: []} In the above state, there is a name field of the todo item and an array called todos that will be used to fetch all the todo items from the GraphQL API and display on the UI. Note that, there is another field called description in the GraphQL schema but since it isn't required, we are not going to use it here. Next, import TextInput and TouchableOpacity to create an input field and native button. Here is the complete code for App.js. import React from 'react'import {StyleSheet,Text,View,TextInput,TouchableOpacity} from 'react-native'import Amplify from 'aws-amplify'import config from './aws-exports'Amplify.configure(config)export default class App extends React.Component {state = {name: '',todos: []}onChangeText = (key, val) => {this.setState({ [key]: val })}addTodo = () => {}render() {return (<View style={styles.container}><TextInputstyle={styles.input}value={this.state.name}onChangeText={val => this.onChangeText('name', val)}<TouchableOpacity onPress={this.addTodo} style={styles.buttonContainer}><Text style={styles.buttonText}>Add +</Text></TouchableOpacity></View>)}}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: '#fff',paddingHorizontal: 10,paddingTop: 50},input: {height: 50,borderBottomWidth: 2,borderBottomColor: 'blue',marginVertical: 10},buttonContainer: {backgroundColor: '#34495e',marginTop: 10,marginBottom: 10,padding: 10,borderRadius: 5,alignItems: 'center'},buttonText: {color: '#fff',fontSize: 24}}) Go to the terminal window and run the command npm start to view this either in an iOS simulator or an android emulator. You will get the following result. Adding a Mutation using a todo item and to retrieve the same you need some business logic to communicate with GraphQL backend. Let us start with a mutation. In the file App.js, import API and graphqlOperation from aws-amplify. Here, API is the category for AWS resource and the later is the method to run either a mutation or the query. Inside the src/graphql/mutation.js file you will find some mutation functions that we can make use of to create, delete, or update a note in the database. Also import createTodo from this file. //App.js// ...import Amplify, { API, graphqlOperation } from 'aws-amplify'import config from './aws-exports'import { createTodo } from './src/graphql/mutations'// ... Add a function addTodo before the render method which uses API.graphqlOperation() the method from amplify SDK. This method will intake the mutation as the first argument and whatever input user enters inside the app UI, as the second argument. // App.jsaddNote = async event => {const { name, todos } = this.stateevent.preventDefault()const input = {name}const result = await API.graphql(graphqlOperation(createTodo, { input }))const newTodo = result.data.createTodoconst updatedTodo = [newTodo, ...todos]this.setState({ todos: updatedTodo, name: '' })} The above function takes name as the input where name is the text of a todo item. Also, notice the use of async/await. This helps to fetch the result from the mutation and update the todos array in the state with the latest todo item and previous or existing data in that array. After updating the state, clear the value of the input field name, and display in the UI by setting it back to an empty string. I urge you to add at least one list of item. You would not get any confirmation right now from the API whether the data field has been added to the GraphQL backend or not. Run Query to fetch data If you want to read data (and render it in the UI of the app), the process is known as a query. To fetch all the data from GraphQL API and display it on the device's screen, let us use the query from amplify GraphQL pre-generated file inside src/graphql/queries.js (just like we did with mutation). // eslint-disable// this is an auto generated file. This will be overwrittenexport const getTodo = `query GetTodo($id: ID!) {getTodo(id: $id) {idnamedescription}}`export const listTodos = `query ListTodos($filter: ModelTodoFilterInput$limit: Int$nextToken: String) {listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {items {idnamedescription}nextToken}}` Import listTodos inside App.js from the above file. //App.jsimport { listTodos } from './src/graphql/queries' We need to fetch the data at the time where the component gets rendered. For this, let us a lifecycle method called componentDidMount. Since this is going to be an asynchronous operation async/await is being used here too. Just after the state is defined in the App component, add the following snippet of code. // App.jsasync componentDidMount() {try {const todos = await API.graphql(graphqlOperation(listTodos))console.log("todos: ", todos)this.setState({ todos: todos.data.listTodos.items })} catch (err) {console.log("error: ", err)}} Refresh the app by saving the file you will notice that on UI screen nothing happens. That's because we haven't added the rendering logic to display this list of items. However, you can verify that data is being fetched using console statement and by looking quickly at the Expo CLI. During the previous step, I did add an item to the list. That's the proof of that. Now let us display this item on the device's screen. Inside the render method, add this after the TouchableOpacity component. We are going to use JavaScript's map function to traverse the todos array. // App.js{this.state.todos.map((todo, index) => (<View key={index} style={styles.todo}><Text style={styles.name}>{todo.name}</Text></View>))}// Corresponding styles for above jsxtodo: {borderBottomWidth: 1,borderBottomColor: "#ddd",paddingVertical: 10},name: { fontSize: 16 } On running npm start (or if it is already running, just the save the App.js file) you will get the following output. Conclusion This tutorial is complete. I am sure by now you have gained enough knowledge to build your own React Native app with AWS Amplify and AppAsync. Also, did you notice the amount of code written inside App.js? It is far less than a traditional app that uses self-backend techniques. This bare minimum demo can serve you a lot better. You can find the complete code for this post in this Github repository. Originally published at Heartbeat
https://amanhimself.dev/building-a-react-native-mobile-app-with-aws-amplify-and-expo/
CC-MAIN-2020-10
refinedweb
3,434
65.52
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.8) Gecko/20050511 Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.9) Gecko/20050626 Firefox/1.0.5 According to Bonsai, some url-checks of image.src have been added for bug 292774 and bug 292737 (I cannot see bug 292774 and bug 292737). But, those can be bypassed. The following url-check has been added for bug 292774. viewImage : function (e) { urlSecurityCheck( this.imageURL, document ) openUILink( this.imageURL, e ); }, The following url-checks have been added for bug 292737. browser.js: else if (makeURL(this.target.src).scheme == "javascript") disableSetWallpaper = true; setWallpaper.xul: if (makeURL(window.arguments[0].src).scheme == "javascript") return false; Vulnerable code from nsContextMenu.prototype.setTarget: if ( this.target.nodeType == Node.ELEMENT_NODE ) { if ( this.target.localName.toUpperCase() == "IMG" ) { this.onImage = true; this.imageURL = this.target.src; Exploit: 1) In an XHTML document, since tags are case-sensitive, <IMG> element is not a HTMLImageElement, it is a HTMLUnknownElement that does not have |src| property. thus, content can make chrome access content-defined getter function of |src| property of <IMG> element. 2) The approach for bypassing url-check is the same as Bug 249332 (Bypassing CheckLoadURI using custom getters and changing toString returns). Note: The trunk is not affected thanks to the fix for Bug 281988. Reproducible: Always Steps to Reproduce: Created attachment 187391 [details] I've confirmed that this works on: Firefox 1.0.5 2005-06-26-05 Mozilla 1.7.9 2005-06-24-08 Created attachment 187392 [details] Arbitrary code execution via setWallpaper() I've confirmed that this works on: Firefox 1.0.5 2005-06-26-05 This is more or less bug 290324 for Firefox itself, except using .xhtml instead of creating dynamic XUL nodes.. Most or all of those places would be safer doing an instanceof check instead. Patch coming up Maybe another day or two to test and make sure we're ready to take a fix for this. jst says, "remember to look for nodeName" the patch in bug 290420 covers the same issues in browser.js, but misses the actual contextMenu.js spot. Some of these are fixed on the trunk. This xhtml <IMG> example in particular is changed to use instanceof What exactly is left to do on trunk for this bug? Created attachment 187685 [details] [diff] [review] Check instanceof rather than spoofable localName Comment on attachment 187685 [details] [diff] [review] Check instanceof rather than spoofable localName Mostly ok, but if you've got time for a few tweaks then keep reading... > if ( area.nodeType == Node.ELEMENT_NODE > && >- area.localName.toUpperCase() == "AREA" ) { >+ area instanceof HTMLAreaElement ) { ( area instanceof HTMLAreaElement ) implies area is an element node. >+ if ( ( elem instanceof HTMLQuoteElement && 'cite' in elem && elem.cite) || >+ ( elem instanceof HTMLTableElement && 'summary' in elem && elem.summary) || ( elem instanceof HTMLQuoteElement ) implies 'cite' in elem (although not elem.cite of course). Same goes for table summary. >+ ( ( elem instanceof HTMLInsElement || elem instanceof HTMLDelElement ) && > ( ( 'cite' in elem && elem.cite ) || > ( 'dateTime' in elem && elem.dateTime ) ) ) || > ( 'title' in elem && elem.title ) I discovered that we can use ( elem instanceof HTMLModElement ) which covers both INS and DEL. Again, the 'cite' and 'dateTime' in elem are implied. ( elem instanceof HTMLElement ) could be used instead of 'title' in elem. >+ if (node instanceof HTMLInputElement) >+ return (node.type == "text" || node.type =="password") >+ else >+ return (node instanceof HTMLTextAreaElement); I like this fix but I would like it more if you added a space between == and "password" and more still if you fixed the other two files in the same way ;-) >+ if (e.type.toLowerCase() == "text" || e.type.toLowerCase() == "hidden" || >+ e instanceof HTMLTextAreaElement) I don't think this is spoofable because we already know this is a form element. That said, you could probably check e.type everywhere. Comment on attachment 187685 [details] [diff] [review] Check instanceof rather than spoofable localName Let's get this in on the branches. Leaving it up to dveditz to decide whether or not we want the tweaks. a=jay we do want the tweaks, waste of Neil's time if we don't use his effort to get better. Comment on attachment 187685 [details] [diff] [review] Check instanceof rather than spoofable localName >- if (node.localName.toUpperCase() == "INPUT") { >- var attrib = ""; >- var type = node.getAttribute("type"); >- >- if (type) >- attrib = type.toUpperCase(); >- >- return( (attrib != "IMAGE") && >- (attrib != "CHECKBOX") && >- (attrib != "RADIO") && >- (attrib != "SUBMIT") && >- (attrib != "RESET") && >- (attrib != "FILE") && >- (attrib != "HIDDEN") && >- (attrib != "RESET") && >- (attrib != "BUTTON") ); >- } else { >- return(node.localName.toUpperCase() == "TEXTAREA"); >- } >+ if (node instanceof HTMLInputElement) >+ return (node.type == "text" || node.type =="password") >+ else >+ return (node instanceof HTMLTextAreaElement); There's a reason that the old code here was checking that the type is not one of a long list: inputs with an unrecognized type attribute are treated as type="text". This behavior is important for future compatibility. Any chance this could be fixed? Er, actually, never mind. Now I see that the .type property (but not getAttribute()) is normalized to "text" in those cases. Fixed on trunk and branches guys, this broke seamonkey's context menu due to a syntax error Error: missing ) after condition Source File: chrome://communicator/content/nsContextMenu.js Line: 398, Column: 25 Source Code: elem.getAttributeNS(XMLNS, "lang") ) { it would've been nice if the patch that was actaully checked in had been attached here... Created attachment 187837 [details] [diff] [review] fix syntax error Sorry my earlier sr= submit didn't appear to go through, but looks like neil covered it anyway. I double-checked what was checked in and this affects only trunk suite. The initial patch was developed for the branches and xpfe moved things around a bit on trunk, and I dropped the || during the conflict merge (but did remember to add it in the browser.js version). The thunderbird version mail/base/content/nsContextMenu.js didn't get the added "|| elem.getAttributeNS(XMLNS, "lang")" from bug 207274 -- is that going to matter? I guess I'll comment over there. checked in biesi's fix. findParentNode() is remaining. Vulnerable code from contentAreaClick(): linkNode = findParentNode(event.originalTarget, "a"); On the trunk, this can be combined with other bug to execute arbitrary code. attachment 188087 [details] in Bug 299520 comment 1 A exploit testcase that is using xhtml <A>. Created attachment 188089 [details] [diff] [review] Remove findParentNode (xpfe version) I changed the useful invocation of findParentNode into a while loop. The other use is unnecessary because scrollbar.xml blocks clicks on scrollbars. Comment on attachment 188089 [details] [diff] [review] Remove findParentNode (xpfe version) sr=dveditz This is Suite only, need mozilla/mail and mozilla/browser versions (yay forking!) Can anyone jump in here and get patches ready for landing on the Aviary branch for Firefox and Thunderbird? Reassigning to jst to patch up browser and mail. Dveditz can patch the 1.7 branch when those patches are ready. Created attachment 188372 [details] [diff] [review] Branches patch I just removed all references to findParentNode and replaced them with something that I think should be equivalent although I haven't even checked my typing. Comment on attachment 188372 [details] [diff] [review] Branches patch r/sr=dveditz for the branch/FE ports Let's get those patches checked in the appropriate places asap. a=jay again. :-) Dveditz: Do we need to get this on the Trunk as well? If so, can you a= for 1.8b3 and get it checked in there as well? Comment on attachment 188089 [details] [diff] [review] Remove findParentNode (xpfe version) a=dveditz Comment on attachment 188372 [details] [diff] [review] Branches patch a=dveditz for branches Neil's patch checked into the aviary1.0.1 branch Fixed on the 1.7 branch xpfe patch checked in to trunk. Checked neil's patch into the trunk. Please open any variations or similar problems as new bugs v.fixed on aviary with Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.9) Gecko/20050706 Firefox/1.0.5 Adding distributors Security advisories published This is MFSA2005-55 and assigned as (issue #8). Is it possible to update 'Alias' field to include SA16043 now? This fix caused bug 301873.
https://bugzilla.mozilla.org/show_bug.cgi?id=298892
CC-MAIN-2016-30
refinedweb
1,353
60.61
Created on 2016-05-20 12:23 by haypo, last changed 2016-12-15 15:33 by brendan-donegan. The webbrowser opens almost all browsers in background mode, it looks like only Elinks is not opened in this mode. Problem: the webbrowser doesn't read the exit status of the browser, and so create zombi process. On Python 3.6, the subprocess module now emits a ResourceWarning in this case (issue #26741). For example, the following script shows a zombi process ("<defunc>"): --- import webbrowser, os b = webbrowser.get("firefox") b.open("") b = None os.system("ps ax|grep firefox") input("press ENTER when firefox exited") os.system("ps ax|grep firefox") --- I guess that Python should use os.fork() somehow to fix this issue. Another option is to hack the Popen object to not display the warning, but I don't think that it's a safe option. See also the issue #27068 "Add a detach() method to subprocess.Popen", but I don't think that it is directly related to background processes run by webbrowser. I checked how "xdg-open" works. It looks like the command works as webbrowser: create a child process "firefox URL", but then it waits until the command completes. In fact, "firefox URL" exits quickly. So we can try "background = False" for firefox. Well, at least with my Firefox 46.0.1. I think the Firefox command will exit immediately if it just signals an existing Firefox process and window, but becomes the main Firefox process if there isn’t already one running. Background = False sounds like it won’t help. Don’t we want the opposite? This appears to be Firefox specific? At least: b = webbrowser.get("chromium-browser") b.open("") returns simply: True With no exception
http://bugs.python.org/issue27069
CC-MAIN-2017-13
refinedweb
293
68.97
Last week we looked at creating a new task in an Ember application. This involves accepting data from the form, creating a new task in Ember Data, and then saving the task, which will send a POST request to the server. A good API will validate incoming data to ensure that it is of the correct format. This will typically involve the API sending back the correct HTTP status code and a helpful message describing why the input was incorrect. However, we can try to prevent the request ever hitting the API server by also doing validation in the client. In today’s tutorial we will be looking at validation to Ember forms. Adding the Ember Validation addon Validation is like the canonical use case of Open Source Software. You should never have to write validation code because there’s always an open source solution waiting to be pulled into your project. A good Ember addon is the Ember Validation package. This is what we’ll be using in this tutorial. To add addon to your project you can add the following line to your package.json file: "ember-validations": "2.0.0-alpha.3" At the time of me writing this, 2.0.0-alpha.3 is the latest release. Next run the following command to install the package: npm install [/bash] ## Writing the test The first thing we need to do is to write a test that will show the functionality we intend to build: ```js test(‘validate task data’, function(assert) { visit(‘/tasks/new’); andThen(function() { fillIn(‘.task-title’, ”); click(‘button’); }); andThen(function() { assert.equal(currentURL(), ‘/tasks/new’); }); }); As you can see, this test is fairly similar to the test we wrote last week for adding a new task. However, in this task we want to assert that the user is returned to the /tasks/new URL when the task title is blank. If you run this test now you should see it fail because the user will be redirected to tasks/1. With the test in place, we can write the code to make it pass! Add the validation to the Controller To make the test pass we need to run a validation process at some point during the request execution that will check to ensure the task title is not blank. Typically I think this is probably best handled in the model because the requirement of a task title is the concern of the model. However, I’m not entirely sure how to do that with this addon, so validation in the Controller will do fine for now. To add the validation functionality to our Controller from last week we can include it as a mixin: import Ember from ’ember’; import EmberValidations from ’ember-validations’; export default Ember.Controller.extend(EmberValidations.Mixin, { }); Next we can add a displayErrors flag property. This will be used for displaying the errors in the template: displayErrors: false, And finally we will also add a validations object that will contain the validation rules. validations: { title: { presence: true } }, In this case we only have a single rule. Validate on save The process of validating the new task object will be as follows. - We will create the Taskobject as normal. - Next we will validate the object - If the object is valid we can call the save method and redirect to view the new task - If the task is not valid we can flip the displayErrors flag which will display the errors in the template This process looks like this in code: createTask: function() { var task = this.store.createRecord(‘task’, { title: this.get(‘title’) }); var self = this; this.validate().then(function() { if (self.get(‘isValid’)) { task.save().then(function(task) { self.transitionToRoute(‘task’, task); }).catch(function() { alert(‘Oh no! :(‘); }); } }, function() { self.set(‘displayErrors’, true); }); } Note, we’re validating the Controller data, not the model object itself, but you get the point. Add errors to form Finally we can add the errors to the template. First we check to see if the displayErrors flag is true. We only want to display the errors if this flag is set to true: {{#if displayErrors}} {{/if}} Next we iterate through the errors array: {{#if displayErrors}} {{#each errors.title as |error|}} <div> {{error}} </div> {{/each}} {{/if}} Now if you run the tests again, you should see them all pass! Conclusion Validation is never something you want to write yourself. Every language and every framework already has a validation library. Adding validation to an Ember project isn’t hard. We’ve added the validation to the controller and to the form with only a couple of lines. Of course, in a real project, your validation requirements would probably be a lot more complicated. We also really should deal with the server sending us validation problems. The server will really be your one true source and so your ember application should be prepared to accept validation responses and treat them in the same way as client response. If you don’t do this, your application will be very annoying to use for the end user.
https://www.culttt.com/2015/08/03/adding-validation-to-ember-forms/
CC-MAIN-2018-51
refinedweb
845
62.98
README @activescott/cookieconsent@activescott/cookieconsent This is a just-enough-working fork of. This fork has the following differences: - It works. I had to update some dependencies to get it to even build. It appears that Osano has decided to abandon the open source version of their package with a response of "we recommend just using the free version of our commercial offering". - Uses the v4.0 code base which was never published to npm, but was pushed to github. - It exports a UMD (with webpack configured like this) module only. It does attach a global window.CookieConsentto the window by default. - Includes some minimal typescript types in the package. Exporting the original source rather than the minified bundle. I presume you'll use your own bundler.This was a mess w/ node & jest, so it does export a UMD bundled module now, but it isn't minified. - It is automatically deployed according to the release process described below (so send me your PR and as long as it passes CI and is reasonable improvement I will merge it). UsageUsage To use it, install using npm install -P "@activescott/cookieconsent" Release Process (Deploying to NPM) 🚀Release Process (Deploying to NPM) 🚀 We use semantic-release to consistently release semver-compatible versions. This project deploys to multiple npm distribution tags. Each of the below branches correspond to the following npm distribution tags: To trigger a release use a Conventional Commit following Angular Commit Message Conventions on one of the above branches. What's next?What's next? I don't have concrete plans, but if we had a quorum of 2-3 other folks interested in keeping this fork up to date, I'd be willing to invest some time to automate publishing and start accepting PRs and issues (although now that I've looked through this code base 😬, we should really just rewrite it). I just want to keep my use of this package working for now. I am considering the following: - Setting up automated publishing to NPM with semantic-release - Is it useful to add a module="dist/esm/index.mjs"declaration in package.json? Node seems ot have deviated from this approach and wants entirely separate packages for esm vs cjs: remainder of this readme (below) is from the original repo that this was forked from at What is Cookie Consent?What is Cookie Consent? Cookie Consent is a lightweight JavaScript plugin for alerting users about the use of cookies on your website. It is designed to help you quickly comply with the EU Cookie Law, CCPA, GDPR and other privacy laws. We made it fast, free, and relatively painless. Cookie Consent is seen over 2 BILLION times every month and is used on millions of sites, making this by far the most popular consent project on the internet. We welcome community contributions and actively review pull requests. Hosted Zero Config ConsentHosted Zero Config Consent Our parent company Osano actively maintains this open source project. Osano is a B-corp and is backed by millions of dollars in venture capital to create data privacy tools for the world. Our mission is to create transparency in data, please consider joining our team. Ensuring that your website is compliant with various laws can be complicated. To effectively use any open source consent manager, you will need to do GeoIP lookups, adjust the consent types based on visitor location, callback and save consents in a database, and create callbacks to load scripts after consent is granted. Osano offers a completely free hosted consent management platform, with additional features. If you have a high traffic website or need additional privacy tools, Osano offers paid plans as well. Unless you specifically need the open source tool, most website owners will be better served by the hosted version. If you use Osano for your business, please support continued development by purchasing a paid plan. The hosted version of the cookie consent manager provides additional capabilities such as: - Multi-lingual, translated into 38 languages and growing. Visitors automatically see the dialog in their browser or OS preferred language. - Consents are stored automatically on the blockchain. REST API calls are available to developers to search and browse the consent records. - 3rd party script blocking and loading does not require callbacks but is instead configurable from a dashboard providing developers with control over what the marketing team can enable or disable. - Hosted on AWS Cloudfront with edges around the globe for Basic UseBasic Use With version 4.0 you only need to attach the script as we've bundled everything together now. The initialization style has changed as have the callbacks (they're gone). Please see the text below to get started. Then, take a look at updated API via the docs. ModuleModule import CC from "CookieConsent" // or const CC = require( "CookieConsent" ) ClassicClassic const CC = window.CookieConsent Initialization:Initialization: const cc = new CC({ //...options, type : "categories" }) Lifecycle hooks, are now events:Lifecycle hooks, are now events: cc.on( "initialized", ( ...args ) => console.log( args ) ) cc.on( "error", console.error ) cc.on( "popupOpened", () => console.log( "Popup Open" ) ) cc.on( "popupClosed", () => console.log( "Popup Closed" ) ) cc.on( "revokeChoice", () => console.log( "Popup Reset" ) ) cc.on( "statusChanged", ( ...args ) => console.log( args ) ) Version 4.0Version 4.0 Lots of updates & some breaking changes... but they're all for the better, we promise! Version 3.1Version 3.1 Reflects the ownership change of the Cookie Consent project. Now actively maintained by: - @arlogilbert - @L0key - @pgoforth Version 3.0Version 3.0 Version 3.0 is a complete rewrite from version 2. The most substantial new features are: - Ability to GeoLocate and only show the add-on to people in the relevant countries - Callback hooks for showing/accepting/revoking the banner - Support for different types of compliance, giving you the flexibility to obey even the strictest cookie laws - Easy no-fuss themes and customisable styles InstallationInstallation The easiest way to get up and running is to use our wizard. You can also install this project through npm: npm install cookieconsent yarn add cookieconsent@3 bower install cookieconsent Or via a jsDelivr: <script src=""></script> DocumentationDocumentation See our full documentation. ContributingContributing Feel free to improve the plugin and send us a pull request. The easiest way to develop is to host the files with a local webserver. e.g. python -m SimpleHTTPServer We use Babel, Terser, and PostCSS to compile the SCSS and minify the JavaScript. You can run a build with: npm run build or yarn run build Legal Mumbo JumboLegal Mumbo Jumbo Osano is a registered trademark of Osano, Inc. Nothing on the Osano website, platform, services, or software, nor any portion thereof constitutes actual legal or regulatory advice, opinion, or recommendation by Osano, Inc. or Osano International Compliance Services LTD. If legal assistance is required, users should seek the services of an attorney. Export ControlExport.
https://www.skypack.dev/view/@activescott/cookieconsent
CC-MAIN-2022-27
refinedweb
1,139
56.76
Attribute Interface for file I/O. More... #include <GA_AIFFileH9.h> Attribute Interface for file I/O. This class provides an interface used to save and load attributes to and from files. In H9, the attributes stored their data interleaved for each element. GA prefers to process data in arrays rather than interleaved. This class contains SaveInfo and LoadInfo which help with the interleaving/de-interleaving process. Definition at line 43 of file GA_AIFFileH9.h. Definition at line 46 of file GA_AIFFileH9.h. Data types stored in Houdini 9 data files. Definition at line 52 of file GA_AIFFileH9.h. Attribute type modifiers stored in Houdini 9 data files. Definition at line 65 of file GA_AIFFileH9.h. Definition at line 48 of file GA_AIFFileH9.h. Definition at line 49 of file GA_AIFFileH9.h. Call once finished loading the attribute data for all the elements to perform any clean up or finalization that may be needed. Query the definition for this custom AIF. The first call will register this AIF in a thread-safe manner. Create load information for an H9 attribute. Create save information for a given GA attribute. Load the attribute data for a given element. Save the element data for a given attribute. Save the attribute defaults to the output stream. Save the string table to the output stream. This method should only be called when getSaveInfo(attrib).getType() == ATTRIB_INDEX. Skip data unsupported data in the input stream.
http://www.sidefx.com/docs/hdk/class_g_a___a_i_f_file_h9.html
CC-MAIN-2018-51
refinedweb
238
62.34
Dim oCars as Object Dim oCar as Object Set oCars = oComVB6.FetchCarsByColour("blue") For Each oCar in oCars MsgBox "Make is " & oCar.Make Next oCar Skip forward a few years: Vantive is still kicking and it is time to convert your VB6 COM component to .Net. Our VB6 Collection object is gone, what will we use instead? What about an array of objects? So in .Net we have: public class Car : ICar {...} public Car[] FetchCarsByColour(string colour) {...} To access these from Vantive VBA, this should do the trick: Dim oCars() as Object Dim oCar as Object oCars = oComNet.FetchCarsByColour("blue") For I = 0 to UBound(oCars) ... This works fine via VB6, but when you try to compile this in Vantive VBA, you'll get a "Cannot assign whole array" error message on the oCars=... line. The solution is to use the ArrayList class. Like this: public ArrayList FetchCarsByColour(string colour) {...} Which you can then access in Vantive VBA exactly as you could with the VB6 collection, including the "Count" method: Dim oCars as Object Dim oCar as Object Set oCars = oComNet.FetchCarsByColour("blue") For Each oCar in oCars MsgBox "Make is " & oCar.Make Next oCar MsgBox "You found " & oCars.Count & " cars"
http://juststuffreally.blogspot.com/2008/07/moving-your-vb6-com-collections-to-net.html
CC-MAIN-2018-43
refinedweb
201
75.71
Three times a week (Monday/Wednesday/Friday), John Savill tackles your most pressing IT questions. Read through the FAQ archives, or send him your questions via email. Q. How can I reinstall OneDrive on Windows 10? Q. How can I make my DFS Namespace highly available? Q. If my DFS Namespace is unavailable will DFS-R stop replicating? Q. How can I reinstall OneDrive on Windows 10? Dept - Windows 10 A. OneDrive is a core part of Windows 10 and before you try and reinstall be sure that is the best approach. I have seen problems before such as it appears to hang logging in however this is nothing to do with the client but the service availability itself so the first check is the service health. Navigate to servicestatus and ensure the OneDrive service has no issues. If the OneDrive service is healthy and you cannot logon you can remove the cached credential for OneDrive: - Stop OneDrive by right clicking on the OneDrive system tray icon and selecting Exit - Open Control Panel - Select User Accounts - Click the Manage your credentials link - Set the type to Windows Credentials and then select the OneDrive Cached Credential and click Remove - Restart OneDrive (Start - Onedrive) If this still does not work you can try a reset by running command (elevated): %localappdata%\Microsoft\ OneDrive\onedrive.exe /reset Within a few minutes OneDrive should start again if not just manually start OneDrive. As a last attempt you can uninstall and reinstall: - Stop OneDrive (stop the OneDrive.exe process) - Uninstall %SystemRoot%\SysWOW64\ OneDriveSetup.exe /uninstall (or System32 instead of SysWOW64 if 32-bit) - Navigate to about/en-us/download/ and download OneDrive via the (Need to reinstall link which is fwlink/p/?LinkId=248256) - Run through setting up accounts again You have now completely reinstalled OneDrive! Once again, this is very rarely required. Make sure you are sure there is no service problem before modifying your client machine configuration. Q. How can I make my DFS Namespace highly available? Dept - DFS A. Distributed File System Namespaces (DFS-N) provides the ability to create a logical namespace that has nodes that point to file shares in the environment. Using this method users can access a single logical namespace that can be navigated like a file system where different nodes redirect to sets of file servers. Additionally each node can have multiple targets which enables users to be redirected to a target closest to them or where the closest target is not available the next closest target. There are two types of DFS-N deployment which will drive how to make it highly available. - Stand-alone - With the stand-alone deployment the namespace is stored locally on the nameserver. To make this highly available it needs to be deployed to a Failover Cluster. - Domain-integrated - With domain-integrated the namespace is stored in Active Directory. To make this highly available simply deploy multiple namespace servers that link to the same domain-integrated namespace. Ensure you also have multiple domain controllers as this mode relies on AD being available. Q. If my DFS Namespace is unavailable will DFS-R stop replicating? Dept - DFS A. No. While DFS-R may initially be configured via DFS Management as part of a DFS namespace the replication partnership is separate from DFS-N. If DFS-N servers were unavailable there would be no interruption to the DFS-R replication.
http://www.itprotoday.com/cloud-data-center/mixed-bag-onedrive-and-distributed-file-system-availability
CC-MAIN-2018-30
refinedweb
566
63.39
When a system fails or aborts a shadow set, this significant event causes every shadow set to be reassessed by all other systems with that shadow set mounted. All active minimerge, full merge, or copy operations cease at this time, returning their resources to those systems. (However, if a system is performing a minicopy operation, that operation continues to completion.) Those systems wait a predetermined amount of time, measured in seconds, before each attempts to manage any shadow set in a transient state. This pause is called a significant-event recovery delay. It is the total of the values specified for two system parameters, SHADOW_REC_DLY and RECNXINTERVAL. (The default value for each is 20 seconds.) If the value of the significant-event recovery delay is the same on all systems, it is not possible to predict which systems will manage which shadow set. However, by making the value of the significant-event recovery delay different on all systems, you can predict when a specific system will begin to manage transient-state operations. 6.12.6 Managing Merge Operations A merge transient state is an event that cannot be predicted. The management of merge activity, on a specific system for multiple shadow sets, can be predicted if the priority level settings for the shadow sets differ. In the following example, there are four shadow sets, and the SHADOW_MAX_COPY parameter on this system is equal to 1. The value of 1 means that only one merge or copy operation can occur at the same time. This example illustrates how the priority level is used to select shadow sets when only merge operations are involved. Two shadow sets are assigned a priority level and two have the default priority level of 5000. The four shadow sets DSA1, DSA20, DSA22, and DSA42, are mounted on two systems. DSA20 and DSA42 are minimerge enabled. $ SET SHADOW/PRIORITY=7000 DSA1: $ SET SHADOW/PRIORITY=3000 DSA42: ! DSA20: and DSA22: are at the default priority level of 5000 In this example, when one of the systems fails, all shadow sets are put into a merge-required state. After the significant-event recovery delay time elapses, this system evaluates the shadow sets, and the operations are performed in the following order: A copy transient state can be predicted by the user because it is the result of direct user action. Therefore, a full copy operation caused by adding a device to a shadow set is not considered a significant event in the cluster. The copy operation is managed by the first system that has an available resource. In the following example, assume there are four shadow sets, and the SHADOW_MAX COPY parameter on this system is equal to 1. Recall that the shadow sets that are not assigned a specific level will have a default priority level assigned. For the following example, assume that: The user adds a device to DSA1. This is not a significant event, and this system will not interrupt the full copy operation of the DSA22 in favor of performing the DSA1 full copy operation. To expand on this example, assume that a system fails (a significant event) before the copy operations have completed. All shadow sets will be put into a merge required state. Specifically, DSA1, DSA20, and DSA22 are put into a full merge state, and DSA42 is put into a minimerge state. After the significant event recovery delay expires, this system begins to evaluate all the shadow sets in a transient state. The operations take place in the following order: Thus, in this example, the priority level is used to direct the priority of merge and copy operations on this system. 6.12.8 Managing Transient States in Progress SHADOW_MAX_COPY is a dynamic system parameter that governs the use of system resources by shadowing. Shadowing can be directed to immediately respond to changes in this parameter setting with the following DCL command: $ SET SHADOW/EVALUATE=RESOURCES This command stops all the current merge and copy operations on the system on which it is issued. It then restarts the work using the new value of SHADOW_MAX_COPY. This command is also useful in other circumstances. For example, if a shadow set had a priority level of 0 or another low value, the SET SHADOW /PRIORITY=n command can be used to increase the value. Then, by using the /EVALUATE=RESOURCES qualifier, the priority of shadow sets in a transient state is reevaluated. The /PRIORITY and /EVALUATE=RESOURCES command qualifiers can be used on the same command line. When a significant event occurs, all of the SHADOW_MAX_COPY resources are applied. If the value of SHADOW_MAX_COPY is modified using the SYSGEN SET and WRITE ACTIVE commands, and then a SET SHADOW /EVALUATE=RESOURCES is issued, the new value of SHADOW_MAX_COPY has a direct and immediate affect. To determine which system is controlling a transient operation, enter the following command: $ SHOW SHADOW/ACTIVE DSAn: To determine the priority values assigned to each shadow set, enter the following command: $ SHOW SHADOW/BY_PRIORITY DSAn: Table 6-1 summarizes the user-visible impact of transient state events from the viewpoint of a shadow set on one system in an OpenVMS Cluster system. For each type of transient state event, the effects on the shadow set, when a merge (full merge, HBMM, or controller minimerge) or copy (full or minicopy) operation was already underway, are listed. The terms Canceled, Restarted, Continued, and Suspended, described in the table key have the same meaning in this table as in Volume Shadowing for OpenVMS messages. Note also the following characteristics of merge and copy operations: Canceled---Operation is stopped so that it can be restarted or continued on any system that is eligible. Restarted---Operation must start over again on the same system at LBN 0 when the operation is resumed. Continued---Operation continues at the LBN where it left off when it was canceled or suspended. Suspended---Operation is stopped such that the operation for that SS can be initiated, restarted, or continued only on the same system where the suspended operation was active. This chapter provides an overview of the differences as well as considerations you should review before linking programs on OpenVMS I64 systems. Major topics include: For release notes on the linker, refer to the HP OpenVMS Version 8.2 Release Notes. 7.1 Linker Utility New Features The purpose of the linker is to create images (that is, entering® Itanium® architecture, some aspects of linking modules on OpenVMS I64 systems are different from linking on VAX and Alpha systems. Overall, however, the OpenVMS I64 Linker interface as well as functional capabilities (for example, symbol resolution, virtual memory allocation, and image initialization) are similar to those on OpenVMS VAX and Alpha systems. 7.1 list contains new qualifiers that are supported by the OpenVMS I64 Linker: These qualifiers and options are described in the following sections. 7.1.1.1 Data Types of Symbols must Match on I64 On OpenVMS Alpha, there can be a symbol that is defined as a piece of data but referenced as if it were a function. There is no way, using the Alpha object language, that this situation can be detected by the linker. But on OpenVMS I64, the linker can detect a symbol's data type mismatch. The OpenVMS I64 linker receives information which marks a symbol as a function (FUNC), a piece of data (OBJECT) or unknown (NOTYPE). It also receives relocations which tell the linker when to create a function descriptor for symbols that are defined or referenced as a function. If the types of a symbol are not unknown (not NOTYPE), they must match. If the definer sets the type as unknown, the referencer type cannot be a function. For example, take the two modules FIRST.C and SECOND.C: FIRST.C #include <stdio.h> int a; int aa; extern int second (); void main () { printf ("The address of 'a' is %x\n", &a); printf ("The address of 'aa' is %x\n", &aa); second (); } SECOND.C #include <stdio.h> extern int a(); extern int aa(); void second () { printf ("The address of 'a' is %x\n", &a); printf ("The address of 'aa' is %x\n", &aa); } When you link FIRST and SECOND, you get the following informational messages (based on the symbol descriptors) and warning messages (based on the relocations) from the linker: $ link first,second %ILINK-I-DIFTYPE, symbol AA of type OBJECT cannot be referenced as type FUNC module: SECOND file: DISK$USER:[JOE]SECOND.OBJ;5 %ILINK-I-DIFTYPE, symbol A of type OBJECT cannot be referenced as type FUNC module: SECOND file: DISK$USER:[JOE]SECOND.OBJ;5 %ILINK-W-RELODIFTYPE, relocation requests the linker to build a function descriptor for a non-function type of symbol symbol: A relocation section: .rela$CODE$ (section header entry: 19) relocation type: RELA$K_R_IA_64_LTOFF_FPTR22 relocation entry: 1 module: SECOND file: DISK$USER:[JOE]SECOND.OBJ;5 %ILINK-W-RELODIFTYPE, relocation requests the linker to build a function descriptor for a non-function type of symbol symbol: AA relocation section: .rela$CODE$ (section header entry: 19) relocation type: RELA$K_R_IA_64_LTOFF_FPTR22 relocation entry: 4 module: SECOND file: DISK$USER:[JOE]SECOND.OBJ;5 To eliminate these informational and warning messages, change the type of the symbols "A" and "AA" to be a function or a piece of data. For example, change the declarations in FIRST.C to functions: #include <stdio.h> int a(); int aa(); extern int second (); void main () { printf ("The address of 'a' is %x\n", &a); printf ("The address of 'aa' is %x\n", &aa); second (); } int a () { return 1; } int aa () { return 1; } After this change, your link will be free of informationals and warnings: $ link first,second $ Another alternative is to change the references to "A" and "AA" in SECOND to be references to data.
http://h71000.www7.hp.com/doc/82final/6675/6675pro_010.html
CC-MAIN-2016-07
refinedweb
1,637
50.46
SharePoint 2010 introduces a new client side object model (hereafter referred to as the “client OM”) for retrieving data. It supports a subset of functionality contained in the server side object model, but generally speaking gives you ready access to the data in your SharePoint site using standard object model nomenclature. Before I actually get into the “codey” part of this posting, let me give a BIG SHOUT OUT to Shaofeng and Michael for giving me tips, tricks, pointers and a cheat sheet that were major sources of information as the code behind this six part blog posting was created. Thank you fellas! The object model structure is very similar to what you've all known to expect, only with an interceding "Client" in the namespace. For example, in the server object model you have: · Microsoft.SharePoint.SPSite · Microsoft.SharePoint.SPWeb · Microsoft.SharePoint.SPList In the client object model you have: · Microsoft.SharePoint.Client.Site · Microsoft.SharePoint.Client.Web · Microsoft.SharePoint.Client.List You “get connected” to your data in SharePoint with the new ClientContext class. It is the uber class through which you issue queries and retrieve data from the farm. Where things get tricky is that when you return objects from a call, they have no data until you execute a query to retrieve them. The underlying goal here is to create a unified programming experience whether you are coding in SilverLight, ECMA (can I please just call it javascript the rest of the way??) and .NET managed applications. The client OM forces some of these semantics upon you, but in return it a) provides you data, b) minimizes the amount of data sent over the wire, and c) minimizes the number of roundtrips to the server. So how do these things work together? Let’s start with a relatively simple example – getting a list of all the lists in your SharePoint site. First, I added a reference to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll. I then added this using statement at the top of my class: using Microsoft.SharePoint.Client; Now, to begin with we need to create our instance of the ClientContext class, which is going to form our connection: PATTERN STEP 1: CREATE A CLIENT CONNECTION ClientContext ctx = new ClientContext(""); Now we’ll start to use some of the built in properties of the ClientConnection class, starting with the Web for the current site (remember, it’s a “Web” and not “SPWeb” because we are using the client OM): Web w = ctx.Web; Now we have our object (w), but we still have no data. We’re going to tell the client OM that we want to populate the collection of lists. We use LINQ to do this, but there are a few different ways in which this can be accomplished; here is the simplest way. PATTERN STEP 2: CREATE THE STATEMENT TO RETRIEVE THE DATA var lists = ctx.LoadQuery(w.Lists); Note that in the example above it will return a default set of properties. We could also pass in the list of properties that should be retrieved (we’ll look at that method in a bit). We still haven’t made a round trip to the server, we’ve just defined what data we want returned. To actually populate the collection of lists, we have to call the ExecuteQuery method on our ClientContext instance. Note that when you do call it though, LoadQuery affects ONLY the local variable named “lists”. It does not affect the ClientContext (specifically, w.Lists). In other words, after ExecuteQuery() is called the following will work: foreach (List L in lists) {..} the following will NOT work: foreach (List L in w.Lists) {..} Now, executing the query and getting our data back is our next line of code: PATTERN STEP 3: EXECUTE THE QUERY ctx.ExecuteQuery(); When we call ExecuteQuery, we actually send our request from the client to the server. The response is going to include all of the data we need, based on our LINQ query and the fields that we’ve asked for. The data comes back to us as simple formatted text that works well with JSON and REST. Here is snippet of the data that’s returned for each list when we asked for the default properties as shown above: { "","ParentWebUrl":"\u002f","HasExternalDataSource":false, "Created":"\/Date(1256585338000)\/","LastItemModifiedDate":"\/Date(1256585451000)\/","LastItemDeletedDate":"\/Date(1256585338000)\/","Id":"\/Guid(ebcb8888-2892-440e-a80d-53c1c78b7339)\/","Description":"A test list","Title":"BigList","Direction":"none","BaseType":0, "ImageUrl":"\u002f_layouts\u002fimages\u002fitdatash.png","ItemCount":3000,"BaseTemplate":120, "DefaultContentApprovalWorkflowId":"\/Guid(00000000-0000-0000-0000-000000000000)\/","TemplateFeatureId":"\/Guid(00bfea71-3a1d-41d3-a0ee-651d11570120)\/","DefaultViewUrl":"\u002fLists\u002fBigList\u002fBig View.aspx","DefaultEditFormUrl":"\u002fLists\u002fBigList\u002fEditForm.aspx", "DefaultNewFormUrl":"\u002fLists\u002fBigList\u002fNewForm.aspx", "DefaultDisplayFormUrl":"\u002fLists\u002fBigList\u002fDispForm.aspx","EnableAttachments":true, "ServerTemplateCanCreateFolders":true,"EnableFolderCreation":false,"EnableModeration":false, "EnableVersioning":false,"ForceCheckout":false,"EnableMinorVersions":false, "DraftVersionVisibility":0,"Hidden":false,"IsApplicationList":false,"IsCatalog":false, "AllowContentTypes":true,"DocumentTemplateUrl":null,"ContentTypesEnabled":false, "MultipleDataList":false,"NoCrawl":false } As I noted above, we can also create a query and just ask for specific fields. To do so we use the Load method on the ClientContext class and a somewhat more complicated LINQ query with Lambdas. Here is how that works: ctx.Load(w.Lists, lists => lists.Include(prop => prop.Title, prop => prop.Id, prop => prop.Hidden)); Basically what we’re saying here is that we want to retrieve items in the Lists property of the Web, we’re going to use a parameter called “lists”, and we’re going to define it as including the Title and Id fields. We still call the ExecuteQuery after creating our LINQ statement, but here’s what the return data looks like for a single list with a specific list of fields: { "","Title":"BigList","Id":"\/Guid(ebcb8888-2892-440e-a80d-53c1c78b7339)\/","Hidden":false,"BaseType":0 } The difference in size is impressive. In fact for this case I did a trace of both methods – asking for the collection of lists and all default fields resulted in a payload of 59k; calling the method with a list of just the three fields I needed resulted in a payload of 12k. This all adds up, especially when retrieving data over slow or congested connections. PATTERN BEST PRACTICE: WHENEVER POSSIBLE, PROVIDE A SPECIFIC LIST OF FIELDS WHEN RETRIEVING DATA So now that we’ve made that single round trip to the server, we won’t have to go back to it again in order to finish our example. With our data in hand, let’s complete the pattern to process the data in our results. In this case we’re going to enumerate all of the lists that were returned and add it to a list box in a Windows Forms application (NOTE: the example here is based on the code snippet above for retrieving specific fields; if you used the first example of retrieving all, you would enumerate through the var lists return value): foreach (List theList in w.Lists) { if(theList.Hidden != true) ListsLst.Items.Add(theList.Title); } One thing that’s important to remember is that when you retrieve items, if they have properties that are object collections, those values will not be retrieved when you query for the item. As an example, take the ListTemplates property of the Web class. It is a property of type ListTemplateCollection, filled with individual ListTemplate items. You won’t get the ListTemplateCollection property populated with the list of ListTemplates if you retrieve the Web object like this: Web w = ctx.Web; ctx.Load(w); ctx.ExecuteQuery(); It will give you all of the simple property values of the Web object but that’s it. In order to populate those object collection properties, you have to pass them to the Load method like this: ListTemplateCollection ltc = ctx.Web.ListTemplates; ctx.Load(ltc); ctx.ExecuteQuery(); //now enumerate foreach(ListTemplate lt in ltc){} Coming Next… That’s our basic pattern, and brings this posting to a close. In part 2 of this posting, I’ll describe how to use this pattern to retrieve data from a list. Hi All, I am new to SharePoint 2010 Development. I want to work on development, so what is the best way to learn the object modela and know what SP classes are there and how to utilize them. I am basically working on building custom claims provider for SP 2010 and People picker. Please guide me through this speschka Thanks BDS Nice post. Do you have a VS Solution for the examples? thanks – nice simple example. sharepoint is a complex leviathan in search of a reason to exist in my opinion. Any why does it not support ODMA? Very impractical from MS. No wonder they purchased Yammer …. Thanks
https://blogs.technet.microsoft.com/speschka/2009/11/01/using-the-sharepoint-2010-client-object-model-part-1/
CC-MAIN-2016-36
refinedweb
1,451
52.6
0 /*Ok I have code that's behaving unexpectedly The following program is supposed to print prime numbers for n1=100,n2=1000,n3=10000 and n4=100000 except that for n1=100, it prints the squares of primes less than 10. I can implement this same program in c++ and wouldn't get such output. I need another pair of eyes to look through my code and tell me if there's anything semantically wrong with it. Thanks */ import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { int n1=100;int n2=1000;int n3=10000;int n4=100000; long start = System.nanoTime(); int n=0; for(int i=2;i<n1;i++){ n=0; for(int j=2;j<i;j++){ if(i%j==0){ n+=1;} } if(n==1) System.out.println(i); } long end = System.nanoTime(); System.out.println("The execution time was: "+(end-start)+" nanoseconds."); } }
https://www.daniweb.com/programming/software-development/threads/433305/why-does-my-program-print-squares-of-numbers
CC-MAIN-2018-13
refinedweb
155
66.23
I have a string containing some text. The text may or may not be code. Using Github's Linguist, I have been able to detect the likely programming language only if I give it a list of candidates. # test_linguist_1.rb #!/usr/bin/env ruby require 'linguist' s = "int main(){}" candidates = [Linguist::Language["Python"], Linguist::Language["C"], Linguist::Language["Ruby"]] b = Linguist::Blob.new('', s) langs = Linguist::Classifier.call(b, candidates) puts langs.inspect $ ./test_linguist_1.rb [#<Linguist::Language name=C>, #<Linguist::Language name=Python>, #<Linguist::Language name=Ruby>] # test_linguist_2.rb #!/usr/bin/env ruby require 'linguist' s = "int main(){}" candidates = Linguist::Language.all # I also tried only Popular # candidates = Linguist.Language.popular b = Linguist::Blob.new('', s) langs = Linguist::Classifier.call(b, candidates) puts langs.inspect $ ./test_linguist_2.rb /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:131:in `token_probability': undefined method `[]' for nil:NilClass (NoMethodError) from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:120:in `block in tokens_probability' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:119:in `each' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:119:in `inject' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:119:in `tokens_probability' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:105:in `block in classify' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:104:in `each' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:104:in `classify' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:78:in `classify' from /home/marvelez/.rvm/gems/ruby-2.2.1/gems/github-linguist-4.8.9/lib/linguist/classifier.rb:20:in `call' from ./test_linguist.rb:21:in `block in <main>' from ./test_linguist.rb:14:in `each' from ./test_linguist.rb:14:in `<main>' Taking a quick look at the source code of Linguist, it appears to use a number of strategies to determine the language, and it calls each strategy in turn. Classifier is the last strategy to be called, by which time it has (hopefully) picked up language "candidates" (as you've discovered for yourself) from the prior strategies. So I think for the particular sample you've shared with us, you have to pass a filename of some kind, even if a file doesn't actually exist, or a list of language candidates. If neither is an option for you, this may not be a feasible solution for your problem. $ ruby -r linguist -e 'p Linguist::Blob.new("foo.c", "int main(){}").language' #<Linguist::Language name=C> It returns nil without a filename, and #<Linguist::Language name=C++> with "foo.cc" and the same code sample. The good news is that you picked a really bad sample to test with. :-) Other strategies look at modelines and shebangs, so more complex samples have a better chance at succeeding. Take a look at these: $ ruby -r linguist -e 'p Linguist::Blob.new("", "#!/usr/bin/env perl print q{Hello, world!}; ").language' #<Linguist::Language name=Perl> $ ruby -r linguist -e 'p Linguist::Blob.new("", "# vim: ft=ruby puts %q{Hello, world!} ").language' #<Linguist::Language name=Ruby> However, if there isn't a shebang or a modeline, we're still out of luck. It turns out that there's a training dataset that is computed and serialized to disk at install time, and automatically loaded during language detection. Unfortunately, I think there's a bug in the library that is preventing this training dataset from being used if there aren't any candidates by the time it gets to this step. Fixing the bug lets me do this: $ ruby -Ilib -r linguist -e 'p Linguist::Blob.new("", "int main(){}").language' #<Linguist::Language name=XC> (I don't know what XC is, but adding some other tokens to the string such as #include <stdio.h> or int argc, char* argv[] gives C. I'm sure most of your samples will have more meat to analyze.) It's a real simple fix and I've submitted a PR for it. You can use my fork of the Gem if you'd like in the meantime. Otherwise, we'll need to look into using Linguist::Classify directly, as you've started exploring, but that has the potential to get messy. To use my fork, add/modify your Gemfile to read as such: gem 'github-linguist', require: 'linguist', git: '', branch: 'fix-no-candidates' I'll try to come back and update this answer when the PR has been merged and a new version of the Gem has been released with the fix. If I have to do any force-pushes to meet the repository guidelines and/or make the maintainers happy, you may have to do a bundler update to reflect the changes. Let me know if you have any questions.
https://codedump.io/share/hlgnkHNQUZ08/1/how-can-i-detect-the-programming-language-of-a-snippet
CC-MAIN-2016-44
refinedweb
878
51.55
Hello guys. I need to create 20X30m polygons at random positions within a predefined boundary. And I also need the number of polygons created equal 25% of the area. Any suggestion? Hello guys. I need to create 20X30m polygons at random positions within a predefined boundary. And I also need the number of polygons created equal 25% of the area. Any suggestion? I'd like the shape of the polygons to be rectangular (20 X 30 meters). And, where would the "fishnet" look for the area of the "base polygon" to know how many polygons (20X30m) to be 25% sampled area of the "base polygon"? That might entail 'humanware' to provide some guidance. You could however, determine the extent of the base polygon then use that extent to set the bounds of the fishnet. You would just want to ensure that your fishnet has sufficient rows and columns that you could get a 25% sample of rectangles within the base polygon. That is not a problem since 'select by spatial location' with a 'completely within' control would ensure that you select only polygons within the base polygon, then continue to select polygons perhaps incrementally, until the 25% areal coverage is met. I thought I would have a go at it, but there are a number of things that would need to be resolved. This is the code I came up with, but it is far from fast and should not be used for a "large" set of data: import arcpy def main(): arcpy.env.overwriteOutput = True # settings fc_in = r'C:\GeoNet\RandRectangles\data.gdb\areas' fc_tmp = r'C:\GeoNet\RandRectangles\data.gdb\rectangles_tmp' fc_sel = r'C:\GeoNet\RandRectangles\data.gdb\rectangles_tmp_sel' fc_out = r'C:\GeoNet\RandRectangles\data.gdb\rectangles_v01' rect_width = 20 rect_height = 30 min_area_frac = 0.25 # Some asumptions: # rectangles should not be reused # rectangles have common origin XY # minimum area of 25% should be covered sr = arcpy.Describe(fc_in).spatialReference ext = arcpy.Describe(fc_in).extent # create a tmp featureclass with the rectangles ext_fin = ReshapeExtent(ext, rect_width, rect_height) feats = [] for c in range(int(ext_fin.width / rect_width)): for r in range(int(ext_fin.height / rect_height)): polygon = CreateRectanglePolygon(ext_fin.XMin + c * rect_width, ext_fin.YMin + r * rect_height, ext_fin.XMin + (c+1) * rect_width, ext_fin.YMin + (r+1) * rect_height, sr) feats.append(polygon) arcpy.CopyFeatures_management(feats, fc_tmp) # now select only the ones that overlap any area polygon arcpy.MakeFeatureLayer_management(fc_in, 'area_lyr') arcpy.MakeFeatureLayer_management(fc_tmp, 'rect_lyr') arcpy.SelectLayerByLocation_management("rect_lyr", "INTERSECT", "area_lyr", None, "NEW_SELECTION") arcpy.CopyFeatures_management('rect_lyr', fc_sel) # create a dictionary from the selected reactangles dct_rect = {r[0]: r[1] for r in arcpy.da.SearchCursor(fc_sel, ('OID@', 'SHAPE@'))} # loop through polygons and determine which to use lst_oid_taken = [] lst_results = [] with arcpy.da.SearchCursor(fc_in, ('OID@', 'SHAPE@')) as curs: for row in curs: oid_area = row[0] area_pol = row[1] dct_overlap = GetDictOfRectanglesForArea(area_pol, dct_rect, lst_oid_taken) lst_selection, lst_oid_taken = GetRandomRectanglesForArea(area_pol, dct_overlap, lst_oid_taken, min_area_frac) lst_results.append([oid_area, lst_selection]) for result in lst_results: oid_area = result[0] lst_selection = result[1] for oid_rect in lst_selection: print "{0}\t{1}".format(oid_rect, oid_area) def GetRandomRectanglesForArea(area, dct_overlap, lst_oid_taken, min_area_frac): import random lst_selection = [] lst_oid = dct_overlap.keys() polygon_area = area.area tot_rect_area = 0 fraction = tot_rect_area / polygon_area cnt = 0 print "\nGetRandomRectanglesForArea" while fraction < min_area_frac: cnt += 1 print " - cnt:", cnt i = random.randrange(0, len(lst_oid) - 1) print " - i:", i oid = lst_oid[i] print" - oid:", oid if not oid in lst_oid_taken: rectangle = dct_overlap[oid] overlap_area = GetOverlapArea(area, rectangle) print " - overlap_area:", overlap_area tot_rect_area += overlap_area print " - tot_rect_area:", tot_rect_area fraction = tot_rect_area / polygon_area print " - fraction:", fraction lst_oid_taken.append(oid) lst_selection.append(oid) if cnt > 100: break return lst_selection, lst_oid_taken def GetOverlapArea(area, rectangle): if rectangle.within(area): return rectangle.area else: overlap = area.intersect(rectangle, 4) return overlap.area def GetDictOfRectanglesForArea(area, dct, lst_done): dct_overlap = {} for oid, rectangle in dct.items(): if not oid in lst_done: if rectangle.within(area): dct_overlap[oid] = rectangle elif rectangle.overlaps(area): dct_overlap[oid] = rectangle return dct_overlap def CreateRectanglePolygon(xmin, ymin, xmax, ymax, sr): points = [arcpy.Point(xmin, ymin), arcpy.Point(xmin, ymax), arcpy.Point(xmax, ymax), arcpy.Point(xmax, ymin), arcpy.Point(xmin, ymin)] return arcpy.Polygon(arcpy.Array(points), sr) def ReshapeExtent(ext, width, height): xmin_new = divmod(ext.XMin, width)[0] * width ymin_new = divmod(ext.YMin, height)[0] * height xmax_new = divmod(ext.XMax, width)[0] * width + width ymax_new = divmod(ext.YMax, height)[0] * height + height return arcpy.Extent(xmin_new, ymin_new, xmax_new, ymax_new) if __name__ == '__main__': main() The result is list of rectangle OIDs with the corresponding area OIDs which I joined back to the rectangles (since I was too lazy to create a proper output featureclass. The steps are more or less the following: 1) a tmp featureclass with rectangles is created using lower left XY which is a multiple of the width and height and covers the entire area: 2) The rectangle features that overlap the areas are selected and read into a dictionary: 3) random rectangles are selected until at least 25% overlap is obtained (taking only the overlapping area of the rectangles into account): There are still some situations that are probably not desired. Such as rectangles that have a very small overlap or have a larger overlap with another polygon and that might not be what you want: So it will probably need to be optimized further. Nice! Now if you want Xander Bakker try option 4 (spaced points ) in my Point Tools for ArcGIS Pro if you are looking to give 2.1 a test ride. Point spacing should be guaranteed, then buffer by 1/2 the distance should also ensure no overlaps you could generate a fishnet within the area that more or less covers it. Assign a random number to each grid square then sample 25% and dump the rest. Also, random polygons could also be accomplished by buffering 25 random points that are at a distance no-closer-than (I have code for this in python) Do you want random shapes? (not going to happen easily)
https://community.esri.com/thread/208112-random-polygons
CC-MAIN-2018-34
refinedweb
977
50.02
Unity 2018.2.8f1さっそく、アップデートしましょう! リリースノート Fixes - (1071483 (1062852)) - Android: Fixed crash when returning null string from Java plugin. - (1065609) - Asset Import: Fixed renaming or changing the namespace containing a scripted importer breaking the auto-reimport mechanism. - (1073894) - Editor: Fixed an issue where launching Unity via Hub invalidates existing login for direct launchers. - (1075850) - Graphics: Fixed main thread stall deleting temporary render targets after calling ConvertTexture() from script. - (1076208) - Graphics: Fixed crash in intensive rendering scenes when using legacy graphics jobs. - (1061224) - Graphics: Fixed crash in MinMaxAABB::MinMaxAABB when Legacy Deferred Render Path is used. - (1033188) - Graphics: Fixed RGBA16 having swapped red/blue channels. - (1075574 (1070347)) - Graphics: Fixed issue where Camera FOV cannot be set to a value lower than 1. - (1041458) - OSX: Fixed an issue where MacOS player would not go into correct screen mode when Command+F is pressed. - (1074390 (1058082)) - Physics: Fixed issue where colliders without physics material don't return correct default material in Physics Settings. - (1074389 (1009394)) - Physics: Fixed wrong UV returned in Raycast result when raycasting to a mesh collider that has negative scale. - (1074384 (1005564)) - Physics: Fixed issue where transform to CharacterController in OnControllerColliderHit is ignored. - (1074376) - Physics: Fixed an issue where some Physics Settings are not reset upon request. - (1074374 (1024453)) - Physics: Fixed issue where mass properties are not correctly updated when changing collider scale. - (1074373 (1048878)) - Physics: Fixed a crash when user sets a very small size to Terrain data. - (1066072 (1059467)) - Physics: Fixed an issue where kinematic bodies may not follow transform change after setting its postion after setting their position or rotation via Transform component. - (1074312) - Scene Management: Fixed crash in LightmapSettingsManager.CheckSettingsConsistency when calling UnloadSceneAsync right after a LoadScene(SingleMode). - (1052766) - Scene/Game View: Fixed issue where specifying frustum view point would actually use it as base for the near plane. - (1073275) - Scripting Upgrade: Fixed hang when disconnecting while reading/writing on a SslStream. - (1060892) - Scripting Upgrade: Fixed crash when entering playmode on OSX. - (1062208) - Scripting Upgrade: Fixed Android Runtime test instability. - (1059122) - Scripting Upgrade: Fixed an issue where UnsafeUtility.GetFieldOffset could return 0 when the type is not initialized. - (1065895) - Scripting Upgrade: Fixed crash when DynamicMethod is constructed into non-dynamic image. - (1069236) - Scripting Upgrade: Fixed crash when using unmanaged constraint. - (966667) - UI: Fixed Chinesse bolded Arial font style looks wide in Editor. - (983200) - UI: Fixed spacing between characters is lost and text is stretched with bold font selected when built on certain platforms. Revision: ae1180820377 Changeset: ae1180820377 Unity 2018.2.8f1
https://unity3d.com/jp/unity/whatsnew/unity-2018.2.8
CC-MAIN-2019-18
refinedweb
415
57.47
Activation functions What is Activation function: It is a transfer function that is used to map the output of one layer to another. In daily life when we think every detailed decision is based on the results of small things. let’s assume the game of chess, every movement is based on 0 or 1. So in every move, we use the activation function. There are main following categories of functions - Unipolar Binary - Bipolar Binary - Unipolar Continuous - Bipolar Continuous - Linear linear A straight line function where activation is proportional to input ( which is the weighted sum from neuron ). This way, it gives a range of activations, so it is not binary activation. We can definitely connect a few neurons together and if more than 1 fires, we could take the max ( or softmax) and decide based on that. So that is ok too. Then what is the problem with this? If you are familiar with gradient descent for training, you would notice that for this function, the derivative is a constant. A = cx, derivative with respect to x is c. That means the gradient has no relationship with X. If there is an error in prediction, the changes made by backpropagation is constant and not depending on the change in input delta(x) !!! sigmoid The Sigmoid function takes).The main disadvantage of sigmoid is it stop learning for large value of x or in other words function get saturated for large value of x. import tensorflow as tf Ys=Y2/100 Ws=W3/100 Y5 = tf.nn.sigmoid(tf.matmul(Ys, Ws) + B3) model=tf.global_variables_initializer() sess.run(model) sess.run(Y5) array([[ 0.73399752, 0.73419272, 0.73438782, 0.73458284, 0.73477777], [ 0.73885001, 0.73952477, 0.7401984 , 0.7408709 , 0.74154227], [ 0.74364489, 0.74478704, 0.74592584, 0.74706129, 0.74819337], [ 0.74838172, 0.74997895, 0.7515694 , 0.75315306, 0.75472992], [ 0.75306009, 0.75509996, 0.75712841, 0.75914542, 0.76115096]]) softmax. We can do a 2-d demonstration by using the following code: x=np.arange(-2.0,6.0,0.1) scores=np.vstack([x,np.ones_like(x),2*np.ones_like(x)]) print(scores.argmax()) plt.plot(x,softmax(scores).T,linewidth=0.7) plt.show() tanh The tanh function, a.k.a. hyperbolic tangent function, is a rescaling of the logistic sigmoid, such that its outputs range from -1 to 1. (There’s horizontal stretching as well.). The (-1,+1) output range tends to be more convenient for neural networks, so tanh functions show up there a lot. This functions are prone to reaching a point from where the gradient of the functions does not change or stop learning or it get saturated for large value of x. relu The Rectified Linear Unit- Relu has a great advantage over sigmod and tanh as it never gets saturated with high value of x. But the main disadvantage of this is its mean is not zero due to which the function becomes zero and overall learning is too slow.. “Unfortunately, ReLU units can be fragile during training and can “die”. For example, a large gradient flowing through a ReLU neuron could cause the weights to update in such a way that the neuron will never activate on any data point again. Programmatically, def reluDerivative(x): x[x<=0] = 0 x[x>0] = 1 return x z = np.random.uniform(-1, 1, (3,3)) print(z) reluDerivative(z) [[-0.37386542 0.16629877 -0.74344915] [ 0.36153638 -0.0906727 -0.7030014 ] [-0.95665917 0.90534339 0.1792306 ]] array([[0., 1., 0.], [1., 0., 0.], [0., 1., 1.]]) Once a ReLU ends up in this state, it is unlikely to recover, because the function gradient at 0 is also 0, so gradient descent learning will not maximize the weights. “Leaky” ReLUs with a small positive gradient for negative inputs ( y=0.01x when x < 0 say) are one attempt to address this issue and give a chance to recover. The sigmoid and tanh neurons can suffer from similar problems as their values saturate, but there is always at least a small gradient allowing them to recover in the long term. Leaky ReLU It is an attempt to solve the dying ReLU problem Swish This function is introduced by Google it is a non -monotonic function. It provides better performance than Relu and Leaky Relu. elu ELU(Exponential linear unit) function solves the Vanishing gradient problem. The other mentioned activation functions are prone to reaching a point from where the gradient of the functions does not change or stop learning. The Elu tries to minimize the problem of relu and minimize the mean to zero so that the learning rate increases. Like batch normalization, ELUs push the mean towards zero, but with a significantly smaller computational footprint. selu SELU is some kind of ELU but with a little twist. α and λ are two fixed parameters, meaning we don’t backpropagate through them and they are not hyperparameters to make decisions about. def selu(x): """Scaled Exponential Linear Unit. (Klambauer et al., 2017) # Arguments x: A tensor or variable to compute the activation function for. # References - [Self-Normalizing Neural Networks]() """ alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 return scale * elu(x, alpha) For standard scaled inputs (mean 0, stddev 1), the values are α=1.6732~, λ=1.0507~. softplus Both the ReLU and Softplus are largely similar, except near 0 where the softplus is enticingly smooth and differentiable. It’s much easier and efficient to compute ReLU and its derivative than for the softplus function which has log(.) and exp(.) in its formulation. Interestingly, the derivative of the softplus function is the logistic function: f′(x)=11+e−xf′(x)=11+e−x. In deep learning, computing the activation function and its derivative is as frequent as addition and subtraction in arithmetic. By switching to ReLU, the forward and backward passes are much faster while retaining the non-linear nature of the activation function required for deep neural networks to be useful. softsign The soft sign function is another nonlinearity which can be considered an alternative to tanh since it too does not saturate as easily as hard clipped functions hard_sigmoid σ is the “hard sigmoid” function: σ(x) = clip((x + 1)/2, 0, 1) = max(0, min(1, (x + 1)/2)) The intent is to provide a probability value (hence constraining it to be between 0 and 1) for use in stochastic binarization of neural network parameters (e.g. weight, activation, gradient). You use the probability p = σ(x) returned from the hard sigmoid function to set the parameter x to +1with p probability, or -1 with probability 1-p References: was recommended this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my problem. You’re amazing!. Howdy I am so glad I found your site, I really found you by accident,. I just want to tell you that I am new to blogging and really enjoyed your web blog. Likely I’m want to bookmark your website . You certainly have fantastic stories. Thanks a bunch for revealing your website. Hey! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts. I have to say this was a great article.Keep up the good work .Enlighten us👌👌 I got what you mean , regards for posting.Woh I am happy to find this website through google. “Success is dependent on effort.” by Sophocles. Thanks to my father who told me concerning this webpage, this web site is in fact awesome. Hi there to every one, the contents existing at this web page are actually remarkable for people experience, well, keep up the good work fellows. mates, its wonderful post regarding cultureand entirely defined, keep it up all the time. This website was… how do I say it? Relevant!! Finally I have found something that helped me. Many thanks! Hello there, You’ve done a fantastic job. I’ll definitely digg it and personally recommend to my friends. I’m sure they will be benefited from this web site. “Having read this I thought it was very enlightening. I appreciate you taking the time and effort to put this article together. I once again find myself personally spending way too much time both reading and commenting. But so what, it was still worth it!” Wonderful article! That is the kind of information that are meant to be shared across the net. Shame on Google for now not positioning this submit higher! Come on over and talk over with my web site . Thanks =) Very good info. Lucky me I recently found your site by chance (stumbleupon). I have saved it for later! An outstanding share! I’ve just forwarded this onto a friend who has been conducting a little research on this. And he in fact ordered me lunch because I found it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for spending time to talk about this topic here on your blog.
http://www.machineintellegence.com/different-types-of-activation-functions-in-keras/
CC-MAIN-2020-34
refinedweb
1,529
65.12
Catalyst::Controller::Imager - generate scaled or mangled images version 0.05 # use the helper to create your Controller script/myapp_create.pl controller Image Imager # DONE. READY FOR USE. # Just use it in your template: # will deliver a 200 pixel wide version of some_image.png as jpg <img src="/image/w-200/some_image.png.jpg" /> # will deliver a 210 by 300 pixel sized image without conversion # (empty areas will be white) <img src="/image/w-210-h-300/other_image.jpg" /> # will deliver a 80 by 80 pixel sized image # (empty areas will be white) <img src="/image/thumbnail/other_image.jpg" /> # define a modifier of your own <img src="/image/blur-9/some_image.png.jpg" /> # your modifier plus a predefined one <img src="/image/thumbnail-blur-9/some_image.png.jpg" /> # same thing as above <img src="/image/blur-9-thumbnail/some_image.png.jpg" /> # in your Controller you then need: sub want_blur :Action :Args(1) { ### do something to get a blurred image } A Catalyst Controller that generates image files in any size you request and optionally converts the image format. Images are taken from a cache directory if possible and desired or generated on the fly. The Cache-directory has a structure that is very similar to the URI scheme, so a redirect rule in your webserver's setup would do this job also. The URI of an image consists of always the same parts: If your Controller is named MyApp::Controller::Image, this first part will be image. Here a series of modifiers and arguments separated with single dashes ('-') are used. h-100 # will request an image's height w-200 # will request an image's width h-80-w-20 # both, height and width will apply thumbnail # a configurable square (defaults to 80) This is the relative path to the image that should get rendered If an additional option like .gif is added immediately after the image path, this format is requested for delivery. A Controller that is derived from Catalyst::Controller::Imager may define its own modifier functions. See EXTENDING below. Possible initially defined options are: specifies the width of the image to generate. The height is adjusted to maintain the same ratio as the original image. The maximum size is controlled by a configuration parameter max_size that defaults to 1000. Can be used in conjunction with h-n. However, if both options are given, the image will scale to fill the given area either by width or by height, get centered inside the area and additional spaces will get filled with white. specifies the height of the image to generate. The width is adjusted to maintain the same ratio as the original image. The maximum size is controlled by a configuration parameter max_size that defaults to 1000. Can be used in conjunction with w-n. However, if both options are given, the image will scale to fill the given area either by width or by height, get centered inside the area and additional spaces will get filled with white. requests the generation of a thumbnail image. Defaults to a maximum size of thumbnail_size. The size can get changed by a simple configuration parameter. A simple configuration of your Controller could look like this: __PACKAGE__->config( # the directory to look for files (inside root) # defaults to 'static/images' root_dir => 'static/images', # specify a cache dir if caching is wanted # defaults to no caching (more expensive) cache_dir => undef, # specify a format that will get delivered if # not guessable from the file extension # defaults to 'jpg' default_format => 'jpg' # specify a maximum value for width and height of images # defaults to 1000 pixels max_size => 1000, # specify the size of thumbnails (always square) # defaults to 80 pixels thumbnail_size => 80, # set jpeg quality # defaults to 95 jpeg_quality => 95, ); If caching is enabled (by setting the cache_dir configuration parameter), every image rendered will get saved into the cache directory if it exists and the directory is writable. The path of a cached image inside the cache directory is identical to the URI part after the action namespace. Thus, a properly configured webserver might take over the responsibility to deliver static images from cache removing the burden from your Catalyst Controller. This base class defines a Chained dispatch chain consisting of the following Action methods. Each method is responsible for eating up a defined part of the URI. The URI always consists of 3 parts: The namespace, a format and size modifier and a relative path to the image in question optionally with another file extension added for format conversion. To allow easy modification the URI dispatching is left to Catalyst. The following :Chained actions each work on a stage of the image construction. The final image will get delivered by the end action. consumes the namespace of the controller inheriting this one. consumes a single URI part. If the part is a concatenation of several things joined with a dash '-', then these things are regarded as either arguments to an action or further actions with their arguments. If a modifier is named 'blur' and needs a single parameter, you may define a method like: sub blur :Action :Args(1) { # do something to blur } During this stage, the only thing that happens is recording every modification into a series of stash-variables. The final stage consumes the image path and tries to find the image in question. After the image is found, a forward to 'generate_image' is issued which does the conversion we want. All action methods communicate with each other by setting or retrieving stash variables. relative path to original image Imager Object as soon as image is loaded binary image data after conversion or from cache relative path to cached image format for conversion { w => n, h => n, mode => min/max/fit/fill } list of Actions executed before scaling ### FIXME: action or subref??? list of Actions executed after scaling ### FIXME: action or subref??? The magic behind all the conversions is the existence of specially named action methods (their name starts with 'want_' or 'scale_'). Actions starting with 'want_' get triggered if the URI part after the package namespace contains a word that matches the remainder of the action's name. The :Arg() attribute specifies how many additional parts this action will need for its operation. One part of the scaling hash inside stash is a scaling mode. Depending on the name of the scaling mode, an action named 'scale_mode' is used to process the scaling. If you plan to offer URIs like: /image/small/image.jpg /image/size-200-300/image.jpg /image/watermark/image.jpg # or a combination of them: /image/size-200-300-watermark/image.jpg # but not invalid things: /image/size-200/image.jpg you may build these action methods: sub want_small :Action :Args(0) { my ($self, $c) = @_; $c->stash(scale => {w => 200, h => 200, mode => 'fill'}); } sub want_size :Action :Args(2) { my ($self, $c, $w, $h) = @_; $c->stash(scale => {w => $w, h => $h, mode => 'fill'}); } sub want_watermark :Action :Args(0) { my ($self, $c) = @_; ### FIXME: action or subref??? push @{$c->stash->{after_scale}}, \&watermark_generator; } start of the action chain -- eats package namespace, eg. /image second chain step -- eat up modifier parameter(s) Modifier parameters and their args must be separated by single dashes ('-'). For every modifier there must exist an action named want_modifiername declared with the number of args it wants to consume # modifier 'h', one argument # eg h-200 sub want_h :Action :Arg(1) # modifier 'size, two arguments # eg size-300-200 sub want_size :Action :Arg(2) final chain step --consumes image path relative to root_dir plus optional format extension for conversion The converting function. Consumes all conversion-relevant parameters from stash and does the conversion (or delivers a file from stash). deliver the data or fire a 404-status in case something went wrong. Yes, I know, a 404 means 'not found', but for the end-user there is no difference between a not found image and an error that occured. And basically if somebody puts rubbush into the URL and calling an unknown action internally is a Internal server error, but for the end-user the requested image and its modification could not get retrieved. scales an image by the minimum scaling factor needed to either match the desired width or height. scales an image by the maximum scaling factor needed to either match the desired width or height. first scales an image by the maximum scaling factor needed to either match the desired width or height. Then, crops the image to make it fit the desired size. scales an image by the minimum scaling factor needed to either match the desired width or height. Then, expand the image with white color to make it fit the desired size. Logic for the 'thumbnail' modifier without further args. Sets the requested width and height to the thumbnail_size configuration parameter (default is 80). Logic for the 'w' modifier with one arg. Sets the requested width of the image. Logic for the 'h' modifier with one arg. Sets the requested height of the image. probably many... Don't get confused if tests fail and carefully read the messages. The test-suite only will pass if Imager is configured with gif, jpeg and png support. In doubt install the required binary libraries and reinstall Imager. Wolfgang Kinkeldei, <wolfgang@kinkeldei.de> This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/Catalyst::Controller::Imager
CC-MAIN-2014-23
refinedweb
1,569
53.92
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. murature.py basic usage You need a recent version of Python. This scripts have been tested with Python 2.4 and 2.5. You will need also the Python OGR bindings and the RPy module. On Debian-like systems (including Ubuntu), this is just a matter of installing the following packages: python-gdal, python-rpy. To run the script, open a terminal in the directory that contains the files, and type: python example.py 3.1 3.1 is the magic number that we pass to the script. If you don't specify a magic number, the default value is 3.0. The usual output is something like this: by hand Min. 1st Qu. 3rd Qu. Median Max. Mean 9.90 12.00 16.50 13.50 30.20 15.01 Simple Height Min. 1st Qu. 3rd Qu. Median Max. Mean 9.093 12.780 20.230 15.170 48.190 16.860 Smart Height Min. 1st Qu. 3rd Qu. Median Max. Mean 7.768 11.540 18.410 13.640 34.670 15.150 The image plotR.png is created in the current directory and shows a graphical comparison between the various recording methods. library description This Python library was written as an help for the study of stone walls, mainly through the quantitative analysis of spatial dimensions of stones. The code is still in the early stages of development and lacks a clear structure, but the functions are documented quite well with docstrings. At the moment you find an example.py that shows how to use the library routines, an example dataset (made by various files), and 3 Python scripts: - geometrywall.py has all the geometry (OGR) related functions - rplots.py contains the RPlots class that can be used to output summaries and graphs - breaks.py has the code for automatically classifying stones into rows The numerical analisys is done with R using the rpy Python module. We are trying to use just methods and functions from the standard R library. - the ogr module is used to import geometry data and get all the needed parameters like centroid and boundary coordinates - height is calculated with two different methods: - a simple method max(y) - min(y) - the smart method - we also store a central measure (like median) to be used in the next steps as a parameter to find stone rows Each stone is assigned a rank number using a kernel density function (density in the R stats standard library) with a narrow bandwidth. This works because vertical coordinates of centroids aren't distributed uniformely, but are concentrated around the mean row's value. Thus, stones who are on the same course will get the same rank number. This allows other kind of analyses based on the variance of single courses and other methods still to be explored. To best compare the measures taken by hand and the automatic ones we need a complete and detailed case study, that has to be well drawn, with an attribute table containing the hand-taken measures. the smart method The basic algorhythm works by finding the highest and the lowest Y coordinate of the stone polygon, then a simple max(y) - min(y) subtraction gives us a rough estimate of the true height of the stone. Tests carried between hand-recorded measures and this method show this roughness is way too high for our needs. The hand-taken measures are our reference because the expert human operator is able to record a significant value for the stone height, and thus (s)he behaves quite differently than this simple algorhythm. --insert images and graphs here-- We can try to get a smart height by averaging the n highest and n lowest Y coordinates. This way our max(y) - min(y) becomes something slightly different: a difference between the average upper limit and the average lower limit. We use a magic number to express the ratio of total points to be used in this calculation. If magicNumber = 3.0 we are going to use totalPoints / magicNumber points for the upper limit and totalPoints / magicNumber points for the lower limit. magicNumber = 3.0 self.stonePointsCount = stoneBoundary.GetPointCount() pointsRatio = int(( self.stonePointsCount / magicNumber )) + 1 The stoneBoundary object is the OGR boundary (of type LINESTRING) of the stone. The OGR GetPointCount() method simply returns the number of points in a LINESTRING. The pointsRatio variable is used to calculate for each stone how many points are needed to compute the smart height. This way we make sure that the algo is consistent across all the stones. Using a fixed value doesn't make sense here, because there will be stones with a few points and others with more than 20 points. The numerical value self.stonePointsCount / magicNumber is a floating point number, that we must convert to an integer in order to use it. We should think about the different results of adding or not 1 to this variable. def smartAlgo(listey,ratio): '''`smart' algo with average coordinates.''' listey.sort() asd = 0 for i in listey[0:ratio]: asd = asd + i yMin = asd/ratio asd = 0 for i in listey[-ratio:]: asd = asd + i yMax = asd/ratio yAvg = yMax - yMin return yAvg the smart 2 method This second smart algorhythm works in a slightly different way from the first one. Instead of using a predetermined number of points for averaging the upper and lower limits, we use a range of Y coordinates based on the extreme values. So, if p_max is the point with the highest Y coordinate, and p_min the one with the lowest, we first obtain the simple height with: simple_height = y(p_max) - y(p_min) Then, the points that will be used for the average upper limit are those whose Y coordinate is such that: (y(p_max) - ( simple_height / n )) < y(p) <= y(p_max) where n expresses the range that should be used, proportional to the stone height. Note that y(p) is less or equal than y(p_max), otherwise p_max itself would be excluded from the procedure, exposing to ZeroDivisionError s and other bugs. The same applies for the lower limit. Once the points to use have been selected, the two averages are calculated and their difference is the resulting smart_2_height of the stone. An example should make it more clear. If y(p_max) for our stone is 410.34 and y(p_min) = 395.16, it's easy to obtain: simple_height = y(p_max) - y(p_min) = 410.34 - 395.16 = 15.18 Then, for finding the average upper limit, we iterate through all the points in the current stone, and select only those such as that: (y(p_max) - ( simple_height / n )) < y(p) <= y(p_max) (410.34 - (15.18 / n)) < y(p) < 410.34 Which value should we give to n? Some experiments showed that values around 7 give good results, so let's use this value for now: (410.34 - (15.18 / 7)) < y(p) <= 410.34 408.17 < y(p) <= 410.34 So, only those points that are in that range will be included in the average upper limit. Performance So far, the two algorhythms both work quite well when compared to hand-made measurements, while the difference between the two are poorly significant. Given this correspondance, we should choose the faster and simpler one. Another important issue is the choice of parameters. At the moment parameters must be specified manually by the user (or fixed in the source code), and there are no plans to change this. buffer analysis This analysis is optionally based on the height values calculated with one of the methods above. introduction In 1993, Parenti and Doglioni suggested the use, among other qualitative parameters, of a quantitative parameter which would be useful to describe a stone wall and eventually compare two walls. This quantitative parameter is calculated on a random area from the wall, as the ratio between the area occupied by stones and the "empty" areas around the stones. This value, if compared to other numeric parameters (most notably the number of stones that fall into the same area), can be useful when creating a tipology. Our analysis is based on this method, pushing the same concept beyond the barrier of the wall taken as a whole. the analysis For each stone-polygon, we start creating a buffer area. This is the area that contains all the points within a certain distance from the polygon boundary. How the distance is chosen can slightly change the results, depending on wheter a fixed value is used or a value proportional to some other value of each polygon (area, perimeter, height, width, etc..). After the buffer area has been created, the procedure is as follows: - subtract the stone area from the buffer area (which includes it) to get only the actual buffer. - find the intersection of the buffer area with the other surrounding stones (this is obtained by creating a multipolygon that includes all stones) and retrieve the total area of this intersection - the intersection_area / buffer_area ratio is the value we will use as an indicator of (possibly hidden) groups of stones. results So far, this method has failed to give the expected results. Lower values are obtained for stones that are near the wall limits, or have otherwise no stones on one or more sides. For normal stones, there are no significant variations in the obtained value. Though not related with the original idea, this method could be used to find which stones are suitable for further analyses that are based on the wall fabric.
https://bitbucket.org/steko/murature
CC-MAIN-2017-30
refinedweb
1,606
60.95
This week’s email is out with a delay thanks to a scheduling snafu, apologies to those left waiting on Tuesday morning. Two issues prior we discussed _email _in Django apps and in doing so I brought up another topic: templates. One step that can help manage email in any Django project is developing a consistent system for naming email templates and using email base templates. So what about “regular” templates? Like email, HTML templates are one of the “batteries included” in Django, and while templates _do _get quite a bit of attention, it’s mostly in how to build cool things with them - a good thing, surely - and not so much how to make them manageable. Confusing template organization and naming is the most obvious template problems in Django projects. The first step is to pick a strategy and to _be consistent _with it, whether that’s a naming strategy or location strategy. That said, for most projects we’ve found that grouping all project templates into a root ‘templates’ folder organized by app name is the best strategy for managing project templates. The alternative, locating them within app folders in template sub folders certainly works, however that’s geared more toward reusable apps. The benefit of using the project templates folder is that in addition to working on individual templates, developers tend to work on multiple templates at a time in such a way that it’s clearer seeing all of the templates together. This is especially true for teams large enough to have some division of specialization (e.g. front end specialists). To get a bit more granular, any given template folder (e.g. root or app) may and should have subfolders specific to features of the template rendering system, e.g. “includes”, “emails”, “tags”, etc. Any template used in more than one app should be moved up the project namespace. As to template names, the convention propagated by Django’s generic views, including model and purpose (or action) is very good to follow. It doesn’t always fit, but when it does it makes clear what a template does and why. Why bother with so much effort around names of files and their folder locations? Because ultimately these things save developer time, otherwise lost in either figuring things out or solving unnecessary errors. There are a lot of ways of getting both data (context) and conditional content into Django templates. The view provides a context, and you can use context processors to add globally available data, you can grab data from the request added by middleware, you can include templates, extend from templates, call template tags from within templates… But some things work better than others. The first thing to understand is whether you’re concerned primarily about transforming some data or some kind of dynamic rendering. For data, if it will be accessed across multiple views, especially across apps, then a context processor may be a good idea. The downside to context processors is that you’re adding to the “global template namespace” but they tend to simplify view contexts to the view specific data. Context processors can simplify views that require extensive context management from super classes, as well. _Include _statements work best when the template to include is (a) non trivial markup and (b) used in multiple locations. For instance a navigation menu with only minor data changes could be implemented nicely with an include. Includes can also be used to break out markup that may not be used in many other files but by virtue of being separated makes the original much easier to read. Template tags can be used to satisfy both, either creating a product from one or more values in the context or being used to render some non-trivial template logic. The downside to template tags is that they add at least a step in understanding the structure of templates. They should be used when the alternative include file would instead by riddled with if/then statements. Hint: that’s one of their single most important roles, solving for nasty template logic which is hard to read, update, and debug. Tags also have the feature of being testable on their own in a way that includes do not. By far the biggest problem maintaining templates in Django projects is overly complex template logic. Judicious use of context variables and template tags goes a long way toward solving this, not to mention precalculating values in the view itself. If you take nothing else away from this email, I hope its this. First, a little “trick” that a lot of developers seem to miss: the template names in Django templates are string literals and can be replaced with template variables. Yep, you can specify the template from which yours inherits from the view. Why would you need to do this? Well, you can use this for conditionally showing a different base template where, for example, you might implement a UI upgrade. There’s also a strategy I learned a while back from a colleague whereby you can use this to conditionally extend from a ‘blank’ template thus cleanly reusing a “normal” template for both full and partial (AJAX) requests. The other reason this is interesting is that it makes it easier to update the global UI by simply changing the base name that templates inherit from. This can’t always be done, of course, but it allows you to dynamically switch between a legacy base template and an updated base template, keeping them available at the flick of a switch. This makes the final step in updating a project’s templates that much simpler. simple.tag yours, Ben P.s. sometimes I have to radically shorten an email from what its subject demanded, and this is one of those cases. If there’s an aspect of wrangling Django templates you’d like to hear more about, just reply and let me know. Learn from more articles like this how to make the most out of your existing Django site.
https://wellfire.co/this-old-pony/making-django-templates-manageable--this-old-pony-49/
CC-MAIN-2019-22
refinedweb
1,009
59.53
QT Conflict starting Explorer from Matlab -- ERROR: exceptions.ImportError: Bug Description When I try to start bzr explorer from matlab, it fails to start and I get the error below. Matlab also contains a QT framework, and I assume there is a conflict between the two. Not sure if there is a workaround for bzr? >> !bzr explorer bzr: ERROR: exceptions. Referenced from: /Library/ Expected in: /Applications/ in /Library// from bzrlib. File "/Library/ from PyQt4 import QtCore, QtGui ImportError: dlopen( Referenced from: /Library/ Expected in: /Applications/ in /Library/ bzr 2.5b1 on python 2.6.6 (Darwin- arguments: ['/usr/ plugins: bash_completion colo[0.3.0], email[unknown], explorer[1.2.1], extmerge[unknown], fastimport[ netrc_ qbzr[ weave_ encoding: 'ISO8859-1', fsenc: 'utf-8', lang: 'en_GB.ISO8859-1' *** Bazaar has encountered an internal error. This probably indicates a bug in Bazaar. You can help us fix it by filing a bug report at https:/ including this traceback and a description of the problem. This looks like a different variation on bug 698104 to do with mismatched Qt versions. What version of Qt is matlab using? Looking at the info.plist I see a version string of 4.7 for QtGui... I suspect Matlab is changing the dylib load path to include its own Qt framework, which is superseding the system-level framework installed when bzr runs in a sub-shell. As for why the frameworks are incompatible, I don't know. I build the installer using Qt 4.7. If anybody can figure out what's wrong here, I'll gladly include the fix, but I don't have time to track this down. Note this is on OS X 10.7.1 with Bzr 2.5b1 -- but this also affects previous release versions of bzr...
https://bugs.launchpad.net/bzr-mac-installers/+bug/853862
CC-MAIN-2015-14
refinedweb
294
69.58
ST(4) NetBSD Kernel Interfaces Manual ST(4)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias. bus is scanned for devices. Any devices found which answer as `Sequential' type devices will be attached to the st driver. MOUNT SESSIONS The an `unmount device',, bits 0 and 1 of the minor number are interpreted as `sub.. BLOCKING MODES SCSI tapes may run in either `variable' or `fixed' block-size modes. Most QIC-type devices run in fixed block-size mode, where most nine-track tapes and many new cartridge formats allow variable block-size. The dif- ference suc- cession. Because there is some data to return (unless there were no records before the file mark), the read will succeed, returning that data. The next read will return immediately with an EOF (as above, if the file mark is never read, it remains for the next process to read if in no-rewind mode). FILE MARK HANDLING The handling of file marks on write is automatic. If the user has writ- ten don't understand why) that certain types of tape do not actually write two file marks to tape, but when read, report a `phantom')._t mt_count; }; The following operation values are defined for mt_op: MTWEOF Write mt_count end of file marks at the present head position. MTFSF Skip over mt_count file marks. Leave the head on the EOM side of the last skipped file mark. MTBSF Skip backwards over mt_count file marks. Leave the head on the BOM (beginning of media) side of the last skipped file mark. MTFSR Skip forwards over mt_count records. MTBSR Skip backwards over mt_count records. MTREW Rewind the device to the beginning of the media. MTOFFL Rewind the media (and, if possible, eject). Even if the device cannot eject the media it will often no longer respond to normal requests. MTNOP No-op; set status only. M MTCACHE Enable controller buffering. MTNOCACHE Disable controller buffering. MTSETBSIZ Set the blocksize to use for the device/mode. If the device is capable of variable blocksize opera- tion, and the blocksize is set to 0, then the drive will be driven in variable mode. This parameter is in effect for the present mount ses- sion only, mt(1), intro(4), mtio(4), scsi(4) HISTORY This st driver was originally written for Mach 2.5 by Julian Elischer, and was ported to NetBSD by Charles Hannum. This man page was edited for NetBSD by Jon Buller. BUGS The selection of compression could possibly also be usefully done as with a minor device bit. NetBSD 9.2 August 23, 1996 NetBSD 9.2
https://man.netbsd.org/NetBSD-9.2/i386/st.4
CC-MAIN-2021-39
refinedweb
446
75.4
Subject: Re: [boost] What C++14/1z standard or TS libraries would you like to have available on a C++11 compiler? From: Edward Diener (eldiener_at_[hidden]) Date: 2016-05-22 12:19:49 On 5/22/2016 11:40 AM, Vicente J. Botet Escriba wrote: > Hi, > > I would like to have your feedback on C++ standard library features you > would like to have available for a C++11 compiler. > > The idea would be to present a Boost.StdExtensions library that would > provide some of these features for review with some of these features. I do not understand what you are asking about ? Don't most compilers when set to C++11 mode on up support C++ standard libraries which support the use of C++11 idioms ? Evidently I am confused what you are proposing. Could you specify your idea for a Boost.StdExtensions library more clearly. > > Please , let me know if you are interested in participating in this > project and working on some specific parts. > > This library should avoid as much Boost dependencies as possible. > > How the library could be structured? I believe that it should follow the > C++ standard files. > Which folder should be used? boost/stdext? boost/stdext11? > Which namespace? boost::stdext? > > I have prefixed with a * the lines that interest myself and with VBE* > those that I could work on. > > The features that need compiler help or that need C++14/17 language > features are excluded and prefixed by N/A. > > Please be free to add a * if you are interested and your name as well if > you want to participate. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2016/05/229845.php
CC-MAIN-2021-31
refinedweb
287
76.52
Delegates are special types supported by the .NET Framework that represent a strongly typed method signature. Delegates can be instantiated and formed over any target method and instance combination where the method matches the method’s signature. C# allows the creation of special classes using the delegate keyword. We call such a class a delegate class. Instances of these delegate classes are called delegate objects. Conceptually, a delegate object is a reference to one or more methods (static or instance). We can then call/invoke a delegate object with the same syntax to call a method. This causes the call to a method. But note that the call to these methods is done by the same thread which called the delegate object. We refer to this as a synchronous call. But when making a synchronous call to a method, the caller thread blocks while the call is active. While the thread is blocked, it could create other threads, despite the fact that the CPU may be idle. So even though these threads might not be consuming CPU, they are wasting resources, which is not cost-effective. When a thread makes an asynchronous call to a method, the call returns immediately. The caller thread is not blocked; it is free to perform some other task. The .NET infrastructure obtains a thread for the method invocation and delivers the in parameters passed by the calling code. The async thread can then run the method in parallel to the calling thread. If the method generates some data and returns this value, the calling thread must be able to access this data. The .NET asynchronous feature supports two mechanisms: that calling thread can either ask for the results, or the infrastructure can deliver the results to the calling thread when the results are ready. The purpose of this article is to explain delegates and how to use them asynchronously. delegate In C#, a new delegate type is created using the delegate keyword: public delegate void MyDelegate(int x, int y); This says that we created a new delegate type, named MyDelegate, which can constructed over methods with void return types and that accept two arguments each typed as int. Our delegate can then be formed over a target, passed around, and then invoked at some point in the future. Invocation in C# looks like an ordinary function call: MyDelegate void int class Foo { void PrintPair(int a, int b) { Console.WriteLine("a = {0}", a); Console.WriteLine("b = {0}", b); } void CreateAndInvoke() { // implied 'new MyDelegate(this.PrintPair)': MyDelegate del = PrintPair; del(10, 20); } } Doesn’t make sense yet? CreateAndInvoke constructs a new MyDelegate, formed over the PrintPair method with the current this pointer as the target. The actual IL emitted by the C# compiler shows some of the complexities of delegates in the underlying type system: CreateAndInvoke PrintPair this); } The constructor is used to form a delegate over a target object and a function pointer. The Invoke, BeginInvoke, and EndInvoke methods implement the delegate invocation routine and are marked as internal (i.e., Runtime in IL) to indicate to the CLR that it provides the implementation; their IL bodies are left blank. Invoke performs a synchronous invocation, while the BeginInvoke and EndInvoke functions follow the Asynchronous Programming Model pattern. But, notice first that the MyDelegate type breaks a rule, namely that structs cannot derive from other types other than System.ValueType. Delegates have special support in the Common Type System (CTS), so this is allowed. Also notice that MyDelegate derives from MulticastDelegate; this type is the common base for all delegates created in C#, and supports delegates that have multiple targets. Consider another delegate creation: Invoke BeginInvoke EndInvoke internal System.ValueType MulticastDelegate public delegate int StringDelegate(string str); This can be declared in a class or at a global scope. The C# compiler will generate a new class from this declaration and derive from System.MulticastDelegate. Examine the methods of this class and its base class, System.Delegate (again): System.MulticastDelegate System.Delegate public sealed class StringDelegate : System.MulticastDelegate { public StringDelegate (object obj, int method); public virtual int Invoke(string str); public virtual IAsyncResult BeginInvoke(string str, AsyncCallback asc, object stateObject); public virtual int EndInvoke(IAsyncResult result); } Now, let’s see some code that correlates to our first delegate creation, MyDelegate: using System; public static class App { public delegate void MyDelegate(int x, int y); public static void PrintPair(int a, int b) { Console.WriteLine("a = {0}", a); Console.WriteLine("b = {0}", b); } public static void Main() { // Implied 'new MyDelegate(this.PrintPair)': MyDelegate d = PrintPair; // Implied 'Invoke': d(10, 20); } } When compiled, it produces this output: a = 10 b = 20 Assume that we have (again) defined our own MyDelegate type, like this in C#: delegate string MyDelegate(int x); We now know that this represents a function pointer type that can refer to any method taking a single int argument and returning a string. And, we also know that when working with an instance of this delegate type, we’ll declare variables of type MyDelegate. Furthermore, we know that behind the scenes, the compiler is generating a new class (type) for us: string private sealed class MyDelegate : MulticastDelegate { public extern MyDelegate(object object, IntPtr method); public extern virtual string Invoke(int x); public extern virtual IAsyncResult BeginInvoke(int x, AsyncCallback callback, object object); public extern virtual string Endinvoke((IAsyncResult result); } Now, let’s assume that we have our own custom type, MyType, with a method MyFunc whose signature matches MyDelegate’s exactly. Now notice that the parameters are not named identically. This is all right, because delegates only require that the expected types be found in the correct signature’s positions: MyType MyFunc class MyType { public string MyFunc(int foo) { return "MyFunc called with the value '" + foo + "' foo foo; } } Once we have a delegate type in the metadata and a target function we’d like to call, we must form an instance of the delegate over a target. This constructs a new instance of the delegate type using the constructor MyDelegate(object, IntPtr). The code passes the target as the first argument and a pointer to the code function as the second. The syntax for this is: MyDelegate(object, IntPtr) MyType mt = new MyType(); MyDelegate md = mt.MyFunc; So now, we put the sum of the parts to form the whole: using System; delegate string MyDelegate(int x); class MyType { public string MyFunc(int foo) { return "MyFunc called with the value '" + foo + "' for foo"; } } public class Program { public static void Main() { MyType mt = new MyType(); MyDelegate md = mt.MyFunc; Console.WriteLine(md.Invoke(5)); Console.WriteLine(md(5)); } } The code compiles and spits out this result: MyFunc called with the value '5' for foo MyFunc called with the value '5' for foo Before using an asynchronous delegate, it is good to remember that all the delegate types automatically offer two methods named BeginInvoke and EndInvoke. The signatures of these methods are based on the signature of the delegate type which contains them. For example, the following delegate type: delegate int MyDelegate(int x, int y) exposes the following methods by compiler generation: IAsyncResult BeginInvoke(int x, int y, AsyncCallback callback, object object, IAsyncResult result); int EndInvoke (IAsyncResult result); These two methods are generated by the compiler. To call a method in an asynchronous way, you must first reference it using a delegate object which has the same signature. Then, you have to call BeginInvoke on this delegate object. As you have seen, the compiler ensures that the first arguments of the BeginInvoke method are the arguments of the method to be called. The last two arguments of this method, IAsyncResult and object, will be discussed shortly. The return value of an asynchronous call can be recovered by calling the EndInvoke method. There also the compiler ensures that the return value of EndInvoke is the same as the return value of the delegate type (this type is an int in our example). The call to EndInvoke is blocking, meaning that the call will only return when the asynchronous execution is done. The following example illustrates the asynchronous call to a ShowSum method: IAsyncResult object ShowSum using System; using System.Threading; public class Program { public delegate int TheDelegate( int x, int y); static int ShowSum( int x, int y ) { int sum = x + y; Console.WriteLine("Thread #{0}: ShowSum() Sum = {1}", Thread.CurrentThread.ManagedThreadId, sum); return sum; } public static void Main() { TheDelegate d = ShowSum; IAsyncResult ar = d.BeginInvoke(10, 10, null, null); int sum = d.EndInvoke(ar); Console.WriteLine("Thread #{0}: Main() Sum = {1}", Thread.CurrentThread.ManagedThreadId, sum); } } Output: Thread #3: ShowSum() Sum = 20 Thread #1: Main() Sum = 20 The BeginInvoke method has a parameter for each parameter of the underlying delegate (just like Invoke) and adds two parameters: an IAsyncCallback delegate, which gets invoked when the asynchronous operation completes, and an object, which is passed as the IAsyncResult.AsyncState property value to the callback function. The method returns an IAsyncResult, which can be used to monitor completion, wait on the WaitHandle, or complete the asynchronous call. IAsyncCallback IAsyncResult.AsyncState WaitHandle public interface IAsyncResult { // Properties object AsyncState { get; } WaitHandle AsyncWaitHandle { get; } bool CompletedSynchronously { get; } bool IsCompleted { get; } } When the delegate has completed execution, you must call EndInvoke on the delegate, passing in the IAsyncResult. This cleans up the WaitHandle (if it was allocated), throws an exception if the delegate failed to execute correctly, and has a return type matching the underlying method’s. It returns the value returned by the delegate invocation: using System; public sealed class Program { delegate int IntIntDelegate(int x); private static int Square(int x) { return x * x; } private static void AsyncDelegateCallback(IAsyncResult ar) { IntIntDelegate f = (IntIntDelegate)ar.AsyncState; Console.WriteLine(f.EndInvoke(ar)); } public static void Main() { IntIntDelegate f = Square; /* Version 1: Spin wait (quick delegate method) */ IAsyncResult ar1 = f.BeginInvoke(10, null, null); while (!ar1.IsCompleted) // Do some expensive work while it executes. Console.WriteLine(f.EndInvoke(ar1)); /* Version 2: WaitHandle wait (longer delegate method) */ IAsyncResult ar2 = f.BeginInvoke(20, null, null); // Do some work. ar2.AsyncWaitHandle.WaitOne(); Console.WriteLine(f.EndInvoke(ar2)); /* Version 3: Callback approach */ IAsyncResult ar3 = f.BeginInvoke(30, AsyncDelegateCallback, f); // We return from the method (while the delegate executes). } } 100 400 Now, if the method has parameters that are reference types and are passed in as parameters, then the asynchronous method will be able to call methods on the reference types that change its state. You can use this to return values from the async method. The code below shows an example of this. The GetData delegate takes an object of type System.Array as an in parameter. Since this passed in by reference, this method can change the values in the array. However, since the object can be accessed by two threads, you have to make sure that you do not access this shared object until the asynchronous method has completed: GetData System.Array in using System; class App { delegate void GetData(byte[] b); static void GetBuf(byte[] b) { for (byte x = 0; x < b.Length; x++) b[x] = (byte)(x*x); } static void Main() { GetData d = new GetData(App.GetBuf); byte[] b = new byte[10]; IAsyncResult ar; ar = d.BeginInvoke(b, null, null); ar.AsyncWaitHandle.WaitOne(); for (int x = 0; x < b.Length; x++) Console.Write("{0} ", b[x]); } } 0 1 4 9 16 25 36 49 64 81 100 To use a callback method, you need to reference it with a delegate object of type System.AsyncCallback passed as the next to the last argument to the BeginInvoke method. This method must conform itself to the delegate type, which means it must have a return type of void (in the case of the example below) and take a single argument of type IAsyncResult: System.AsyncCallback using System; using System.Threading; using System.Runtime.Remoting.Messaging; class Program { public delegate int MyDelegate(int x, int y); static AutoResetEvent e = new AutoResetEvent(false); static int WriteSum( int x, int y) { Console.WriteLine("Thread# {0}: Sum = {1}", Thread.CurrentThread.ManagedThreadId, x + y); return x + y; } static void SumDone(IAsyncResult async) { Thread.Sleep( 1000 ); // AsyncResult of the System.Runtime.Remoting.Messaging namepsace MyDelegate func = ((AsyncResult) async).AsyncDelegate as MyDelegate; int sum = func.EndInvoke(async); Console.WriteLine("Thread# {0}: Callback method sum = {1}", Thread.CurrentThread.ManagedThreadId, sum); e.Set(); } static void Main() { MyDelegate func = WriteSum; // the C# 2.0 compiler infer a delegate object of type // AsyncCallback to reference the SumDone() method IAsyncResult async = func.BeginInvoke(10, 10, SumDone, null); Console.WriteLine("Thread# {0}: BeginInvoke() called! Wait for SumDone() completion.", Thread.CurrentThread.ManagedThreadId); e.WaitOne(); Console.WriteLine("Thread# {0}: Bye....", Thread.CurrentThread.ManagedThreadId); } } Compiling this code results in the following: Thread# 1: BeginInvoke() called! Wait for SumDone() completion. Thread# 3: Sum = 20 Thread# 3: Callback method sum = 20 Thread# 1: Bye.... This article used C# 2.0 syntax and therefore had is its basis on writing delegate code on the .NET Framework 2.0 platform. The reason why I state this is that often in technical documentation, the topic of delegates will be coupled with, or have relation to, events. An event is a message sent by an object (a control) to signal the occurrence of an action. The action could be caused by some user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it called the event receiver. In event communication, the event sender class does not know which object or method will receive (handle) the event it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. A special type called a delegate provides the functionality of a function pointer. A delegate is a class that can hold a reference to a method. As has been stated, a delegate class has a signature, and can hold references only to methods that match its signature. When writing code for Windows Forms, the following example show an event delegate declaration: public delegate void AlarmEventHandler( object sender, EventArgs e); So while we examined how to use delegates with the goal of understanding how to use them asynchronously, we also should clarify any other usage of delegates (in this case, a Windows Forms UI). The standard signature of an event handler delegate defines a method that does not return a value, who first parameter is of type Object and refers to the instance that raises the event, and whose second parameter is derived from type EventArgs and holds that event data. EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data. To associate the event with the method that will handle the event, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. Having said that said, let’s look briefly at multithreading and GUI applications. If you have been involved with Win32 development, then you would know that it is typical to access APIs synchronously; a thread initiates some task, then waits patiently for the task to complete. If the code reaches a more advanced level, it could create a worker thread to make this synchronous call, freezing the main thread to continue its work. Using worker threads to perform length blocking calls crucial for GUI applications because the blocking thread that pumps the message queue disables the UI of the application. The process of creating worker threads like this is never straightforward. In short, thread creation is expensive. Creating a new worker thread every time you need to make a blocking call could result in more threads than are necessary, increasing resource consumption. In .NET, asynchronous execution can be a valuable design technique. For example, you should use asynchronous execution in a Windows® Forms application when you want to execute a long-running command without blocking the responsiveness of the user interface. As you will see, programming with delegates makes it relatively easy to run a command asynchronously on a secondary thread. That means you can build a Windows Forms application that executes long-running calls across the network without freezing the user interface. Herein lies the issue of control.BeginInvoke vs. delegate.BeginInvoke. When you call Control.BeginInvoke, the call to Control.Invoke is made on a threadpool thread and the call to BeginInvoke returns immediately. So, in effect, you have a worker thread calling BeginInvoke. The threadpool thread then takes over and calls Control.Invoke, waiting on the return value. The delegate passed to Invoke is then invoked on the UI thread. If you call Delegate.BeginInvoke, then you go from your worker thread to the threadpool thread, where the method pointed to by the delegate gets executed. If you are accessing UI elements on this thread, you are going to get unpredictable results. To call Control.BeginInvoke with an end goal of having a matching EndInvoke just allows the processing to continue on the thread that called them, not waiting for the UI to update. Having examined the differences between delegate's BeginInvoke and Control.BeginInvoke, it appears that Control's BeginInvoke() ensures that the delegate is invoked in the thread that created the Control's context. This implies no thread pool threads are involved. This was illustrated by a .NET MVP's test application. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)); } supercat9 wrote:Although the term "BeginInvoke" is used with both delegates and controls, the behavior is very different and it might be good to explicitly mention this. BillWoodruff wrote:Looking back over the code in this article, I don't see any use of objects of type 'control. logicchild wrote:Hi supercat9. Point taken. I will adjust the article accordingly. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/articles/41777/net-framework-delegates-understanding-asynchronou?fid=1548354&df=90&mpp=10&noise=1&prof=true&sort=position&view=expanded&spc=none
CC-MAIN-2017-04
refinedweb
3,015
54.52
Re: [jslint] Re: This eval is not evil Expand Messages - On Thu, Oct 18, 2012 at 6:46 PM, Marcel Duran <marcelduran@...> wrote: > client['eval'.toString()]("return 100.5", 0, function (err, res) {Interesting hack, but I don't think this improves readability. Anyways, it's easier to just use alternative names: client.EVAL All Redis commands can be passed to the client either in all lowercase or all uppercase. - On Thu, Oct 18, 2012 at 7:22 PM, Kirk Cerny <kirksemail@...> wrote: > I believe that it is close enough to a reserved word to avoid using itWhat's bad about using reserved words as property names? > as a property name. In his book, Douglas mentions that it is *bad* that reserved words cannot be used as object property names without quoting: * Page 7, section "Names": It is not permitted to name a variable or parameter with a reserved word. Worse, it is not permitted to use a reserved word as the name of an object property in an object literal or following a dot in a refinement. * Page 103, section "Reserved Words": They cannot be used to name variables or parameters. When reserved words are used as keys in object literals, they must be quoted. They cannot be used with the dot notation, so it is sometimes necessary to use the bracket notation instead: var method; // ok var class; // illegal object = {box: value}; // ok object = {case: value}; // illegal object = {'case': value}; // ok object.box = value; // ok object.case = value; // illegal object['case'] = value; // > I also think it makes the code harder to read and understand, becauseSo what about "case" in the above example? Would you also avoid using > whenever I read eval any where my first impression is that it is the > eval function. it? The dot notation namespaces variable names, and to me that is not confusing. To me reading `redisClient.eval` is no more confusing that something like `redisClient.redisEval`. If one is confused by this, then I propose avoiding `eval` at all, and instead name it `lave`. Surely, `redisClient.lave` is less confusing... ;-) I understand if Douglas doesn't want to make an exception on the basis that this would make the parser too complicated. All the other arguments, I don't understand. Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/jslint_com/conversations/topics/3059?var=0&l=1
CC-MAIN-2015-35
refinedweb
390
63.49
Sean Leather wrote: > That doesn't work if you want to use two packages that have modules > sharing the same hierarchical name, and this is a definite possibility > given my statements above. Of course, having the ability to import > modules from specific packages [1] would fix this, but only as long as > the package names are also unique. > > Personally, I like the Java package naming scheme recommendation. It > scales better, because each package name uses the organization or URI to > uniquely identify a subset. Personally, I have major qualms with the Java package naming scheme. In particular, using domain names sets the barrier to entry much too high for casual developers (e.g. most of the Haskell user base). Yes, DNs are cheap and plentiful, but this basically requires a lifetime lease of the DN in question and the migration path is covered in brambles. The alternative is simply to lie and make up a DN, in which case this degenerates into the exact same resource quandary as doing nothing (but with high overhead in guilt or registration paperwork). The way CPAN is set up is much more egalitarian, though mired in a bit much administrivia for casual developers. The orthogonality of package names to module names is something I consider very much a feature, and not a bug. The only other packaging system I've seen to offer this is Monticello for Squeak/SmallTalk, and I've missed it ever since. By making packages orthogonal that allows for developers to create drop-in replacement packages that offer the same module services as another package, without needing to alter any code that uses the old package (save relinking/recompiling). This is the same advantage as allowing different modules to offer the same functions (e.g. having Data.ByteString as a drop-in for the [ ]-portions of the Prelude), but lifted up to the next tier. The question then is two-fold. First, is the question of how to minimize the problems of ambiguity and how to resolve conflicts when they arise. Second, is the question of whether this is really the job of Haskell, the language itself, or whether it is more appropriately dealt with by the build tools, e.g. Cabal. I'll deal a bit more with the latter question. ((. )) I do like your (Sean Leather's) patch for being able to specify package names in source code, though I'd think something like Core's "package:module.module.module" syntax would be better if it gets adopted into Haskell'. I do however think that specifying the package should be optional, with conflicts to be resolved by commandline flags or via Cabal. Without this we loose the ability to have drop-in replacement packages, which in turn greatly complicates migration paths. The community is still young, but forks do happen and we would do best to allow for forwards compatibility whenever possible. This approach also gives the same sort of split control as the various {-# FOO #-} pragma give. As an ad-hoc GHC solution, adding a new PACKAGE pragma would be better than just using a string there. In theory we can already do this with OPTIONS_GHC, though that pragma seems not to respect the -package option. Of course, the new pragma should be position restricted to make it obvious which imports it applies to, rather than assuming to apply to the whole file (i.e. by putting it where you put the strings). One issue with this and Java's scheme of just concatenating package names onto module names is that they offer no provisions for specifying version restrictions. For a PACKAGE pragma we could design it deal with this too, since the modules themselves don't have versions. Of course this starts getting into hairy issues which Cabal was designed to resolve, so porting it back to the compiler seems misguided. Perhaps a simpler option, for a Haskell' world, would be to give modules versions and give the import syntax some way of specifying the version to use. Sticking with something like the current packaging system, packages would just specify the module versions they provide, and those versions need not be related to the version of the package itself. This has the benefit of being able to release and maintain legacy packages, once the world has forked or moved on to a new major version. As an addendum to this, it could be helpful if "package" names (i.e. alphanumeric sequences) were a part of the module version specification. This way a package hfoo-legacy could continue to provide the hfoo-1.24 versions of modules, and it would be the package that forked off rather than forcing the new hfoo package to rename itself to break ties from the legacy code. Another ability that the package/module system lacks right now is a good way for annotating deprecations. Java has this, but again they do it wrong. Whenever something is specified as deprecated it needs to provide a migration path to non-deprecated code. Simply saying "you fail" is an insufficient error message. This proposal doesn't solve the resource allocation issue. That issue will always be around so long as we assume nodes in the dependency graph have unique names. And that assumption is a very useful expedient so we're unlikely to abandon it any time soon (though maybe we should). But I think giving modules explicit name-version annotations is a better path forward than adding more bureaucracy to the module hierarchy. I think the suggested best practices for naming modules should be refined since they're starting to get out of date with all the code on Hackage. In particular there's a lot of conflict about (1) where to put new interesting Num data types (Data.Number.*, Data.*, Numeric.*, ...?); (2) where to put testing and diagnostic tools (Debug.*, Test.*); and (3) where to put modules for the core operation of application projects. But beyond providing better guidance, I don't think we should have a central body issuing leases for the module namespace. Especially because we already have a packaging system which is orthogonal to the module system. One of the reasons I love Haskell so much is because it is so extremely agile. I've been an active open-source developer for many years, and of all the languages I've used Haskell has by far the easiest system for communal public release of code. Perl's community is also very nice though it's gotten to be large enough that they do really need the bureaucracy they have. All the same it means less of my Perl code has made it into the wild than I would have liked. As for C and Java, the only stuff of mine that's managed to eek out into the public are whole projects, never any of the many small building blocks it takes to make something run and to make people able to bang out a program in a few hours because all the dirty work is already done and available in a large public repository. -- Live well, ~wren
http://www.haskell.org/pipermail/haskell-cafe/2008-August/046168.html
CC-MAIN-2014-42
refinedweb
1,189
60.24
hi im stuck with an IndentationError someone can help me def shipping_cost_ground(weight): if weight <= 2: price_per_pound = 1.50 elif weight <= 6: price_per_pound = 3.00 elif weight <= 10: price_per_pound = 4.00 else: price_per_pound = 4.75 return 20 + (price_per_pound * weight) print(shipping_cost_ground(8.4)) shipping_cost_premium = 125.00 def shipping_cost_drone(weight): if weight <= 2: price_per_pound = 4.50 elif weight <= 6: price_per_pound = 9.00 elif weight <= 10: price_per_pound = 12.00 else: price_per_pound = 14.25 return (price_per_pound * weight) print(shipping_cost_drone(1.5)) def cheap_shipping_method(weight): ground = shipping_cost_ground(weight) premium = shipping_cost_premium drone = shipping_cost_drone(weight) if ground < premium and ground < drone: <----- identation error here method = "standard ground" cost = ground elif premium < ground and premium < drone: method = "premium ground" cost = premium else: method = "drone" cost = drone print("The cheapest option available is $%.2f with %s shipping." % (cost, method) )
https://discuss.codecademy.com/t/sal-shipping-indentationerror/437644
CC-MAIN-2019-43
refinedweb
131
62.85
The fastest way to get started experimenting with Mappedin Web SDK is to fork the Mappedin template CodeSandbox. Mappedin Web SDK v4 is available as @mappedin/mappedin-js in NPM. To start a new project locally, we introduce a fast way to do that using Vite. More information about setup options is in the Vite Getting Started -guide. The guides are written in JavaScript, however, the SDK includes comprehensive types as it is written in Typescript. Run the following commands in your shell to bootstrap a new project and install Mappedin Web SDK. yarn create vite mappedin-v4-guidecd mappedin-v4-guideyarn add @mappedin/mappedin-js Modify the contents of the following files: index.html, src/main.js to match the following. <!DOCTYPE html><html><head><meta charset="utf-8" /><title>Mappedin v4</title><meta name="viewport" content="width=device-width,initial-scale=1" /></head><body><div id="app"></div><script type="module" src="src/main.js"></script></body></html> import { getVenue, showVenue } from "@mappedin/mappedin-js";import "@mappedin/mappedin-js/lib/mappedin.css";//("app"), venue);}init(); To run the project with hot reloading, run yarn run dev. Now, you should be able to see a prompt in your shell telling you to open your browser at (default port). You should be greeted by a rendering of the Mappedin Demo Mall, like the below CodeSandbox example. The 3D rendered mall map can be zoomed, panned and rotated.
https://developer.mappedin.com/web-sdk/v4/getting-started/
CC-MAIN-2022-33
refinedweb
237
57.77
Next: Character Strings in Oct-Files, Previous: Getting Started with Oct-Files, Up: Oct-Files [Contents][Index] Octave supports a number of different array and matrix classes, the majority of which are based on the Array class. The exception is the sparse matrix types discussed separately below. There are three basic matrix types Matrix A double precision matrix class defined in dMatrix.h, ComplexMatrix A complex matrix class defined in CMatrix.h, and BoolMatrix A boolean matrix class defined in boolMatrix.h. These are the basic two-dimensional matrix types of Octave. In addition there are a number of multi-dimensional array types including NDArray A double precision array class defined in dNDArray.h ComplexNDarray A complex array class defined in CNDArray.h boolNDArray A boolean array class defined in boolNDArray.h int8NDArray int16NDArray int32NDArray int64NDArray 8, 16, 32, and 64-bit signed array classes defined in int8NDArray.h, int16NDArray.h, etc. uint8NDArray uint16NDArray uint32NDArray uint64NDArray 8, 16, 32, and 64-bit unsigned array classes defined in uint8NDArray.h, uint16NDArray.h, etc. There are several basic ways of constructing matrices or multi-dimensional arrays. Using the class Matrix as an example one can Matrix a; This can be used for all matrix and array types. size. For example: dim_vector dv (2, 3); // 2 rows, 3 columns Matrix a (dv); This can be used on all matrix and array types. Matrix a (2, 2) However, this constructor can only be used with matrix types. These types all share a number of basic methods and operators. Many bear a resemblance to functions that exist in the interpreter. A selection of useful methods include The () operator or elem method allow the values of the matrix or array to be read or set. These can take a single argument, which is of type octave_idx_type, that is the index into the matrix or array. Additionally, the matrix type allows two argument versions of the () operator and elem method, giving the row and column index of the value to obtain or set. Note that these functions do significant error checking and so in some circumstances the user might prefer to access the data of the array or matrix directly through the fortran_vec method discussed below. The total number of elements in the matrix or array. The number of bytes used to store the matrix or array. The dimensions of the matrix or array in value of type dim_vector. The number of dimensions of the matrix or array. Matrices are 2-D, but arrays can be N-dimensional. A method taking either an argument of type dim_vector, or in the case of a matrix two arguments of type octave_idx_type defining the number of rows and columns in the matrix. This method returns a pointer to the underlying data of the matrix or array so that it can be manipulated directly, either within Octave or by an external library. Operators such an +, -, or * can be used on the majority of the matrix and array types. In addition there are a number of methods that are of interest only for matrices such as transpose, hermitian, solve, etc. The typical way to extract a matrix or array from the input arguments of DEFUN_DLD function is as follows #include <octave/oct.h> DEFUN_DLD (addtwomatrices, args, , "Add A to B") { int nargin = args.length (); if (nargin != 2) print_usage (); else { NDArray A = args(0).array_value (); NDArray B = args(1).array_value (); if (! error_state) return octave_value (A + B); } return octave_value_list (); } To avoid segmentation faults causing Octave to abort this function explicitly checks that there are sufficient arguments available before accessing these arguments. It then obtains two multi-dimensional arrays of type NDArray and adds these together. Note that the array_value method is called without using the is_matrix_type type, and instead the error_state is checked before returning A + B. The reason to prefer this is that the arguments might be a type that is not an NDArray, but it would make sense to convert it to one. The array_value method allows this conversion to be performed transparently if possible, and sets error_state if it is not. A + B, operating on two NDArray’s returns an NDArray, which is cast to an octave_value on the return from the function. An example of the use of this demonstration function is addtwomatrices (ones (2, 2), eye (2, 2)) ⇒ 2 1 1 2 A list of the basic Matrix and Array types, the methods to extract these from an octave_value, and the associated header file is listed below. Next: Character Strings in Oct-Files, Previous: Getting Started with Oct-Files, Up: Oct-Files [Contents][Index]
http://www.gnu.org/software/octave/doc/interpreter/Matrices-and-Arrays-in-Oct_002dFiles.html
CC-MAIN-2015-35
refinedweb
765
54.22
I need to implement a read / write function for my node.cpp file. I had a friend suggest using (partially) a queue to write / restore tree structure from the input file that will be used to test the program (do not have access to it). Below you will see my three files. The one that needs to be manipulated is node.cpp. Animal.cpp #include <cassert> #include <fstream> #include <string> #include "node.h" using namespace std; bool getYesNoAnswer() { // get yes no answer while (true) { string ans; getline(cin, ans); if ((ans[0] == 'y') || (ans[0] == 'Y')) return true; else if ((ans[0] == 'n') || (ans[0] == 'N')) return false; cout << "please answer yes or no.\n"; } } void learnNewAnimal(node* current) { // learn about a new animal type string currentAnimal = current->question; cout << "what is your animal?\n"; string newAnimal; getline(cin, newAnimal); cout << "What is a yes/no question that I can use to tell a " << current->question << " from a " << newAnimal << " ?\n"; string newQuestion; node * node1 = new node(newAnimal, 0, 0); node * node2 = new node(currentAnimal, 0, 0); // make sure allocation worked assert ((node1 != 0) && (node2 != 0)); getline(cin, newQuestion); cout << "For a " << newAnimal << " is the answer yes or no?\n"; if (getYesNoAnswer() != 0) { current->ifYes = node1; current->ifNo = node2; } else { current->ifYes = node2; current->ifNo = node1; } current->question = newQuestion; } void animalGame(const char* fileName) { // initialize the database node* root = 0; { ifstream in (fileName); if (in.good()) in >> root; } if (root == 0) // file was empty or nonexistent root = new node ("cat", 0, 0); // play the game node * current = root; // now start the game cout << "Let's play \"Guess the Animal\".\n"; while (current != 0) { // if current node has children it is a question if (current->ifYes != 0) { cout << current->question << '\n'; if (getYesNoAnswer()) current = current->ifYes; else current = current->ifNo; } // if no children it is an answer else { cout << "I know. Is it a " << current->question << " ?\n"; if (getYesNoAnswer()) cout << "I won.\n"; else { // we didn't get it. // time to learn something learnNewAnimal(current); } cout << "Try again?\n"; if (getYesNoAnswer()) current = root; else current = 0; } } // Save the modified question set ofstream out (fileName); out << root << flush; } int main (int nargs, char** argv) { if (nargs != 2) { cerr << "Usage: animal filename\n" << " where the filename denotes a file used both\n" << " to read an existing database of questions (may\n" << " be empty or even nonexistent, in which case a\n" << " default initialzation is used instead) and to\n" << " receive the modified database of questions\n" << "afterwards." << endl; return -1; } animalGame(argv[1]); return 0; } Node.h #ifndef NODE_H #define NODE_H #include <iostream> #include <string> // // binary tree node for animal guessing game // // Each node contains a question and and pointers // to the node representing yes and no responses, or // an animal name and two null pointers // struct node { std::string question; node* ifYes; node* ifNo; node (std::string q, node* yes = NULL, node* no = NULL) : question(q), ifYes(yes), ifNo(no) {} private: // read a tree from in storing the tree root in t static void read (std::istream& in, node*& t); // write the tree whose root is given. // Note: the form written out by this function should be something // that read(...) will accept, recreating the original tree. static void write (std::ostream& out, const node* root); friend std::istream& operator>> (std::istream&, node*&); friend std::ostream& operator<< (std::ostream&, const node*); }; inline std::ostream& operator<< (std::ostream& out, const node* n) { node::write (out, n); return out; } inline std::istream& operator>> (std::istream& in, node*& n) { node::read (in, n); return in; } #endif Node.cpp #include "node.h" #include <cassert> /* Input/Output format for this program. A tree of questions and answers is represented by multiple lines of text. There will always be at least one line of text. Each line represents one node in the tree. Each begins with either a 'Q' or an 'A', indicating whether the node is a Question node or an Answer node, followed by one or more blank spaces, followed by the text of the question or answer. The text of a question or answer begins with the first non-blank character after the Q or A and continues until the end of the line. Each 'Q' line is followed immediately by two blocks of 'Q' and 'A' lines. The first block describes the collection of questions and answers relevant following a "yes" answer to the first question. The second block describes the collection of questions and answers relevant to a "no" answer to the opening question. For example, Q Does it live in the water? Q Does it have webbed feet? A Duck A Fish A Cat Describes a tree in which the first question to be asked is "Does it live in the water?". If the person playing the game answers "yes", then the block of lines Q Does it have webbed feet? A Duck A Fish is relevant (i.e., the program will next ask about webbed feet). If the person answers "no". then the block of lines A Cat is relevant (i.e., the program will next ask "Is it a cat?". The "indentation" shown in the sample above is purely for human readability. It is not required in your output, though your input routine should tolerate it if it is present. */ using namespace std; // write the tree whose root is given. // Note: the form written out by this function should be something // that read(...) will accept, recreating the original tree. void node::write( std::ostream& out, const node* root ) { // insert your code here const node* cur = root; out << cur->question << std::endl; out << cur->ifYes->question << std::endl; // Originally all that was there was //insert your code here } // read a tree from in storing the tree root in t void node::read( istream& in, node*& t ) { // replace the line below by your own code //t = NULL; std::string line; if( getline( in, line ) ) t = new node ( line, 0, 0 ); if( getline( in, line ) ) t->ifYes = new node ( line, 0, 0 ); //Originally all that was there was t=Null (which needs to be replaced) } Do you guys have any suggestions on what method to use to complete this program or a link that clearly describes tress and how to use them? Thanks
http://www.dreamincode.net/forums/topic/324329-help-with-readwrite-for-queue/
CC-MAIN-2016-07
refinedweb
1,038
69.72
Why encrypt? It's normal when you start making software to not worry about many things: performance, security, or even the products you make. However, if you have a product that people are starting to use, you owe it to them to make their data safe. Encryption is used to change data so that it cannot be read unless the reader has privileged information. It is mainly used with passwords so that if your application is compromised by a hacker, they cannot access the passwords that your users have given you. It can also be used with other PII (Personally-Identifiable Information), such as passport numbers, credit card details, and more. What is encryption? Four words that frequently get confused with one another are encryption, encoding, hashing, and obfuscation. Though similar, they have different purposes and behave differently. When we encrypt something, we can decrypt it later. For this, we use a key, which is another piece of data that should be kept safe. When we encode something, we can easily decode it back by using the same or a similar algorithm to the one that did the encoding. Encoding is used to change data from one format to another (for example, encoding text as ASCII values). When we hash something, we cannot "unhash" it. You can hash some data to come up with a long string of characters. If you change the data and hash it again, the string changes. Thus it can be used to easily compare data, by just comparing the hashes. When we obfuscate something, it means making it difficult to understand. For example, some techniques for obfuscation may be minification or changing source code so it looks like it does something different from what it actually does; thus making it more difficult to understand. There are limits to obfuscation, as the content must still be readable by whomever is meant to consume it—for example, obfuscated data must still be valid, and obfuscated computer code must still be runnable by the machine. Hashing with Werkzeug If you have a Flask and Python application and you want to start hashing PII quickly (so you can't unhash it later), you can do so by using a Flask dependency that comes with a set of encryption functions: werkzeug. Want to encrypt with Python, but not using Flask? Check out our other blog post. from werkzeug.security import generate_password_hash, check_password_hash ... @app.route('/register', methods=['POST']) def register_user(): username = request.form['username'] password = request.form['password'] try: User(username, generate_password_hash(password)).save_to_db() except: return jsonify({'error': 'An error occurred saving the user to the database'}), 500 return jsonify({'message': 'User registered successfully'}), 201 That piece of code will get the username and password from the request's form data, and create a new User object (presumably defined elsewhere), and save it to the database. The code assumes the User object takes in its __init__ method a username and password, and that it has a method to save itself to a database. For a more complete example, check this link: P.S. If you are interested in learning much more about Flask and Python, sign up to our mailing list below!
https://blog.tecladocode.com/learn-python-password-encryption-with-flask/
CC-MAIN-2019-26
refinedweb
531
62.58
I was following this tutorial and finally wanted to test whole code: #include <iostream> #include <winsock2.h> #include <errno)) == -1) { std::cout<<"Failed to establish connection with server\r\n"<<WSAGetLastError();; }However, I'm getting error 10061 all the time, which means connection refused. I'm totally confused with this winsock. All tutorials are either obsolete, only unix or incomplete... I tried switching off my firewall and anti vir but that didn't help. Does anyone know why can't I connect to my localhost? I would be really garteful for help! And please don't hesitate to provide any advice as I'm really totally inexperienced with network programming. Edited by savail, 14 August 2012 - 03:49 AM.
http://www.gamedev.net/topic/629606-winsock-connection-refused-to-localhost/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024
CC-MAIN-2016-36
refinedweb
119
51.04
The there are a few more things, such as a new built-in code cleanup profile for applying code style settings. Let’s have a look, shall we? DOWNLOAD ReSharper 2019.1 EAP Export EditorConfig from ReSharper code style settings Many teams are using EditorConfig to customize code style settings across IDEs and editors. From the ReSharper settings, under Code Editing | General Formatter Style, we can now export ReSharper’s code style settings to EditorConfig. We can export cross-editor options, as well as properties that are only supported by ReSharper/Rider. Combined with the Format Selection | Configure… context action (Alt+Enter), we can visually update formatting rules and then export them as EditorConfig. Typing assist for unindent on backspace To help with indenting/unindenting code, we’ve added a new typing assist when pressing Backspace. Instead of moving the caret back one position at a time, pressing Backspace returns the caret to the proper indent position. We can change the behavior of this typing assist in ReSharper’s settings (under Environment | Editor | Editor Behavior): The following options are available: - To proper indent position (default) – When the caret is to the right of the proper indent, Backspace deletes the space to the proper indent. Otherwise, Backspace deletes the whole indent and moves to the previous line. This means that maximum 2 Backspaces are required to move to the previous line. - To nearest indent position – Backspace moves to the previous indent position. - Disabled – Speaks for itself, doesn’t it? 😉 Analyze/optimize references for SDK projects Code bases evolve. Over time, we add new references and install NuGet packages into our projects. Removing those that are not in use is often more difficult. ReSharper 2019.1 comes with improvements to analyzing and optimizing references in our projects! Next to analyzing project and assembly references, ReSharper now also checks for unused package references in SDK projects! Using the Optimize References… context menu for a project (Ctrl+Alt+Y), we can analyze and optimize references. When our project does not contain any code that uses a given reference, it will show as unused. We can easily uninstall unused packages and keep our project’s dependency tree clean! The Mark reference as used at runtime context menu can be used to inform ReSharper of references that are used implicitly (only at runtime). Even if there are no direct code dependencies on them, ReSharper will mark these references as being in use. Other updates to formatting & code cleanup In ReSharper 2018.3, we made customizing code style easier and faster, by detecting formatting and naming settings from existing code. In 2019.1, this detection now runs in the background, allowing you to continue coding while detection is running. We have added a new option Place ‘System.*’ and ‘Windows.*’ namespaces first when sorting ‘using’ directives (find it in the ReSharper settings, under Code Editing | C# | Code Style | Reference Qualification and ‘using’ Directives). By default, ReSharper and Rider will place these namespaces first when ordering namespaces. When this option is disabled, namespaces will be ordered alphabetically. Namespace ordering is now also compatible with Visual Studio and StyleCop. Another new formatting option helps inserting blank lines before or after a case <x>: statement (under Code Editing | C# | Formatting Style | Blank Lines). Want to update your code to match code styles? A new built-in code cleanup (Ctrl+E, C) profile is now available for that: Reformat & Apply code styles. Give ReSharper 2019.1 EAP a go, or try these features in Rider 2019.1 EAP! We’d love to hear your feedback. Does the IIS Express feature work with Compound configurations ? I’m trying to launch several apps through IIS express but I’m having issues… When do you anticipate that we will stop seeing the message about depreciated APIs and have resharper load async, since Visual Studio 2019 will be launching next week? The above comment is in relation to 2019.3 still showing a message even though your release notes suggest async package loading should be working That warning should be gone with 2019.1 EAP 3. Can you double check you are on that version (or newer) via the Extensions | ReSharper | Help | About ReSharper…. menu? Yes I can confirm that it still shows the warning messages: “One or more of your installed extensions will not be compatible with a future Visual Studio update” when I click manage performance, Resharper 2019.1 EAP 3 is listed under Depreciated APIs. I’ve installed it on 2 machines with the same results JetBrains Resharper Ultimate 2019.1 EAP3 Checked built 2019-03-26 Visual Studio 2019 Rc4 (version 16.0.28721.148 ) Thanks! Just checked internally, there are a couple more that are being tackled. I’m already looking forward to have “Typing assist for unindent on backspace” in the public release of ReSharper! But one thing is not so clear to me: am I right that “Analyze/optimize references for SDK projects” scans for unused references and in case of anything found, it also removes the NuGet package from packages.config resp. CSPROJ file, whereas the “old” versions of ReSharper only remove the assembly reference but not the package? That’s correct i’m still waiting to add a renaming feature for vs project like rider. If you can sort System.* und Windows.* namespaces to the top, then you also should add Microsoft.* the that list. Or, better. Make the list editable. So customer can support third party stuff also in there.
https://blog.jetbrains.com/dotnet/2019/03/28/export-editorconfig-code-style-optimize-references-sdk-projects-resharper-2019-1-eap-updates/?replytocom=552863
CC-MAIN-2019-47
refinedweb
914
56.15
SHFormatDateTime function [SHFormatDateTime is available for use in the operating systems specified in the Requirements section. It may be altered or unavailable in subsequent versions.] Produces a string representation of a time specified as a FILETIME structure. Syntax Parameters - pft [in] Type: const FILETIME UNALIGNED* A pointer to the FILETIME structure whose time is to be converted to a string. - pdwFlags [in, out, optional] Type: DWORD* A pointer to a DWORD value that contains bitwise flags that specify the date and time format. When you call the function, you can combine zero or more of the following flags, with exceptions as noted. You can also set this parameter to NULL, in which case the function assumes that the FDTF_DEFAULT flag is set. FDTF_SHORTTIME (0x00000001) 0x00000001. Formats the time of day as specified by the Regional and Language Options application in Control Panel, but without seconds. This flag cannot be combined with FDTF_LONGTIME. FDTF_SHORTDATE (0x00000002) 0x00000002. Formats the date as specified by the short date format in the Regional and Language Options application in Control Panel. This flag cannot be combined with FDTF_LONGDATE. - Equivalent to FDTF_SHORTDATE | FDTF_SHORTTIME. FDTF_LONGDATE (0x00000004) 0x00000004. Formats the date as specified by the long date format in the Regional and Language Options application in Control Panel. This flag cannot be combined with FDTF_SHORTDATE. FDTF_LONGTIME (0x00000008) 0x00000008. Formats the time of day as specified by the Regional and Language Options application in Control Panel, including seconds. This flag cannot be combined with FDTF_SHORTTIME. FDTF_RELATIVE (0x00000010) 0x00000010. If the FDTF_LONGDATE flag is set and the date in the FILETIME structure is the same date that SHFormatDateTime is called, then the day of the week (if present) is changed to "Today". If the date in the structure is the previous day, then the day of the week (if present) is changed to "Yesterday". FDTF_LTRDATE (0x00000100) 0x00000100. Adds marks for left-to-right reading layout. This flag cannot be combined with FDTF_RTLDATE. FDTF_RTLDATE (0x00000200) 0x00000200. Adds marks for right-to-left reading layout. This flag cannot be combined with FDTF_LTRDATE. FDTF_NOAUTOREADINGORDER (0x00000400) 0x00000400. No reading order marks are inserted. Normally, in the absence of the FDTF_LTRDATE or FDTF_RTLDATE flag, SHFormatDateTime determines the reading order from the user's default locale, inserts reading order marks, and updates the pdwFlags output value appropriately. This flag prevents that process from occurring. It is used most commonly by legacy callers of SHFormatDateTime. This flag cannot be combined with FDTF_RTLDATE or FDTF_LTRDATE. Windows Server 2003 and Windows XP: This value is not available. When the function returns, the DWORD value pointed to by this parameter can contain zero or more of the following flags. FDTF_SHORTTIME (0x00000001) The short time was successfully formatted. FDTF_SHORTDATE (0x00000002) The short date was successfully formatted. FDTF_LONGDATE (0x00000004) The long date was successfully formatted. FDTF_LONGTIME (0x00000008) The long time was successfully formatted. FDTF_RELATIVE (0x00000010) Relative notation was used for the date. - pszBuf [out] Type: LPTSTR A pointer to a buffer that receives the formatted date and time. The buffer must be large enough to contain the number of TCHAR characters specified by the cchBuf parameter, including a terminating null character. - cchBuf Type: UINT The number of TCHARs that can be contained by the buffer pointed to by pszBuf. Return value Type: int Returns the number of TCHARs written to the buffer, including the terminating null character. On failure, this value is 0. Examples The following code example demonstrates the use of SHFormatDateTime. #include <windows.h> #include <shlwapi.h> #include <stdio.h> #include <tchar.h> void sample(LPCTSTR pszName, DWORD dwFlags) { FILETIME ft; GetSystemTimeAsFileTime(&ft); TCHAR szBuf[256]; int cch = SHFormatDateTime(&ft, &dwFlags, szBuf, 256); _tprintf(TEXT("%s\n\t%s\n"), pszName, cch ? szBuf : TEXT("<failed>")); } #define trysample(f) sample(TEXT(#f), f) int __cdecl main() { trysample(FDTF_DEFAULT); trysample(FDTF_LONGDATE | FDTF_SHORTTIME); trysample(FDTF_LONGDATE | FDTF_LONGTIME | FDTF_RELATIVE); return 0; } ..................... A typical run of this sample might produce the following output for these flags: FDTF_DEFAULT 5/13/2059 4:36 AM FDTF_LONGDATE | FDTF_SHORTTIME Tuesday, May 13, 2059, 4:36 AM FDTF_LONGDATE | FDTF_LONGTIME | FDTF_RELATIVE Today, May 13, 2059, 4:36:06 AM Requirements See also
https://msdn.microsoft.com/en-us/library/bb773833(v=vs.85).aspx
CC-MAIN-2015-11
refinedweb
679
50.84
Pop Searches: photoshop office 2007 PC Security You are here: Brothersoft.com > Windows > Internet > News Readers > Advertisement Advertisement view larger (1) Advertisement import text file | hsbc.co.uk.com | wallpaper uk | casino uk | dts logo free | google uk | avast real time | bejeweled 2 for | format factory ver.1.9 | ashampoo disk cleanup | dogtra-uk.co.uk-ipod-download Please be aware that Brothersoft do not supply any crack, patches, serial numbers or keygen for UK news,and please consult directly with program authors for any problem with UK news. bitcomet for macbook | kundan designs wallpapers | wpd to doc freeware | msn uk | ebay uk | frs talking calculator 1.3.1 | install rpm with smart | data world of warcraft 2.4.3 | pdf reader .jad | yessim tools v1.2 | adobe pdf reader blackberry | calculus lab matlab student | aol uk | news breaking news | ishares uk | alpena business intelligence | uk skyscraper news | uk design | samsung m110s galaxy s firmware | uk tv | coles logo gif | yahoo uk | sis 2 adb | sky news uk in News Readers
http://www.brothersoft.com/uk-news-170459.html
CC-MAIN-2018-22
refinedweb
171
55.84
I created a sample ASP.NET MVC application that I plan to post at the website. While the application was being code reviewed by the ASP.NET MVC Feature team, a surprising objection surfaced. The application is extremely simple. It contains a view that renders a list of database records. Next to each record, there is an Edit link and a Delete link (see Figure 1). Pretty standard stuff. Or, so I thought… Figure 1 – A Grid of database records Here’s the objection. You should not use a link for deleting a record. Using a Delete link opens up a security hole. The Security Objection In theory, someone could send an email to you that contains an image. The image could be embedded in the message with the following tag: <img src=”” _fcksavedurl=”””” /> Notice that the src attribute points at the Delete() method of the Home controller class. Opening the email (and allowing images in your email client) will delete record 23 without warning. This is bad. This is a security hole. I had come across this security concern in the past, but had not given it much thought. Originally, Microsoft enabled you to invoke ASMX Web Services by performing a HTTP GET request. In .NET Framework 1.1, HTTP GET requests were disabled by default (You can re-enable HTTP GET requests in the Web.config file). This change in behavior was made to prevent these types of HTTP GET security attacks. The REST Objection. For example, you don’t want a search engine to delete all of the records in your application while crawling your website. Performing an HTTP GET should have no lasting effect on your application. The proper HTTP operation to perform, when deleting a record, is an HTTP DELETE. The HTTP protocol supports the following HTTP operations: · OPTIONS – Returns information about the communication options available (idempotent). · GET – Returns whatever information is identified by the request (idempotent). · HEAD – Performs the same operation as GET without returning the message body (idempotent). · POST – Posts new information or updates existing information (not idempotent). · PUT – Posts new information or updates existing information (idempotent). · DELETE – Deletes information (idempotent). · TRACE – Performs a message loop back (idempotent). · CONNECT – Used for SSL tunneling. These operations are defined as part of the HTTP 1.1 standard which you can read about at. Notice that the description of an HTTP POST and HTTP PUT are identical. To understand the difference between a POST and a PUT, you need to understand what it means for an operation to be idempotent. An idempotent operation is an operation that has the same outcome no matter how many times that it is performed. For example, if you perform a POST operation to create a new database record, then you can create a new database record every time that you perform the POST. A POST operation is not idempotent because it can have a different effect on your application each time the operation is performed. If, on the other hand, you perform a PUT operation, then the very same database record must be created each time you perform the PUT. A PUT operation is idempotent because performing a PUT operation a thousand times has the same effect as performing the operation one time. Notice that an HTTP DELETE is also idempotent. Performing the same HTTP DELETE request multiple times should have the very same effect on your application each time the request is made. For example, the request /Home/Delete/23 should delete database record 23, and no other database record, regardless of how many times the request is made. HTML Supports Only GET and POST So, the proper thing to do when deleting a database record is to perform an HTTP DELETE operation. Performing an HTTP DELETE does not open a security hole and it does not violate REST principles. Unfortunately, standard HTML does not support HTTP operations other than GET and POST. A link always performs a GET and a form can perform either a GET or POST. HTML does not support other types of HTTP operations. According to the HTML 3.1 specification, the HTML FORM tag only supports GET and POST. It does not support other HTTP operations such as DELETE or PUT. See. Furthermore, Internet Explorer only supports GET and POST (see). Performing Ajax Deletes If you are willing to go beyond standard HTML, you can perform HTTP DELETE operations by taking advantage of AJAX. The XmlHttpRequest object supports any of the HTTP operations. Therefore, if you are willing to make your application depend on JavaScript, then you can do everything the right way. The Home controller in Listing 1 contains an Index() and Delete() method. The Index() method returns all of the movies from the Movies database and the Delete() method deletes a particular movie with a particular Id (this controller uses the Entity Framework). Listing 1 – ControllersHomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Tip46.Models; namespace Tip46.Controllers { [HandleError] public class HomeController : Controller { private MoviesDBEntities _entities = new MoviesDBEntities(); public ActionResult Index() { ViewData.Model = _entities.MovieSet.ToList(); return View(); } [AcceptVerbs(HttpVerbs.Delete)] public ActionResult Delete(int id) { var movieToDelete = (from m in _entities.MovieSet where m.Id == id select m).FirstOrDefault(); _entities.DeleteObject(movieToDelete); _entities.SaveChanges(); return RedirectToAction("Index"); } } } Notice that the Delete() method is decorated with an AcceptVerbs attribute. The Delete() method can only be invoked by an HTTP DELETE operation. The Index view in Listing 2 displays the movies from the Movies database table within an HTML table. A Delete link is rendered next to each movie record (see Figure 2). Listing 2 – ViewsHomeIndex.aspx <%@ Page <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script type="text/javascript"> function deleteRecord(recordId) { // Perform delete varDelete</a> <%-- GET Delete: Security Hole <%= Html.ActionLink("Delete", "Delete", new { id=item.Id })%>--%> </td> <td> <%= Html.Encode(item.Id) %> </td> <td> <%= Html.Encode(item.Title) %> </td> <td> <%= Html.Encode(item.Director) %> </td> <td> <%= Html.Encode(item.DateReleased) %> </td> </tr> <% } %> </table> </asp:Content> Deletes are performed with an Ajax call. The Delete link invokes the JavaScript deleteRecord() function. This function uses the Microsoft ASP.NET AJAX WebRequest object to perform an Ajax call. The WebRequest performs an HTTP DELETE operation. After the DELETE operation completes, the JavaScript deleteCompleted method is called. This method reloads the current page (a more elegant approach here would be to use the new ASP.NET AJAX Client Template functionality coming with the next version of ASP.NET AJAX. That way, you could just update the grid without reloading the entire page). Figure 2 – The Index view But, I Don’t Want to Depend on JavaScript Many developers do not want their websites to depend on JavaScript. In other words, they want their websites to continue to work with JavaScript turned off. There are somewhat legitimate reasons for this requirement. Not all mobile devices support JavaScript (although most do). And, there are accessibility concerns about JavaScript (although Aria should fix these accessibility problems). If you want your website to work with JavaScript disabled then you can’t perform an HTTP DELETE when deleting a database record. Instead, you should perform an HTTP POST. An HTTP POST does not expose the same security hole as an HTTP GET operation. You can use the AcceptVerbs attribute to prevent a controller action from being invoked unless it is invoked with an HTTP POST operation. So, the Delete() action would look like this: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id) { var movieToDelete = (from m in _entities.MovieSet where m.Id == id select m).FirstOrDefault(); _entities.DeleteObject(movieToDelete); _entities.SaveChanges(); return RedirectToAction("Index"); } Unfortunately, the only way to perform an HTTP POST with standard HTML is to use a <form> tag. Furthermore, you must use an <input type=”submit”>, <input type=”image”>, or <input type=”button”> tag to create a button for deleting a record. There is no such thing as an <input type=”link”> tag. That’s a shame, because links look better than buttons. HTML should not tie appearance to behavior, but it does. You should be able to make a Delete link to delete a record. The best option here is to use the <input type=”image”> tag. That way, you can make the Delete and Edit links look the same when displaying a grid of database records. Because I did not want to make my sample application depend on JavaScript, this is the approach that I am taking in the sample application. The non-JavaScript dependent Index view is contained in Listing 3. Listing 3 – ViewsHomeIndex.aspx (no JavaScript) <%@ Page <h2>Index</h2> <table> <% foreach (var item in Model) { %> <tr> <td> <a href='<%= Url.Action("Edit", "Home", new { id = item.Id })%>'><img src="Content/Edit.png" alt="edit" border="0" /></a> </td> <td> <% using (Html.BeginForm("Delete", "Home", new { id = item.Id })) { %> <input type="image" src="Content/Delete.png" /> <% } %> </td> <td> <%= Html.Encode(item.Id) %> </td> <td> <%= Html.Encode(item.Title) %> </td> <td> <%= Html.Encode(item.Director) %> </td> <td> <%= Html.Encode(item.DateReleased) %> </td> </tr> <% } %> </table> <p> <%= Html.ActionLink("Create New", "Create") %> </p> </asp:Content> I got the images for the Edit and Delete links from the Visual Studio image library (see Figure 3). You have these set of images on your hard drive at the following location: C:Program FilesMicrosoft Visual Studio 9.0Common7VS2008ImageLibrary Figure 3 – Using Images for Edit and To get the images to align correctly, I added a vertical-align style to the table cells. I used the following style rules: table { border-collapse:collapse; } td { vertical-align:top; padding:10px; border-bottom: solid 1px black; } Conclusion Don’t use Delete links to delete database records. Potentially, someone could perform a GET request and perform a delete without your consent or control. The best option is to use JavaScript to perform an HTTP DELETE operation. Using JavaScript enables you to avoid the security hole. Using JavaScript also enables you to respect the semantics of the HTTP protocol. If you don’t want your application to depend on JavaScript, the second best option is to perform an HTTP POST instead of an HTTP DELETE. Performing a POST operation requires you to use an HTML form. This can be ugly. However, you can improve the appearance of a form button by using an <input type=”image”> tag and adding Cascading Style Sheet styling. What about the [Authorize] attribute? Hey Stephen, good to see you posting again. I agree for the most part but there are clear ways to get around this. 1) Only accept HTTP Post. 2) Check referring URL (extend attributes if you have to for DRY) 3) Anti-forgery tokens already included in ASP.NET MVC. This is definitely a good post though. People used to WebForms are going to have to learn how classic web development is handled for security reasons and this is a good example. Keep up the good work! I learned allot about HTTP, that I should have known already. Thanks. Stephen, Thanks a ton for this tip, and the others you’ve posted…they have all been a great help. This post got me thinking…if I wanted to get around this security gate I would simply embed a url that calls a page with a JavaScript onload function to POST the delete command. I’m just thinking out loud here but it seems there must be a good way to verify the POST is valid. …Maybe check the “Refering URL” to make sure it came from the application. …or use some sort of security token …or maybe even have the user re-validate their credentials if the data is really critical. What would you suggest? opps…I guess I took too long to reply after reading the post 🙂 (multi-tasking again) Seems my thoughts were already spoken. Cheers! And keep up the great work! -Phil vBulletin uses delete links but after clicking on the delete link, you need to retype your password. If you had a second page where you need to click on something like confirm that you want to delete the items or a page to reauthenticate the password, this attack will get stopped. @idelator, Good point. Maybe the best solution is to use JavaScript HTTP DELETE for uplevel browsers and an extra delete confirm page with an HTTP POST for downlevel browsers. To prevent search robot deletions I’ve used a simple Javascript approach which removes the actual URL from the link : Which can be combined with a confirm prompt. I agree with the above posters that discussing this sort of common misuse of GET in the context of a security hole, only to suggest replacing it with another CSRF security hole is not the best choice. I also think making this change to please RESTifarians is a bit of a waste, since you have much larger problems to fix first if you want to please them (why are you DELETEing the 23rd /Delete resource? Shouldn’t that remove records of the 23rd deletion?). I think the non-safeness of this operation, and why allowing a user to perform something non-safe through GET is bad, is a much stronger argument against it. Remember when GWA came out and accidentally taught the word idempotentic to so much of the web, because of this very sort of delete link? Which leads nicely into why it’s very much in the HTML designer’s intention to not provide a link-style form submission. Because they imagine that the user will learn that blue underlined text is safe, and can be clicked on with no danger, and a button (or a graphical button-like image) is not safe, and should be carefully considered before clicking. Of course too many web app developers don’t follow this idea so very few users have learned an instinct of blue-underline=safe, but it’s still a good idea to follow when designing your own app. Browsers’ tabs are a good pragmatic example of how things get easier if you make sure links are always GETs and GETs are always safe. Because you can easily open links with a middle-click, but not buttons. What happens in your AJAX version if I middle-click on a DELETE link? Does it just confusingly do nothing, or does it delete it in the background and leave me with a no-longer valid page state in my first tab (item #23 represented as still existing)? In the example of it being a button, that question is removed, since I can’t middle-click on a delete button. Oh, and since you mention idempotency, and since I just saw another post on it today, I thought I’d share it with you. It’s OK for GET Requests to Update the Database is a good reminder not to get too locked into the idea of GET=SELECT and nothing else. Ah, the comments allowed HTML… I tried to demonstrate setting the href attribute of a link on the onclick handler. .. href=”#” onclick=”this.href=’Delete/23′” I agree with jlharper. Your tips actually does not solve anything, just try to replace GET by DELETE or POST command. What happen if I write a small script that automatically uses POST or DELETE because your resource ID is simple to guess? I agree with Doug which is using [Authorize]. Most of the time we will not allow anybody to delete some records without authorization do you think. “a” tags shouldn’t be used for deletes. Posting Forms should be used for deletes. (If the delete is successful then do a redirect, otherwise return error). The javascript ‘delete’ method is just going to far imho, when there is suitable html for this situation. You can always use CSS (if you must) to style the submit button so it looks like a link… Useful stuff. But regardless of using HTTP Delete with ajax or post back; I think one should always [Authorize] the request. No body wants to delete something in their apps by unauthorized person. i think thats is the best way to address the issue. Hi all, About [Authorise], this will work in this cases: a) if you are viewing emails from some email client eg Thunderbird. b) if you set in config to keep authorization cookie per browser session (I mean to use not persistent cookies). In this case it will work only when you was visiting your site in previous session and there are no auth cookie. In other cases this authorization cookie will be sent if exists. So if you receive a letter with such image link and will read it in browser which has authorization cookie – you’ll delete the item. So please use Post or Delete request if you want to make this safe. Thanks Stephen, very interesting and useful post! =) Best regards. Hi Stephen, IMHO, Use HTTP Post with AntiForgeryToken helper method. I just looked up the AntiForgeryToken helper Shiju suggested, and I want to second his suggestion. AntiForgeryToken is precisely the ASP.NET MVC feature intended to combat these CSRF attacks. It’s an implementation of the standard method of sticking a unique token in a cookie and a form and checking that the cookie and form value still match when the form gets submitted, that is, that the form the user has submitted is a form that the web app itself created — something merely checking a user has an authentication cookie won’t help with. I think the fact that this post veers off into discussion of proper mapping of HTTP verbs to actions covers up the more important fact that the security hole brought up is of the CSRF class, and that no matter what HTTP verb is used, CSRF must be protected against. In every input-accepting control of your application. It is still probably the most unrecognized, widespread security hole in web applications today, now that knowledge of XSS is starting to spread. On the other hand, you do have to note that AntiForgeryToken requires the use of POST, not GET, which leads us back to the discussion of the fact that it’s bad form to use GET for anything dangerous enough that you want to protect from a CSRF attack anyway. Which leads to the reason it’s bad form, which leads to discussion of proper mapping of HTTP verbs to actions. Oh well 🙂 Have I missed something or isn’t this just a case of making sure the auth’d user has the rights to delete the record? Interesting post, thanks. Though I do wonder how often it would even be appropriate to implement it. For instance, in my mind, I can’t think of any delete abilities that would be publically available on a website. They’re always secured and normally tied to an account. I’m sure there’s a case I’m not thinking of, and for that I’m sure it’s appropriate, but I can’t think of anywhere in any app I’ve developed where the extra work involved would balance against the benefit. That img tag in the last html code example needs an alt attribute. In my blog I’ve written a whole series on supporting a RESTful web service with MVC and ASP.Net. To help with overloading of POST (to provide support for DELETE and PUT) I created an ActionMethodSelectorAttribute that extended AcceptVerbsAttribute to support overloaded POST. See the Overloading Post entry: shouldersofgiants.co.uk/…/…erloading-POST.aspx As somebody already mentioned, you didn’t actually resolve anything other than not allowing a search engine to follow the delete links. All the security checking should be always in the controller or the layer that handles the rules. Even if you might end up with duplications (like having a second check whether the delete links should be displayed or not in the UI), security is not something to be implemented in html. Imho GET / POST / DELETE / PUT or whatever you may use should have absolutely no impact on your application rules. This… …is NOT a RESTful URL. It has a VERB in it– REST is about NOUNS, remember? It’s a little lame, but a little CSS styling and you can have a submit button look like a link… :/ I’m just starting to look at MVC, so I found this discussion really interesting. However, I would point out (I don’t think anyone already posted this) that there is already a good discussion posted at this link. blog.codeville.net/…/#comment-2171 I found this link directly on the MVC codeplex site here…/View.aspx however this article is dated from September and implies that the AntiForgeryToken is in the Futures section of MVC. Is that still the case or has it moved to the Core. I have to agree w/ some of the other comments here. GET shouldn’t be used for deletes because it has a side-effect. HTML guidelines tell you this. You don’t want to have linkable, favoritable, urls that cause side-effects. But it’s still easy to fake a form POST, so the security hole remains. Use the antirequestforgerytoken, the authorize attribute, and other means to protect your application. Another thing I’d like to call out is your use of obtrusive javascript. You have quite a following on this blog and you really shouldn’t be advocating code that looks like this: ..a href=’javascript:void(0)’ onclick=’doSomething();… First, javascript in the HREF attribute is a complete no-no, it should actually point to something (or “#”). Second, attaching behavior in the onclick attribute mixes your concerns. You should be attaching this behavior with javascript in the HEAD tag. Something like this (jQuery): $(function() { $(‘a.some_class_denoting_behavior’).click( function() { doSomething(); return false; }); }); the return false prevents the browser from actually trying to visit the link. I recommend reading up on unobtrusive javascript, and if you’re serious, pick up DOM Scripting by Jeremy Keith. It’s a great book. It talks about progressive enhancement, unobtrusive scripting, and complete separation of behavior from content. Hope this helps. good About being an authorized user, this is still open to the delete attack mentioned. Say you are an authorized user and you log into a site in one tab. Now say you open an email in Gmail in another tab. The attack here will work since you are logged into the site. It’s worse if you implement a “remember me” feature because then a user can close their browser and the attack will still work. Hi, Your article is nice.Thanks for that. I have the following questions. 1. How can we protect our Aplication from Javascript attacks ? 2. If we are using JS then we have to expose our links to delete command. Same applies even if we need to get some details from our website. Why this is like that ? Do we have alternative ways to achiev this in JS ? Thanks, Thani I think alot of you are missing the point of the article. While i understand that it is easy to bypass the provided solution by issueing a POST request. The fix addresses the issue that if a user adds an image (src pointing to a delete action) to an email and the person receiving that email has already been authorized then the delete would still take place. I guess the ideal solution would be a combination or POST and authorisation although if you really wanted to achieve this with GET then i would implement some form of confirmation. I disagree Lee; that is the point of the article, but we’re pointing out it’s the wrong point. While this fix (switch from GET to POST) addresses the one, specific problem of a forged GET request (in the example, an image), it still leaves it open to a forged POST request, which is not any harder to forge. It is not difficult to get a user to click a link, and that’s all that’s necessary to forge a POST request. You also just clicked the submit button on this comment form — and probably clicked at least 10 >input type=”button”<s today on web pages without thinking about it, and without viewing the source to see exactly which URL the form was going to submit to. If one of those buttons told your browser / email client to send a POST request to your app, you would be unaware of what was being sent, where, until the delete URL of your app has redirected you to the index page of your app, post-delete. And then consider the possibility of a page with both a forged form and some onload javascript which automatically submits the form the second you visit the page. All that would be required then to delete your database would be a single click on a link, pointing at some outside web site, and next thing you know you’re staring at your web app, post-delete. Authentication does not solve this problem. If you are authenticated with your app, your browser is authenticated with your app, and the fake form is going to be authenticated with your app when it tells it that you have just asked for the deletion of the database or transfer of money. Aggressive timeouts and reminders to always logout may catch some CSRF attacks at a login screen, but do nothing to when your app is open in the background in another window or another tab, or a user just closed the tab but is still within the timeout period. Yes, your email client may have a different cookie jar from your browser and so not be authenticated with your app, but protection only for an email client / second browser is not enough of a solution, when something called the world wide web exists and your users are going to be visiting it with the same browser they use for your app. And if you add a confirmation step, what stops the attacker from just pointing at the URL that indicates confirmation? CSRF is a security hole in your apps right now, if you aren’t taking steps to prevent it on every single form and in every single input-accepting or action-taking URL in your app. The easiest, most common, defense is a random per-user or per-formview token, stuck in both a cookie and as an input to a form, and a check on the form’s submission that the token was submitted along with the form to make sure the form was generated by your app (since only your app will have permission to read or write the cookie). ASP.NET MVC calls its implementation of this pattern AntiForgeryToken. LOL, I never can keep the names of less-than and greater-than straight! I meant <input type=”button”> (and won’t it be embarrassing if this comes out inverted also!) jlharper, Many thanks for your extensive comments on this issue, they were very informative. Of course the confirmation page could be where a POST is required. Better still, if your models aren’t too deeply entrenched, you could skip the actual record deletion and use a binary field, i.e. never use a warning when you mean undo. My initial thought is that this post creates more problems than it solves. From what I remember, HTTP DELETE and PUT commands existed to support file resources on a remote server. Similiar to commands used by the FTP protocol. I have never seen any web application utilize either of these two methods for any reason. Additionally, in default IIS installations the verbs accepted for most filetypes do not include DELETE and PUT. The most common (as I have observed in IIS on XP) are GET, HEAD, POST, and DEBUG. I believe there is a great reason for this: the other methods were never intended for use with the way the web works today. hi, How to Configure Asp.net MVC Beta + IIS 7.0 + HTTPS with PUT and DELETE verbs Looks like AntiForgeryToken is now part of ASP.NET MVC (as of RC1). A can be an alternative too so it can be styled with CSS too. Take a look at this article for more information particletree.com/…/rediscovering-the-button-e… button type=”submit” seems I found a bug in the parser 🙂 Here is the link to the article particletree.com/…/rediscovering-the-button-e… I don’t want application to depend on JavaScript. The best option is to perform an HTTP POST instead of an HTTP DELETE. Performing a POST need to use an HTML form. This can be ugly. intrinsically GET requests don’t create security holes. privileged operations require authorization. this is not just the delete operation, there are many operations that require the client to go through an AA phase. just as a registered user of an online trading site cannot view records of another user (generally a get operation BTW) there is no reason to assume that delete would no provide similar restrictions on the application level. Nice Post! Thanks for the advice.. Great Information, this will be very helpful to me. I admit, I have not been on this webpage in a long time… however it was another joy to see It is such an important topic and ignored by so many, even professionals. THanks for the great article. it’s been a while since i visited your blog and it’s great that someone wrote about it finally. So let me get this straight? If I have a link that says delete and by clicking on it then it should delete the database info I am trying to delete, and yet that causes a security risk, what is the best 2.0 way to resolve this problem. Now, the problem is only a problem when a site is public, right? This was very informative and detailed. Thanks a lot for the info!! thanks for script, very useful f Very good example I am on my second pair! Sometimes I wear them just for the peace and quiet – no IPod, no movie, no screaming children, no seatmate yammering. What’s the price of peace and quiet? Priceless!online associate degrees | business school Beats by Dr. Dre. They are a bit expensive, but totally worth it. Online Education degree | fire school This is good one to provide the better learning of ASP.NET. Transparency and access to information is should be a golden standard we aim for here in the UK. Let’s all hope Tim and Digital Engagement go some way of getting there.Exploratory Essay Regards, Can u compare jsp and asp.net over security issues, fastness, cost effective? Which is best to avoid hacking? サイト売買 求人 is wonderful. トイレつまり is wonderful. 外国商標 is wonderful. 電話代行 東京. 助成金 横浜 is wonderful. 不眠症 治療 is wonderful. ディズニーランド is wonderful. 我孫子市 一戸建て is wonderful. 浦和 不動産 is wonderful. 業務用エアコン is wonderful. 照明 インテリア is wonderful. 生い立ちビデオ is wonderful. 相続税対策 is wonderful. 歯並び is wonderful. ゴルフ会員権 is wonderful. 上尾 不動産 is wonderful. 幼児 習い事 is wonderful. 帰化申請 中古医療機器 買取. .thanks for sharing your views.. Free online games. . Regards, I have always had problems with ajax on my work out plans blog. f you are willing to go beyond standard HTML, you can perform HTTP DELETE operations by taking advantage of AJAX but i have a problem with Ajex. Wedding Dresses Wedding Flowers Yes, better don’t delete the links manually. cheap car insurance. I prefer to make my blog no follow or break the links so that they no longer work. the coding is great and can any one one suggest ho to protect the scripts? I just heard about this. Never knew before, but I guess there are many others who also don’t realize the holes. Thank you.. I hope my bankruptcy discharge papers website hasn’t deleted much. this some great information. You do not want security holes. wedding tips free wedding information inexpensive wedding ideas Very interesting article. Many thanks for the share of the information. Thanks, Andreas I agree with AD, good discussion Compare Credit Cards, Credit Card Comparison Nice article. The code works fine and is a good starting point for me making a custom module. Thanks for the module… Cleared up quite a few things and learned something along the way. Thanks. weight loss pills for women Appetite suppressant pills Hide my IP free trial thanks A LOT. Great post thanks!SN Such an excellent post, thank you for sharing Why does my ASP.NET application work on my local machine but not when I upload it to the server? Thanks for explaining this pretty neat application, definitely helps with the screenshots to understand the code, thanks! I agree with the others regarding using GET for deletes due to the side effects, I have had a few problems with this in the past. Great article though and interesting stuff. Thanks for explaining this, the code works fine for me, I’m going to be starting a custom module this week. Yes, better don’t delete the links manually. Essay| Essays| Essay Writing| Essay Help| Custom Essay| Developers can easily leverage the Model-View-Controller pattern in ASP.NET Buy Essay| Online Essay| Essay Writing Service| Essay Service| Essay Topics| | It’s lucky to know this, if it is really true. Companies tend not to realize when they create security holes from day-to-day operation. I work for a reputable Concrete Sealer company and even sometimes it is hard to keep the optimal security standards. Adios. Nice article.The code works fine and is a good starting point for me making a custom module.Thanks for the module… HI, Can I download DLC for guitar hero world tour wii without an internet connection ,via the computer? I would have to say that using the DELETE verb might be more of a headache in bigger corporations, since by default, IIS only allows the following verbs : GET, HEAD, POST, DEBUG . In the companies I’ve worked at, the developers don’t control the servers, so the developers would have to notify the IT team to allow the DELETE verb, and then if you have a server farm, this would have to be added to all the servers. Not to mention, if you use URLScan, by default it also doesn’t allow the DELETE verb. I’d say JavaScript should be used for Deletes, since it’s a good idea to have a confirmation dialog asking if you’re really sure you want to delete, and then which would create an HTTP POST. There are specific techniques and exercises you can employ to help prevent premature ejaculation. Fortunately , medical science in addition has developed a bewildering array of early ejaculation solutions. We’ve analyzed the formulas, polled our audience, totaled the results ( and read virtually 8000 emails ) to discover the top-recommended early ejaculation products. All so you can get help.Men who have continuing early ejaculation troubles don’t want to do exercises, use funny positions or create excuses. They need a cure and they need it immediately.A early ejaculation cure has to work fast and it has got to be 100 percent trustworthy. Not just that, but it has got to be something that doesn’t ruin the mood. control premature ejaculation ejaculation trainer ejaculation master prejaculation premature ejaculation treatmentVGF
http://stephenwalther.com/archive/2009/01/21/asp-net-mvc-tip-46-ndash-donrsquot-use-delete-links-because
CC-MAIN-2021-04
refinedweb
5,927
65.22
boost/beast/zlib/zlib.hpp // // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at) // // Official repository: // // This is a derivative work based on Zlib, copyright below: /* Comments) 1950 to 1952 in the files (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef BOOST_BEAST_ZLIB_ZLIB_HPP #define BOOST_BEAST_ZLIB_ZLIB_HPP #include <boost/beast/core/detail/config.hpp> #include <cstdint> #include <cstdlib> namespace boost { namespace beast { namespace zlib { #if !defined(__MACTYPES__) using Byte = unsigned char; // 8 bits #endif using uInt = unsigned int; // 16 bits or more /* Possible values of the data_type field (though see inflate()) */ enum kind { binary = 0, text = 1, unknown = 2 }; /** Deflate codec parameters. Objects of this type are filled in by callers and provided to the deflate codec to define the input and output areas for the next compress or decompress operation.). */ struct z_params { /** A pointer to the next input byte. If there is no more input, this may be set to `nullptr`. */ void const* next_in; /** The number of bytes of input available at `next_in`. If there is no more input, this should be set to zero. */ std::size_t avail_in; /** The total number of input bytes read so far. */ std::size_t total_in = 0; /** A pointer to the next output byte. */ void* next_out; /** The remaining bytes of space at `next_out`. */ std::size_t avail_out; /** The total number of bytes output so far. */ std::size_t total_out = 0; int data_type = unknown; // best guess about the data type: binary or text }; /** Flush option. */ enum class Flush { // order matters none, block, partial, sync, full, finish, trees }; /* compression levels */ enum compression { none = 0, best_speed = 1, best_size = 9, default_size = -1 }; /** Compression strategy. These are used when compressing streams. */ enum class Strategy { /** Default strategy. This is suitable for general purpose compression, and works well in the majority of cases. */ normal, /** Filtered strategy. This strategy should be used when the data be compressed is produced by a filter or predictor. */ filtered, /** Huffman-only strategy. This strategy only performs Huffman encoding, without doing any string matching. */ huffman, /** Run Length Encoding strategy. This strategy limits match distances to one, making it equivalent to run length encoding. This can give better performance for things like PNG image data. */ rle, /** Fixed table strategy. This strategy prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. */ fixed }; } // zlib } // beast } // boost #endif
https://www.boost.org/doc/libs/develop/boost/beast/zlib/zlib.hpp
CC-MAIN-2021-43
refinedweb
400
58.58
React和Node.js入门指南. The rationale for this is that JavaScript is very fast and it's worth keeping a DOM tree in it to speedup its manipulation. React is not a framework though. Think of it as the "View" in your traditional MVC framework. Although React was conceived to be used in the browser, because of its design it can also be used in the server with Node.js. We will take a peek at how this works, but you should wait for a more in-depth post about that. Hello World To get our feet wet, let's just have React render "Hello World". var Hello = React.createClass({ render: function() { return <div>Hello {this.props.name}</div>; } }); React.render(<Hello name='World' />, document.getElementById('container')); Apart from the weird part of mixing HTML with JavaScript, this code is pretty self-explanatory. Notice though how Hello is instantiated in the HTML just like the new Custom Elements standard and name is an attribute that is being used in the React Component as this.props.name. There is one strange part though: the way we are inlining HTML in JavaScript. What's up with that? JSX JSX is a JavaScript syntax extension with the ability to inline HTML. That's basically it. It's not required to use React, but it is recommended because it is "a concise and familiar syntax for defining tree structures with attributes" and "helps make large trees easier to read than function calls or object literals". It was conceived to be used with transpilers and not as an independent language. Our Hello World example is transpiled into: var Hello = React.createClass({displayName: "Hello", render: function() { return React.createElement("div", null, "Hello ", this.props.name); } }); React.render(React.createElement(Hello, {name: "World"}), document.getElementById('container')); You can learn more about JSX by following the official guide and by trying out the live transpiler. Also, it's supported by Babel. 组件 Let's make it more interesting and create some components: var Books = React.createClass({ render: function() { return ( <table> <thead> <tr> <th>Title</th> </tr> </thead> <tbody> <Book title='Professional Node.js'></Book> <Book title='Node.js Patterns'></Book> </tbody> </table> ); } }); var Book = React.createClass({ render: function() { return ( <tr> <td>{this.props.title}</td> </tr> ); } }); React.render(<Books />, document.getElementById('container')); Here we follow the exact same logic as we did in our Hello World example, but this time we composed an element of another element. We even passed a property from the parent element to the child element. Components are a very useful way to compose and reuse views (and logic). 属性 Everything in this.props is passed down to you from the parent. That includes the values that were declared in the element attributes, just like in regular HTML where you declare attributes like class or href. However, in React you can set a JSON blob in the attributes instead of having to declare an attribute for each property: var data = { title: 'Professional Node.js', author: 'Pedro Teixeira' }; var Book = React.createClass({ render: function() { return ( <tr> <td>{this.props.data.title}</td> <td>{this.props.data.author}</td> </tr> ); } }); React.render(<Book data={data}/>, document.getElementById('container')); 事件 Now we need to add a read checkbox to each book that mutates its state. For that, we need to register a listener for the checked event: var Books = React.createClass({ render: function() { return ( // ... <tr> <th>Title</th> <th>Read</th> </tr> // ... ); } }); var state = { read: false }; var Book = React.createClass({ handleChange: function(ev) { console.log('onChange: ', ev); }, render: function() { return ( <tr> <td>{this.props.title}</td> <td><input type='checkbox' checked={state.read} onChange={this.handleChange} /></td> </tr> ); } }); // ... Registering an event listener is as simple as passing a function to the attribute in the HTML. You can see all the supported events in the official documentation. Notice, though, that when we click the checkbox the state doesn't change. This is because the variable state is not changed, therefore the view doesn't change. 状态 In order for each Book to have a state that we can mutate and see the change reflected in the view, we need to add a getInitialState function that defines the initial state of the component and assigns it to this.state. var Book = React.createClass({ getInitialState: function() { return { read: false }; }, handleChange: function(ev) { console.log('onChange: ', ev); }, render: function() { return ( <tr> <td>{this.props.title}</td> <td><input type='checkbox' checked={this.state.read} onChange={this.handleChange} /></td> </tr> ); } }); Now we need to update handleChange to mutate the state every time the checkbox changes: preview on JSFiddle handleChange: function(ev) { this.state.read = !this.state.read; console.log(this.state.read); } Now, if we try again we should see the checkbox changing, right? Not really, although we can see in the logs that this.state.read is getting changed every time we click in the checkbox. What is missing then? Changing the value of the state is not enough, we need to trigger the UI updates. To do that we can call setState which will merge the current state with the next state being applied to the view. preview on JSFiddle handleChange: function(ev) { this.setState({ read: !this.state.read }); } And voilà! Now we are properly mutating the state and seeing the change reflected in our UI. 属性验证 Properties that are passed in the element attributes can take multiple forms. React provides a way to validate the property types that are passed to the components by declaring them in propTypes. In our example, we could validate the book title: var Book = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired } // ... }); Now if we don't pass a title attribute to the Book Component, we will see a warning in the logs: Warning: Failed propType: Required prop title was not specified in Book. Check the render method of Books. You can review more types and validations in the official documentation. 合起来 To finish our Book Library, we should implement a form to add new books and a button to remove existing ones. Does that sound like a plan? To write the form, we can do it in a new Component: section of ./views/index.jsx var BookForm = React.createClass({ propTypes: { onBook: React.PropTypes.func.isRequired }, getInitialState: function() { return { title: '', read: false }; }, changeTitle: function(ev) { this.setState({ title: ev.target.value }); }, changeRead: function() { this.setState({ read: !this.state.read }); }, addBook: function(ev) { ev.preventDefault(); this.props.onBook({ title: this.state.title, read: this.state.read }); this.setState({ title: '', read: false }); }, render: function() { return ( <form onSubmit={this.addBook}> <div> <label htmlFor='title'>Title</label> <div><input type='text' id='title' value={this.state.title} onChange={this.changeTitle}</div> </div> <div> <label htmlFor='title'>Read</label> <div><input type='checkbox' id='read' checked={this.state.read} onChange={this.changeRead} /></div> </div> <div> <button type='submit'>Add Book</button> </div> </form> ); } }); In the BookForm component we are changing its internal title and read values once they're changed in the view. Then, when the form is submitted, we pass its values to the onBook function that it received. After that we reset its state so that it can get new books. Now, let's implement our Books component based on what we had before: section of ./views/index.jsx var Books = React.createClass({ propTypes: { books: React.PropTypes.array }, getInitialState: function() { return { books: (this.props.books || []) }; }, onBook: function(book) { this.state.books.push(book); this.setState({ books: this.state.books }); }, render: function() { var books = this.state.books.map(function(book) { return <Book title={book.title} read={book.read}></Book>; }); return ( <div> <BookForm onBook={this.onBook}></BookForm> <table> <thead> <tr> <th>Title</th> <th>Read</th> </tr> </thead> <tbody>{books}</tbody> </table> </div> ); } }); Here we instantiate BookForm and pass onBook to it so that it can get new books once they're submitted. Once a book is received on onBook, we add it to the component state and propagate the book list. To generate the list of books, we just map through every book it knows and instantiate a Book on each one. Now, let's take a look at our Book component: section of ./views/index.jsx var Book = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired, read: React.PropTypes.bool.isRequired }, getInitialState: function() { return { title: this.props.title, read: this.props.read }; }, handleChange: function(ev) { this.setState({ read: !this.state.read }); }, render: function() { return ( <tr> <td>{this.props.title}</td> <td><input type='checkbox' checked={this.state.read} onChange={this.handleChange} /></td> </tr> ); } }); The Book componet stayed almost unchanged: it gets the title and read from the parent component and renders a with that data. Once onChange is triggered, it mutates the state and triggers a UI update. You can checkout a working version of our example. 服务器 To render React in the server we can use Node.js. You can install it using the pre-compiled binaries. We will not dive into how Node.js works and expect that you already know the basics. If you want to learn how to use Node.js we recomend NodeTuts and Node Patterns from our great Pedro Teixeira. The idea is to render a React view in the server and allow that view to still be interactive in the client. What we are going to do is have a view file with our React code - just like we saw before - and render it on the server. However, the HTML we are sending will include a script tag for a browserify bundle that includes our React view without being rendered. Once that bundle is interpreted in the client it will replace the static view and make it dynamic. This assumes some previous knowledge of either Express or Hapi. Express Express is a web framework for Node.js. It is the first successful Node.js framework and still the most used. It is very minimalist and can be extended using its middleware system. We have used the version 4.12.4 of the Express framework in this example. First, we need to require our dependencies: section of ./index.js var express = require('express'); var browserify = require('browserify'); var React = require('react'); var jsx = require('node-jsx'); var app = express(); Then we need to make jsx files requirable: section of ./index.js jsx.install(); Now we just need to serve our routes. But first, we should require our view: section of ./index.js var Books = require('./views/index.jsx'); section of ./index.js app.use('/', function(req, res) { var books = [{ title: 'Professional Node.js', read: false }, { title: 'Node.js Patterns', read: false }]; res.setHeader('Content-Type', 'text/html'); res.end' }) ) )); }); What this is doing is rendering our Books AND a script with our initial data AND a script with our browserify bundle. This way the first load has a fully rendered static view and the user doesn't have to wait for the client to render it. rendered HTML <body> <div id="container"> <!-- ... --> </div> <script id="initial-data" type="text/plain" data-</script> <script src="/bundle.js"></script> </body> We also need to listen for the /bundle.js request: section of ./index.js app.use('/bundle.js', function(req, res) { res.setHeader('content-type', 'application/javascript'); browserify('./app.js', { debug: true }) .transform('reactify') .bundle() .pipe(res); }); You might be asking: what does app.js have? Basically it's just a jsx script that requires our view and attaches it to the container so that it becomes dynamic in the client. ./app.js var React = require('react'); var Books = require('./views/index.jsx'); var books = JSON.parse(document.getElementById('initial-data').getAttribute('data-json')); React.render( To finish, we just need to listen for incoming connections: section of ./index.js var server = app.listen(3333, function() { var addr = server.address(); console.log('Listening @', addr.address, addr.port); }); Most of this is a very standard Express app, but you shouldn't be doing this in production. You should use a proper view engine (like express-react-views) and you shouldn't bundle your static assets on every request. This is just a proof of concept. We have a repository with this code so that you can try it: check it out. Don't forget to install the dependencies by running npm install in your shell before running the app. Hapi Hapi is also a web framework for Node.js. It advocates that configuration is better than code and business logic must be isolated from transport layer, providing a great solution for large teams. Our Hapi example uses almost the same code as the Express one. The framework version used was the 8.6.1. First we need to require our dependencies: section of ./index.js var Hapi = require('hapi'); var browserify = require('browserify'); var map = require('through2-map'); var fs = require('fs'); var React = require('react'); var jsx = require('node-jsx'); Then we need to make jsx files requirable: section of ./index.js jsx.install(); And create our Hapi server: section of ./index.js var server = new Hapi.Server(); Now we just need to serve our routes. But first, we should require our view: section of ./index.js var Books = require('./views/index.jsx'); section of ./index.js server.route({ method: 'GET', path:'/', handler: function (request, reply) { var books = [{ title: 'Professional Node.js', read: false }, { title: 'Node.js Patterns', read: false }]; reply' }) ) )).header('Content-Type', 'text/html'); } }); Almost the same logic as our Express example. Rendering a static view of our view and sending the initial data with a bundled script to make the site dynamic after being loaded in the client. We also need to listen for the /bundle.js request: section of ./index.js server.route({ method: 'GET', path:'/bundle.js', handler: function (request, reply) { reply(null, browserify('./app.js') .transform('reactify') .bundle().pipe(map({ objectMode: false }, function(chunk) { return chunk; }))); } }); We will be using the same ./app.js as in the Express example. To finish, we just need to set the connection: section of ./index.js server.connection({ host: 'localhost', port: (process.argv[2] || 3333) }); And start the server: section of ./index.js server.start(function () { console.info("Listening @", server.info.uri); }); Just as I said about our Express app: don't use this in production. You should use a proper view engine (like hapijs-react-views) and you shouldn't bundle your static assets on every request. This is just a proof of concept. We have a repository with this code so that you can try it: check it out. Also don't forget to install the dependencies by running npm install in your shell before running the app. 下一步 Now that you've built your first React app, you should jump into the official React website and go through their guides. Then try to build your own proof-of-concepts with different constraints and features. If you have questions/suggestions, you can reach out to @ramitos and @sericaia and we'll do our best to help!
https://wohugb.gitbooks.io/react-webpack-cookbook/content/getting-started.html
CC-MAIN-2021-04
refinedweb
2,485
60.72
Created on 2010-10-26 12:18 by jldm, last changed 2015-02-24 08:56 by gregory.p.smith. This issue is now closed. Hi, first of all sorry for my English. On windows XP SP3, the following code: import subprocess subprocess.getoutput("dir") returns '"{" is not recognized as an internal or external command,\noperable program or batch file.' I made a workaround by changing in the file Lib/subprocess.py the line 574 (I thin in 3.2a3 is 584) (in the getstatusoutput(cmd) function definition) from: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') to: pipe = os.popen('( ' + cmd + '; ) 2>&1', 'r') I have tested it with: ActivePython 3.1.2.3 (ActiveState Software Inc.) based on Python 3.1.2 (r312:79147, Mar 22 2010, 12:20:29) [MSC v.1500 32 bit (Intel)] on win32 and Python 3.2a3 (r32a3:85355, Oct 10 2010, 17:11:45) [MSC v.1500 32 bit (Intel)] on win32 Regards from Spain. José Luis Domenech Oddly, the test suite skips getoutput and getstatusoutput on windows with the comment that the source says it is relevant only for posix, but the documentation does not have 'availability: unix' tags. (It is also odd that getoutput isn't documented, but that's a different issue.) Your workaround can't be used as a fix, since the semantics of {}s in the shell are different from those of ()s. It's not clear to me what the point of the {}s is, but I have a fear that eliminating them would introduce subtle changes in the behavior of getoutput calls. Perhaps not, though. It looks like this issue amounts to an RFE for support of getoutput/getstatusoutput on Windows, though the fact that it is not documented as unix-only may make it a bug instead :) The appropriate fix is probably to conditionalize the code based on platform. A complete patch will require unit test changes and documentation changes (since the docs currently mention the braces). All of that said, it also appears that the new check_output should be preferred to either getoutput or getstatusoutput. Perhaps those functions could be re-implemented in terms of check_output. () is used to launch a command in a sub-shell and {} is used to group commands, for example to set up a stream redirection for all commands in brackets. I think we should implement getstatusoutput and getoutput with Popen objects to gain portability and avoid spawning subshells. Do you have in implementation in mind? I'm not clear how this would work. My idea is simply using Popen with appropriate args for stdout and stderr instead of using a shell command with redirections: --- Lib/subprocess.py (révision 86943) +++ Lib/subprocess.py (copie de travail) @@ -560,11 +560,7 @@ return ''.join(result) -# Various tools for executing commands and looking at their output and status. -# -# NB This only works (and is only relevant) for UNIX. - -def getstatusoutput(cmd): +def getstatusoutput(cmd, shell=True): """Return (status, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple @@ -581,14 +577,21 @@ >>> subprocess.getstatusoutput('/bin/junk') (256, 'sh: /bin/junk: not found') """ - pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') - text = pipe.read() - sts = pipe.close() - if sts is None: sts = 0 - if text[-1:] == '\n': text = text[:-1] + # Wish I could use with... + popen = Popen(cmd, shell=shell, stdout=PIPE, stderr=STDOUT) + sts = popen.communicate() #or wait() or whatever is the right thing + try: + text = process.stdout.read() + finally: + process.stdout.close() + if sts is None: + sts = 0 + if text.endswith('\n'): + text = text[:-1] return sts, text (The new “shell” argument is icing on the cake, allowing us to later support a list as cmd argument like Popen does.) -def getstatusoutput(cmd): +def getstatusoutput(cmd, shell=True): shell=True is dangerous, it can lead to shell command injection. I would prefer to set its default value to False. The function already exists in Python 3.1, but it is not used in Python source code. Is it too late to fix its API to avoid security vulnerabilities? > The function already exists in Python 3.1, but it is not used in Python source code We don’t know what code out there uses. This would be an incompatible change. Ah, I did not realize that getstatusoutput was implemented using os.popen. I thought it already used Popen. Now, in python3, os.popen is in turn implemented using subprocess.Popen, so removing that level of indirection seems sensible. The question that remains is, does removing the {} change the output obtained from a command sequence in any way? Note that for backward compatibility you will need to re-munge the status code into C format. Which makes me wonder if getoutput/getstatusoutput should just be documentationally deprecated instead. (I never use them myself, FWIW) See also Issue9922 > The question that remains is, does removing the {} change the output > obtained from a command sequence in any way? {} are used to group output from the commands into one stream. I believe the stdout and stderr arguments to Popen allow us to get compatible behavior. Tests need to prove that, of course. > Which makes me wonder if getoutput/getstatusoutput should just be > documentationally deprecated instead. (I never use them myself, FWIW) They were relocated from the commands module, resulting in slightly overlapping functions that don’t share a naming patter: call, check_call, getoutput, getstatusoutput. subprocess_getoutput.patch: patch subprocess.getstatusoutput() to use directly Popen, instead of os.popen, with stderr=subprocess.STDOUT instead of "2>&1" shell redirection. It strips also all trailing spaces and newlines, not just the last one. And finally, it removes "Availability: UNIX." from the documentation.). And if getstatusoutput() doesn't accept argument list, it becomes useless with shell=False (it doesn't support to call a program with arguments). Note: the status is still shifted on UNIX to be compatible with the wait() format. >). Example of function to escape a list of arguments on UNIX: def escapeargs(*args): return ' '.join(pipes.quote(arg) for arg in args) R. David Murray disagree with me to allow getoutput(list) (shell=True) because Popen(list, shell=True) behaves differently. subprocess.Popen(['echo Hello'], shell=True) writes 'Hello', whereas subprocess.Popen(['echo', 'Hello'], shell=True) writes nothing (because echo has no argument. I would like to do something like that: getoutput(['echo', 'Hello']) calls Popen('echo Hello', shell=True) using escapeargs() function defined above. So getoutput(list) calls shell -c "arg1 arg2", whereas Popen(list, shell=True) calls shell -c "arg1" arg2 arg3 ... See also issue #7839 for Popen(str, shell=False) and Popen(list, shell=True) cases. subprocess.getoutput does not currently work at all on Windows. So it's not necessary to maintain backwards compatibility. The following fix works for me on WinXP/Python 3.2.2. Replace pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') # line 613 of subprocess.py with if mswindows: pipe = os.popen(cmd + ' 2>&1', 'r') # Windows does not support { } else: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') A better fix, which supports multiple windows commands: if mswindows: pipe = os.popen('( ' + cmd + ' ) 2>&1', 'r') # Windows uses () rather than { } else: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') This works with the command subprocess.getoutput("echo before & python -V & echo after") Note that python -V writes to stderr, so without the enclosing ( ) the version information is not captured. If Windows shell syntax is similar to POSIX one, then () will run in a sub-shell, which would be a different behavior than using {} (which merely group statements and their streams). I got the () syntax from: which refers to grouping, not subshell. Without knowing this issue existed, I recently started working on adding some convenience APIs for shell invocation to shutil: I think the getstatus and getstatusoutput APIs were copied from the commands module in 3.0 without sufficient thought being given to whether or not they fit with the design principles of the subprocess module. IMO, both should be deprecated: - they're not cross-platform - they invoke the shell implicitly, which subprocess promises never to do > IMO, both should be deprecated: > - they're not cross-platform Isn’t the purpose of this report to fix that? :) > - they invoke the shell implicitly, which subprocess promises never to do One could argue that it’s not implicit if it’s documented. Nonetheless, I agree that they don’t fit well with the subprocess promises. So, +1 on deprecating and +1 on new, safer helpers. I think that adding safer wrappers and deprecating things are valuable but different bugs. In the short term, we could apply the proposed small patch to just fix the issue at hand. Can one of the Windows experts weigh in? The patch does this: if mswindows: pipe = os.popen('( ' + cmd + ' ) 2>&1', 'r') else: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') It was tested manually; a test should be simple to write. Patched according to Nick Coghlan's suggestion in. Ad hoc tests look ok on Windows. I'll add tests & look at *nix later. New changeset c34e163c0086 by Tim Golden in branch '3.3': Issue #10197 Rework subprocess.get[status]output to use subprocess functionality and thus to work on Windows. Patch by Nick Coghlan. New changeset 05ce1bd1a4c2 by Tim Golden in branch 'default': Issue #10197 Rework subprocess.get[status]output to use subprocess functionality and thus to work on Windows. Patch by Nick Coghlan. New changeset b6efaa97ee0e by Tim Golden in branch '3.3': Issue #10197: merge heads New changeset 28a0ae3dcb16 by Tim Golden in branch 'default': Issue #10197: merge heads New changeset fe828884a077 by Tim Golden in branch 'default': Issue #10197: merge 3.3 Code & tests now work on Windows. Applied to 3.3 & 3.4. The documentation needs updating to state that these are available on Windows (currently it says UNIX) with a versionchanged annotation. New changeset 2924a63aab73 by Tim Golden in branch '3.3': Issue #10197: Indicate availability of subprocess.get[status]output on Windows and add a note about the effects of universal newlines New changeset effad2bda4cb by Tim Golden in branch 'default': Issue #10197: Indicate availability of subprocess.get[status]output on Windows and add a note about the effects of universal newlines Good point. I've added the versionchanged tag. The issue with bytes-string encoding goes all the way back to Popen.communicate if universal newlines mode is used so I've simply put in a reference to the existing notes on the subject higher up in the docs. New changeset 0aa2aedc6a21 by Tim Golden in branch 'default': Issue #10197 Tweak docs for subprocess.getstatusoutput and align the documentation, the module docstring, and the function docstring. Is this ready to be reclosed? Lib/subprocess.py still has outdated comment: # NB This only works (and is only relevant) for POSIX. Thanks: final outdated comments removed New changeset 34df43c9c74a by R David Murray in branch '3.3': #10197: Update get[status]output versionchanged with actual version. New changeset ee277b383d33 by R David Murray in branch 'default': #10197: Update get[status]output versionchanged with actual version. A side effect of the changes made within are that getstatusoutput() on POSIX systems now returns a different value for status. The old implementation present in Python 2 and Python 3.3 before this patch returned the raw waitpid() status result as the status value. ie: getstatusoutput("exit 1")[0] == 256. the lower 8 bits were reserved for the signal number the process died with, if any. Now it returns the sanitized subprocess style returncode: positive numbers are the process exit code (so the above example returns 1) and negative numbers are the negative signal number the process died with. I prefer the new behavior, but this API change is not documented anywhere that I can find. to track the fall out of that.
https://bugs.python.org/issue10197
CC-MAIN-2017-22
refinedweb
1,977
67.65
Read here for LOTS more of these @ForestOwl, do you remember the thread you created about vector.unitize() You’re making the same mistake here. shuffle will modify the list and not create another one. so not print a but rather print thing Can this, be somehow fixed with the Rhino embedded python engine? I can imagine huge problems can emerge if the coder is careless. Just tried this in CPython 2.7: True = False True == False True True = not False True == False False Yes, I read that since at the beginning there were no booleans in python in order to make them backportable they derived True and False from the int() class. This made them mutable in all Python2 versions. Which was also transferred to IronPython. I assumed since the C# connection they might have fixed that but unfortunately they didn’t. Perhaps this could be fixed somehow with the embedded engine bind it somehow to .net’s booleans. I don’t know. I’m not familiar with low level programming. I’m not going to change this behavior. And I think the Ironpython dev will focus on trying to finish 3.4 before he tries to ´fix’ 2.7 I tried PointAt this time too, but it seems I am doing something wrong. I have the curve length of 84, then I have a list of numbers between 0 and 84. When I use PointAt, my points fly everywhere. Do you might know why? problem derivativeat 07.gh (20.6 KB) I find your code difficult to follow. It is good practice if you don’t use good descriptive names for the variables to place comments explaining what you’re trying to do. Up to the part where you remove the duplate values from the list and you sort it everything is clear, but after that I really don’t get what you’re trying to do. Thank you for saying, I changed it. I hope it is more clear now. I have a curve and I want to place points on it between 0 and the MAX length of the curve. I made values and somehow by using PointAt, the points fly away. I do not yet understand why. Do you might know why my points are not on that curve? problem derivativeat 08.gh (27.0 KB) Point at takes parameter not distance on the curve One of the components here does what you want. It will be a good test to see if it works with multiple length values instead of the slider. I do not remember how I intended it to work I can fix it. I need python, does it not exist in python? @ivelin.peychev @ivelin.peychev Does one of you might know which places the points by length? EDIT: never mind, I found it from a former post Curve.PointAtLength Method You’ll have to normalize the length if I remember correctly, keep that in mind No it seems it can be used without normalizing the length. Great! You could also, you know, look up the documentation: You’re logic is wrong, @ForestOwl! You need to remap your desired distance for each curve from the curve length domain to the curve domain. Let’s say your desired, random distance for a point on the curve is 2.5, and the domain of the curve is (3.5, 5.0), whereas its length domain is (0.0, 84.856). At the moment, you try to create a point at the curve parameter 2.5, which doesn’t exist. This makes your point appear somewhere else. Instead, you simply remap your distance to the curve domain. For this example, that should be a curve parameter of 3.544… that fits on your curve, since it’s included in the curve domain! import Rhino.Geometry as rg import random random.seed(2) def fit(value, source_domain, target_domain): """Fits a number between a target domain that is relative to a number in the source domain. Args: value: number to be fitted source_domain: tuple containing the domain start and end target_domain: tuple containing the domain start and end Returns: The refitted value, or None, if the initial value is outside the source domain. """ if (value < source_domain[0]) or (value > source_domain[1]): return else: source_range = source_domain[1] - source_domain[0] if source_range == 0: fitted_value = target_domain[0] else: target_range = target_domain[1] - target_domain[0] fitted_value = (((value - source_domain[0]) * target_range) / source_range) + target_domain[0] return fitted_value curr_plane = Planes[0] curr_crv = Curves[0] min_dist, max_dist = DistInterval # Get the curve length crv_len = curr_crv.GetLength() # Get the curve domain crv_dom = curr_crv.Domain curr_dist = 0.0 # current desired distance crv_parameters = [] # curve parameters div_pts = [] # curve division points while curr_dist < crv_len: # Remap the desired distance to the curve domain crv_param = fit(curr_dist, (0.0, crv_len), crv_dom) # Check if curve parameter hasn't been visited yet if crv_param not in crv_parameters: # Get the curve point for the curve parameter pt = curr_crv.PointAt(crv_param) # Add the curve point to the division points list div_pts.append(pt) # Add the curve parameter to the curve parameters list as history entry crv_parameters.append(crv_param) # Randomly increment the current desired distance curr_dist += random.randint(min_dist, max_dist) # --- OUTPUTS a = div_pts problem derivativeat 08.gh (16.4 KB) No, this wouldn’t work either! When normalising the curve domain or curve length, you still have to remap your distance to the normalised domain, when it’s not between 0.0 and 1.0.
https://discourse.mcneel.com/t/python-derivativeat/81591/35
CC-MAIN-2022-05
refinedweb
907
75.1
Custom USB games controllers with Raspberry Pi Pico | HackSpace 42 Games controllers – like keyboards – are very personal things. What works for one person may not work for another. Why, then, should we all use almost identical off-the-shelf controllers? In the latest issue of HackSpace magazine, we take a look at how to use Raspberry Pi Pico to create a controller that’s just right for you. We’ll use CircuitPython for this as it has excellent support for USB interfaces. The sort of USB devices that we interact with are called human interface devices (HIDs), and there are standard protocols for common HIDs, including keyboards and mice. This is why, for example, you can plug almost any USB keyboard into almost any computer and it will just work, with no need to install drivers. We’ll be using the Keyboard type, as that works best with the sorts of games that this author likes to play, but you can use exactly the same technique to simulate a mouse or a gamepad. Before we get onto this, though, let’s take a look at the buttons and how to wire them up. We’re going to use eight buttons: four for direction, and four as additional ‘action’ buttons. We’ll connect these between an I/O pin and ground. You can use any I/O pin you like. We’re going to use slightly different ones in two different setups, just because they made sense with the physical layout of the hardware. Let’s take a look at the hardware we’re using. Remember, this is just the hardware we want to use. The whole idea of this is to create a setup that’s right for you, so there’s no need to use the same. Think about how you want to interact with your games and take a look at the available input devices and build what you want. The first setup we’re creating is an Arcade box. This author would really like an arcade machine in his house. However, space limitations mean that this isn’t going to be possible in the near future. The first setup, then, is an attempt to recreate the control setup of an arcade machine, but use it to play games on a laptop rather than a full-sized cabinet. Arcade controls are quite standard, and you can get them from a range of sources. We used one of Pimoroni’s Arcade Parts sets, which includes a joystick and ten buttons (we only used four of these). The important thing about the joystick you pick is that it’s a button-based joystick and not an analogue one (sometimes called a dual-axis joystick), as the latter won’t work with a keyboard interface. If you want to use an analogue joystick, you’ll need to switch the code around to use a mouse or gamepad as an input device. As well as the electronics, you’ll need some way of mounting them. We used a wooden craft box. These are available for about £10 from a range of online or bricks and mortar stores. You can use anything that is strong enough to hold the components. The second setup we’re using is a much simpler button-based system on breadboard-compatible tactile buttons and protoboard. It’s smaller, cheaper, and quicker to put together. The protoboard holds everything together, so there’s nothing extra to add unless you want to. You can personalise it by selecting different-sized buttons, changing the layout, or building a larger chassis around this. Insert coin to continue Let’s take a look at the arcade setup first. The joystick has five pins. One is a common ground and the others are up, down, left, and right. When you push the joystick up, a switch closes, linking ground to the up pin. On our joystick the outermost pin is ground, but it’s worth checking on your joystick which pin is which by using a multimeter. Select continuity mode and, if you push the joystick up, you should find a continuous connection between the up pin and ground. A bit of experimentation should confirm which pin is which. In order to read the pins, we just need to connect the directional output from the joystick to an I/O pin on Pico. We can use one of Pico’s internal pull-up resistors to pull the pin high when the button isn’t pressed. Then, when the button is pressed, it will connect to ground and read low. The joystick should come with a cable that slots onto the joystick. This should have five outputs, and this conveniently slots into the I/O outputs of Pico with a ground on one end. The buttons, similarly, just need to be connected between ground and an I/O pin. These came with cables that pushed onto the button and plugged into adjacent pins. Since Pico has eight grounds available, there are enough that each button can have its own ground, and you don’t have to mess around joining cables together. Once all the cables are soldered together, it’s just a case of building the chassis. For this, you need five large holes (one for the joystick and four for the buttons). We didn’t have an appropriately sized drill bit and, given how soft the wood on these boxes is, a large drill bit may have split the wood anyway. Instead, we drilled a 20 mm hole and then used a rotary tool with sanding attachment to enlarge the hole until it was the right size. You have to go quite easy with both the drill and the sanding tool to avoid turning everything into shards of broken wood. Four small holes then allow bolts to keep the joystick in place (we used M5 bolts). The buttons just push into place. With a combination of small sections of wire and jumpers, you can create whatever pattern of wiring you like on protoboard The only remaining thing was a 12 mm hole for a micro USB cable to pass through to Pico. If you don’t have a 12 mm drill bit, two overlapping smaller holes may work if you’re careful. The buttons just push-fit into place, and that’s everything ready to go. A smaller approach Our smaller option used protoboard over the back of Pico. Since we didn’t want to block the BOOTSEL button, we only soldered it over part of Pico. However, before soldering it on at all, we soldered the buttons in place. Tactile switches typically have four connections. Well, really they have two connections, but each connection has two tabs that fit into the protoboard. This means that you have to orientate them correctly. Again, your multimeter’s continuity function will confirm which pins are connected and which are switched. Protoboard is a PCB that contains lots and lots of holes and nothing else. You solder your components into the holes and then you have to create connections between them. We placed the buttons in the protoboard in positions we liked before worrying about the wiring. First, we looked to connect one side of each switch to ground. To minimise the wiring, we did this in two groups. We connected one side of each of the direction buttons together and then linked them to ground. Then we did the same to all the action buttons. There are two ways of connecting things on protoboard. One is to use jumper wire. This works well if the points are more than a couple of holes apart. For holes that are next to each other, or very close, you can bridge them. On some protoboard (which doesn’t have a solder mask), you might simply be able to drag a blob of solder across with your soldering iron so that it joins both holes. On protoboard with solder mask, this doesn’t work quite so well, so you need to add a little strand of wire in a surface-mount position between the two points and solder it in. If you’ve got a pair of tweezers to hold the wire in place while you solder it, it will be much easier. For longer connections, you’ll need to use jumper wire. Sometimes you’ll be able to poke it through the protoboard and use the leg to join. Other times you’ll have to surface-mount it. This all sounds a bit complicated, but while it can be a bit fiddly, it’s all fairly straightforward once you put solder to iron. Program it up Now that we’ve got the hardware ready, let’s code it up. You’ll first need to load CircuitPython onto your Pico. You can download the latest release from circuitpython.org. Press the BOOTSEL button as you plug Pico into your USB port, and then drag and drop the downloaded UF2 file onto the RP2 USB drive that should appear. We’ll use Mu to program Pico. If you’ve not used CircuitPython before, it’s probably worth having a quick look through the ’getting started’ guide. The code to run our games controller is: import board import digitalio import gamepad import time import usb_hid from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode kbd = Keyboard(usb_hid.devices) keycodes = [Keycode.UP_ARROW, Keycode.DOWN_ARROW, Keycode.LEFT_ARROW, Keycode.RIGHT_ARROW, Keycode.X, Keycode.Z, Keycode.SPACE, Keycode.ENTER] pad = gamepad.GamePad( digitalio.DigitalInOut(board.GP12), digitalio.DigitalInOut(board.GP14), digitalio.DigitalInOut(board.GP9), digitalio.DigitalInOut(board.GP15), digitalio.DigitalInOut(board.GP16), digitalio.DigitalInOut(board.GP17), digitalio.DigitalInOut(board.GP18), digitalio.DigitalInOut(board.GP20), ) last_pressed = 0 while True: this_pressed = pad.get_pressed() if (this_pressed != last_pressed): for i in range(8): if (this_pressed & 1<<i) and not (last_pressed & 1<<i): kbd.press(keycodes[i]) if (last_pressed & 1<<i) and not (this_pressed & 1<<i): kbd.release(keycodes[i]) last_pressed = this_pressed time.sleep(0.01) This uses the HID keyboard object (called kbd) to send key press and release events for different key codes depending on what buttons are pressed or released. We’ve used the gamepad module that is for keeping track of up to eight buttons. When you initialise it, it will automatically add pull-up resistors and set the I/O pins to input. Then, it will keep track of what buttons are pressed. When you call get_pressed(), it will return a byte of data where each digit corresponds to an I/O pin. So, the following number (in binary) means that the first and third buttons have been pressed: 00000101. This is a little confusing, because this is the opposite order to how the I/Os are passed when you initialise the GamePad object. The while loop may look a little unusual as it’s not particularly common to use this sort of binary comparison in Python code, but in essence, it’s just looking at one bit at a time and seeing either: it’s now pressed but wasn’t last time the loop ran (in which case, it’s a new button press and we should send it to the computer), or it isn’t pressed this loop but was the previous loop (in which case, it’s newly released so we can call the release method). The << operator shifts a value by a number of bits to the left. So, 1<<2 is 100, and 1<<3 is 1000. The & operator is bitwise and so it looks at a binary number and does a logical AND on each bit in turn. Since the right-hand side of the & is all zeros apart from one bit (at a different position depending on the value of i), the result will be dependent on whether the value of this_pressed or last_pressed is 1 or 0 at the position i. When you have an if condition that’s a number, it’s true if the number is anything other than 0. So, (this_pressed & 1<<2) will evaluate to true if there’s a 1 at position 2 in the binary form of this_pressed. In our case, that means if the joystick is pushed left. You can grab this code from the following link – hsmag.cc/USBKeyboard. Obviously, you will need to update the GPIO values to the correct ones for your setup when you initialise GamePad. We’ve taken a look at two ways to build a gamepad, but it’s up to you how you want to design yours. Issue 42. Martin Bonner “If you don’t have a 12mm drill bit…” I don’t understand the next bit. Surely the reaction of any right thinking person is “… you now have a perfect excuse to go out and buy one”? (Also, rather than drill a smaller hole and then sand it to the right size, the correct tool is a hole saw.) SamVimes Out of curiosity: Is there any advantage over using an arcade kit with one of these “zero delay usb encoders”? Cheaper? More accurate? Faster? Smaller? Additional functionality? pik33 Is it possible to do a reverse thing? Connect an USB joystick/gamepad to RPi Pico and get digital signal outputs on Pico’s pins?
https://www.raspberrypi.org/blog/custom-usb-games-controllers-with-raspberry-pi-pico-hackspace-42/
CC-MAIN-2021-21
refinedweb
2,211
71.34
Due 9am, Monday, October 03 2016 In this prelab, you will familiarize yourself with some of the design and implementation issues in the upcoming lab 4. Please write or type up your solutions, and hand in a paper copy before class on Monday. Remember, late prelabs receive zero credit. In this section of the lab you will implement your own doubly-linked list and a corresponding iterator. Suppose your MyLinkedList<T> class is implemented as a doubly linked list and contains Node as a nested class: public class MyLinkedList<T> extends AbstractList<T> { class Node { T data; Node prev, next; // more code here } // Class variables for MyLinkedList private Node head; private Node tail; private int size; /* Lots more code will go here */ } where both head and tail point to sentinel nodes pointing at each other and the size is 0 when the list is empty. public MyLinkedList() { // Your answer will go here } private Node getNth(int index) { // Your answer will go here }that returns a reference to the Node at position index in the linked list. Write the method body for this method. For the prelab, you may assume that index is within the range 0 to size-1 (but check this in the actual lab!). Your MyLinkedList class will generate a ListIterator when the factory method listIterator() (from AbstractList) is invoked. An Iterator provides an easy way for someone to go through every item in your collection. The Iterator<T> interface has three methods: // returns true if there are more items to see public boolean hasNext(); // returns the next item in the list (and advances forward) public T next(); // removes the last item returned by next() public T remove(); A ListIterator supports going both backwards and forwards, so it also contains a couple of other methods // returns true if there are more items to see going backwards public boolean hasPrevious(); // returns the previous item in the list (and advances backwards) public T previous(); After one call to next(), the iterator is logically in the state shown below (click to enlarge). If you call next() you would get B, but if you called previous() instead you would get A. You don't want to always have to re-start at the head each time a user calls next(), so your ListIterator will need to keep track of its position in the list based on a Node instead of an index (which you might choose to use when constructing an ArrayList iterator). Fill in the following methods listed in this anonymous class: (For the prelab you may ignore throwing exceptions for going too in the next question ... }; } We also want an add(x) method that adds a new item just before whatever would have been returned by next() but just after whatever would have been returned by previous()? (This would put x in between A and B in the above diagram.) Give brief method bodies for these as well: public void remove() { // what lines of code go here? } public void add(T x) { // what lines of code go here? }
https://www.cs.oberlin.edu/~rhoyle/16f-cs151/lab04/prelab.html
CC-MAIN-2017-51
refinedweb
508
60.38
Velo by Wix: Event handling of Repeater Item In this post, we consider why we shouldn't nest event handler inside the Repeater loop and how we can escape it. At first sight, the adding event handling for repeated items looks easy. You just handling events of repeated items inside Repeater loop methods there you have all needed data and scope with selector $item(). $w("#repeater").onItemReady(($item, itemData, index) => { // it look easy $item("#repeatedButton").onClick((event) => { // we have all we need console.log( $item("#repeatedContainer"), itemData, index, ); }); }); What's wrong with this approach? Sometimes the loop may set a few event handlers for the same item when you change order or filter or sort Repeater Items. Each iteration of the loop may add a copy of the callback function to the handler when it starts again. You may don't pay attention to twice running code if you just hide or show some component by an event. But if you work with APIs or wixData, then you can get a lot of problems. My team and I consider this approach as an anti-pattern and we don't use it more. For the "static" Repeaters which fill up once and don't change anymore during a user session, this approach can be used. But if you would like to do dynamic fill up your Repeater or change its items, you shouldn't set a handler function inside the loop. Let's see another way. Selector Scope In the Velo, we have two types of selector functions. The Global Scope Selectors it's $w(). We can use it anywhere in the frontend part of Wix site. If we use $w() with Repeater Items, then it changes all items // will change a text in all items $w("#repeatedText").text = "new"; Repeated Item Scope A selector with repeated item scope can be used to select a specific instance of a repeating element. We can get repeated-item-scope selector in a few ways. In the loop, selector as the first argument in callback function for .forEachItem(), .forItems(), and .onItemReady() methods. Deprecated way, selector as the second argument in an event handler. It still works but you don't have to use it. Removal of the $w Parameter from Event Handlers // 🙅♀️ DON'T USE IT 🙅♂️ $w("#repeatedButton").onClick((event, $item) => { // deprecated selector function (could be removed in the future) $item("#repeatedText").text = "new"; }); And with an event context. We can get the selector function with $w.at(context). $w("#repeatedButton").onClick((event) => { // accepts an event context and // returns repeated items scope selector const $item = $w.at(event.context); $item("#repeatedText").text = "new"; }); Let's try to reproduce how we can use event.context instead of Repeater loop methods. // we use global selector `$w()`, it provides handling all repeated items $w("#repeatedButton").onClick((event) => { // get repeated item scope const $item = $w.at(event.context); // get the ID of the repeated item which fired an event const itemId = event.context.itemId; // get all repeater's data, it's stored as an array of objects const data = $w("#repeater").data; // use the array methods to find the current itemData and index const itemData = data.find((item) => item._id === itemId); const index = data.findIndex((item) => item._id === itemId); // we have all we need console.log( $item('#repeatedContainer'), itemData, index, ); }); In this way, we have only one callback for all elements with the specific ID. Using context we can get the active item scope, its itemData, and index Now, we see how to do more careful handling of events in the Repeater. But this code not good enough for reuse. Let's move the scope selector logic out event handler to the separate method. Create hook Our hook will have next steps: #1 Implementation // here will be all logic const createScope = (getData) => (event) => { // TODO: Implement hook } #2 initialize // sets callback function, it has to return the repeater data const useScope = createScope(() => { return $w("#repeater").data; }); #3 using // using with repeated items $w("#repeatedButton").onClick((event) => { // returns all we need const { $item, itemData, index, data } = useScope(event); }); We create a hook with createScope(getData) it will be work with a specific Repeater. The argument getData it's a callback, it has to return the Repeater data. The createScope will return a new function useScope(event) that has a connection with the specific Repeater data. The useScope(event) accepts an event object and return the data of the current scope. For the realization of createScope(getData) function, we will create a public file public/util.js We can get Repeater data with getData(), and we have the event context. All we need just return Scope selector and item data as an object. We will use getter syntax for returning itemData, index, and data. public/util.js export const createScope = (getData) => (event) => { const itemId = event.context.itemId; const find = (i) => i._id === itemId; return { $item: $w.at(event.context), get itemData() { return getData().find(find); }, get index() { return getData().findIndex(find); }, get data() { return getData(); }, }; }; If you don't work with getter/setter for property accessors you can look here how it works. Let's see how we can use the hook on the page with static or dynamic event handlers. HOME Page Code import { createScope } from "public/util"; const useScope = createScope(() => { return $w("#repeater").data; }); $w.onReady(() => { // use a dynamic event handler $w("#repeatedButton").onClick((event) => { const { $item, itemData, index, data } = useScope(event); }); }); // or a static event handler export function repeatedButton_click(event) { const { $item, itemData, index, data } = useScope(event); } Now, we can reuse the selector hook with all Repeater in all site pages. JSDoc The Velo code editor supports JSDoc, it's a markup language that is used inside JS block comments. JSDoc provides static type checking, adds the autocomplete, and making good documentation of your code. I recommend using JSDoc. Code snippet with JSDoc: /** * Create Repeated Item Scope * * * @typedef {{ * _id: string; * [key: string]: any; * }} ItemData; * * @typedef {{ * $item: $w.$w; * itemData: ItemData; * index: number; * data: ItemData[]; * }} ScopeData; * * @param {() => ItemData[]} getData * @returns {(event: $w.Event) => ScopeData} */ export const createScope = (getData) => (event) => { const itemId = event.context.itemId; const find = (i) => i._id === itemId; return { // @ts-ignore $item: $w.at(event.context), get itemData() { return getData().find(find); }, get index() { return getData().findIndex(find); }, get data() { return getData(); }, }; }; Don't remove JSDoc in your code! In the building process, all comments will be removed automatically from the production bundle. Resources - Code on GitHub - Scope selector $w.at(context) - Global Scope & Repeated Item Scope Selectors - Event Context - Property getters and setters
https://shoonia.site/event-handling-of-repeater-item
CC-MAIN-2021-49
refinedweb
1,087
58.38
Hello, On Thu, Dec 30, 2004 at 10:58:08PM +0000, Roger Leigh wrote: > "Marcelo E. Magallon" <mmagallo@debian.org> writes: > > > On Fri, Dec 31, 2021 at 10:38:46AM -0300, Eduardo Marcel Macan wrote: > > > > > Mini-XML is a small XML parsing library that you can use to > > > read XML and XML-like data files in your application without > > > requiring large non-standard libraries. Mini-XML only > > > requires an ANSI C compatible compiler (GCC works, as do > > > most vendors' ANSI C compilers) and a "make" program. > > > > You mean unlike libxml2? > > > > Package: libxml2 > > Depends: libc6 (>= 2.3.2.ds1-4), zlib1g (>= 1:1.2.1) > > > > I wonder at which other library is upstream taking shots... not Xerces > > and not libxmlparse. > > > > You might want to include relevant information, like (lack of) > > validation, external loading, UTF-8, namespaces and the like. > > mxml is intended to be minimal, as a counter to libxml2 bloat (and it > *is* a bloated monster). If you are looking for a tiny tool to handle xml within C programs I suggest that you take a look at flexml. It is based on flex. Unfortunately it works with the old-flex. I had not the time to help patching it so that is works with flex. I am sure that the upstream author will accept to recieve patches.
https://lists.debian.org/debian-devel/2005/01/msg00096.html
CC-MAIN-2019-18
refinedweb
218
74.9
Artifact fc8c51f0b61bc803ccdec092e130bebe762b0a2f: - File src/encode.c — part of check-in [0a12473c] at 2004-03-17 18:44:46 on branch trunk — The sqlite_trace() API only works for commands started by the user, not for SQL commands run during initialization. (CVS 1298) (user: drh size: 8974) /* ** not used by any other ** part of the SQLite library. ** ** $Id: encode.c,v 1.12 2004/03/17 18:44:46 drh Exp $ */ #include <string.h> #include <assert.h> /* ** How This Encoder Works ** ** The output is allowed to contain any character except 0x27 (') and ** 0x00. This is accomplished by using an escape character to encode ** 0x27 and 0x00 as a two-byte sequence. The escape character is always ** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The ** 0x27 character is encoded as the two byte sequence 0x01 0x28. Finally, ** the escape character itself is encoded as the two-character sequence ** 0x01 0x02. ** ** To summarize, the encoder works by using an escape sequences as follows: ** ** 0x00 -> 0x01 0x01 ** 0x01 -> 0x01 0x02 ** 0x27 -> 0x01 0x28 ** ** If that were all the encoder did, it would work, but in certain cases ** it could double the size of the encoded string. For example, to ** encode a string of 100 0x27 characters would require 100 instances of ** the 0x01 0x03 escape sequence resulting in a 200-character output. ** We would prefer to keep the size of the encoded string smaller than ** this. ** ** To minimize the encoding size, we first add a fixed offset value to each ** byte in the sequence. The addition is modulo 256. (That is to say, if ** the sum of the original character value and the offset exceeds 256, then ** the higher order bits are truncated.) The offset is chosen to minimize ** the number of characters in the string that need to be escaped. For ** example, in the case above where the string was composed of 100 0x27 ** characters, the offset might be 0x01. Each of the 0x27 characters would ** then be converted into an 0x28 character which would not need to be ** escaped at all and so the 100 character input string would be converted ** into just 100 characters of output. Actually 101 characters of output - ** we have to record the offset used as the first byte in the sequence so ** that the string can be decoded. Since the offset value is stored as ** part of the output string and the output string is not allowed to contain ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27. ** ** Here, then, are the encoding steps: ** ** (1) Choose an offset value and make it the first character of ** output. ** ** (2) Copy each input character into the output buffer, one by ** one, adding the offset value as you copy. ** ** (3) If the value of an input character plus offset is 0x00, replace ** that one character by the two-character sequence 0x01 0x01. ** If the sum is 0x01, replace it with 0x01 0x02. If the sum ** is 0x27, replace it with 0x01 0x03. ** ** (4) Put a 0x00 terminator at the end of the output. ** ** Decoding is obvious: ** ** (5) Copy encoded characters except the first into the decode ** buffer. Set the first encoded character aside for use as ** the offset in step 7 below. ** ** (6) Convert each 0x01 0x01 sequence into a single character 0x00. ** Convert 0x01 0x02 into 0x01. Convert 0x01 0x28 into 0x27. ** ** (7) Subtract the offset value that was the first character of ** the encoded buffer from all characters in the output buffer. ** ** The only tricky part is step (1) - how to compute an offset value to ** minimize the size of the output buffer. This is accomplished by testing ** all offset values and picking the one that results in the fewest number ** of escapes. To do that, we first scan the entire input and count the ** number of occurances of each character value in the input. Suppose ** the number of 0x00 characters is N(0), the number of occurances of 0x01 ** is N(1), and so forth up to the number of occurances of 0xff is N(255). ** An offset of 0 is not allowed so we don't have to test it. The number ** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number ** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth. ** In this way we find the offset that gives the minimum number of escapes, ** and thus minimizes the length of the output string. */ /* ** Encode a binary buffer "in" of size n bytes so that it contains ** no instances of characters '\'' or '\000'. The output is ** null-terminated and can be used as a string value in an INSERT ** or UPDATE statement. Use sqlite_decode_binary() to convert the ** string back into its original binary. ** ** The result is written into a preallocated output buffer "out". ** "out" must be able to hold at least 2 +(257*n)/254 bytes. ** In other words, the output will be expanded by as much as 3 ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead. ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.) ** ** The return value is the number of characters in the encoded ** string, excluding the "\000" terminator. ** ** If out==NULL then no output is generated but the routine still returns ** the number of characters that would have been generated if out had ** not been NULL. */ int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){ int i, j, e, m; unsigned char x; int cnt[256]; if( n<=0 ){ if( out ){ out[0] = 'x'; out[1] = 0; } return 1; }; } } if( out==0 ){ return n+m+1; } out[0] = e; j = 1; for(i=0; i<n; i++){ x = in[i] - e; if( x==0 || x==1 || x=='\''){ out[j++] = 1; x++; } out[j++] = x; } out[j] = 0; assert( j==n+m+1 ); return j; } /* ** Decode the string "in" into binary data and write it into "out". ** This routine reverses the encoding, e; unsigned char c; e = *(in++); i = 0; while( (c = *(in++))!=0 ){ if( c==1 ){ c = *(in++) - 1; } out[i++] = c + e; } return i; } #ifdef ENCODER_TEST #include <stdio.h> /* ** The subroutines above are not tested by the usual test suite. To test ** these routines, compile just this one file with a -DENCODER_TEST=1 option ** and run the result. */ int main(int argc, char **argv){ int i, j, n, m, nOut, nByteIn, nByteOut; unsigned char in[30000]; unsigned char out[33000]; nByteIn = nByteOut = 0; for(i=0; i<sizeof(in); i++){ printf("Test %d: ", i+1); n = rand() % (i+1); if( i%100==0 ){ int k; for(j=k=0; j<n; j++){ /* if( k==0 || k=='\'' ) k++; */ in[j] = k; k = (k+1)&0xff; } }else{ for(j=0; j<n; j++) in[j] = rand() & 0xff; } nByteIn += n; nOut = sqlite_encode_binary(in, n, out); nByteOut += nOut; if( nOut!=strlen(out) ){ printf(" ERROR return value is %d instead of %d\n", nOut, strlen(out)); exit(1); } if( nOut!=sqlite_encode_binary(in, n, 0) ){ printf(" ERROR actual output size disagrees with predicted size\n"); exit(1); } m = (256*n + 1262)/253; printf("size %d->%d (max %d)", n, strlen(out)+1,"); } fprintf(stderr,"Finished. Total encoding: %d->%d bytes\n", nByteIn, nByteOut); fprintf(stderr,"Avg size increase: %.3f%%\n", (nByteOut-nByteIn)*100.0/(double)nByteIn); } #endif /* ENCODER_TEST */
https://sqlite.org/src/artifact/fc8c51f0b61bc803
CC-MAIN-2019-47
refinedweb
1,225
70.84
Good news, all tables can be accessed in a Hive notebook. One simply needs to keep in mind that different connections correspond to different namespaces. To access table foo from another connection, prefix its name by the database name (for instance “db_bar”): SELECT count(*) FROM db_bar.foo Note that you'll need to remove the prefix when converting to a recipe. The database name is shown above the sql code area: «connected to db_bar (Hive)» and is distinct from the connection name. You can also find all database names by executing the SQL query show databases Note: you might also check the metastore sync: open the dataset, click settings → advanced → metastore: Synchronize. ©Dataiku 2012-2018 - Privacy Policy
http://answers.dataiku.com/221/access-tables-from-several-connections-in-a-hive-notebook
CC-MAIN-2019-35
refinedweb
117
63.39
Nokia QVGA TFT LCD for the Arduino Mega. Graphics Library (part 2 of 2) In part 1 of this two part series I presented the hardware design and build for the Nokia 6300 TFT that shows how we can connect it directly to the external memory interface of the Arduino Mega and that by doing so we achieve the fastest possible interface between the TFT and the Arduino MCU. Now the driver software has been updated to support the 2.4″ Nokia N82 LCD that I have reverse engineered. Everything that you can do on the 6300 screen, you can now also do on the N82. A TFT with the fastest transfer times possible on an Arduino deserves a software library to do it justice, and that’s what I hope to provide here. The software library provides the following functionality: - 24 bit bitmap graphics with LZ compression. - JPEG decoding support for images in flash or received over the serial port. - Fixed-width and proportional fonts. Four supplied in the library and an almost limitless amount available online. - Rectangles, filled, gradient filled and outlined. - Ellipses, filled and outlined. - The fastest available line drawing algorithm. - Single point plotting. - Character terminal with hardware scrolling. - PWM backlight driver. - Low power (sleep) mode. The library is implemented as a set of C++ templates. This design decision was taken to maximise the performance of the library as much as possible by isolating the choices that you make at design-time, such as the colour depth and orientation of the LCD and making those compile-time template parameters. This means that entire swathes of code simply do not get compiled making your program as fast and as small as it can be. To take a contrived example, a traditional library might have a function coded as follows: uint16_t getWidth() { if(_orientation==LANDSCAPE) return 320; else return 240; } Note that the code for the design-time decision regarding the LCD orientation is there at runtime even though it’s completely redundant. Contrast this with the template library which might have two function specialisations that look like this: template<> uint16_t Nokia6300::getWidth<LANDSCAPE> { return 320; } template<> uint16_t Nokia6300::getWidth<PORTRAIT> { return 240; } When the code is compiled the template specialisation for the orientation that you are not using simply never happens and the optimiser is presented with a trivial function that returns a constant. This is certain to be inlined by the optimiser meaning that the entire function call never happens at all! This design pattern is prevalent throughout my entire library. Anyway, you can forget the theory and there’s no need to be nervous about the sometimes obscure syntax that comes with templates because I take care of all that and expose only a very small number of simple types that you interact with. Let’s walk through the library learning by example. Hopefully these examples provide cut-and-paste code that you can use in your own programs. All of these examples are based around the popular and easy to use Arduino prototyping IDE. Advanced users will find that the library works just as well outside the IDE. My own development environment consists of avr-gcc 4.7.0, Eclipse Indigo and avr-libc 1.8.0 so compatibility with the most advanced toolchain to date is assured. Library Installation This library requires that you are using at least version 1.0 of the Arduino IDE. Download the library zip file from my downloads page and unzip it into your Arduino libraries directory. For me, that directory is C:\Program Files (x86)\arduino-1.0.1\libraries. Adjust that pathname to reflect where you installed the Arduino IDE on your computer. When you’re finished you should have a new xmemtft directory in the Arduino libraries directory. All of the demos presented below can be accessed under the Arduino File -> Examples -> xmemtft menu. A very basic sketch The following sketch shows the bare minimum that you need to do in order to initialise the LCD ready for work. #include "Nokia6300.h" using namespace lcd; typedef Nokia6300_Portrait_16M TftPanel; //typedef Nokia6300_Landscape_16M TftPanel; //typedef Nokia6300_Portrait_262K TftPanel; //typedef Nokia6300_Landscape_262K TftPanel; TftPanel *tft; void setup() { tft=new TftPanel; } void loop() { // use the panel here } All you need to do is uncomment the typedef line that corresponds to how you want to use the TFT in your project. Select a colour depth and orientation and you’re good to go. The class constructor for the panel object will take care of powering up the device and sending the initialisation sequence. The entire library is contained within a namespace called lcd. For code-clarity all these examples will import lcd into the global namespace with a using namespace lcd statement. Advanced users will know the reasons why they don’t want to do this in a real project. Typical use case with backlight Normally you’re going to want a backlight and you’ll want to clear down the TFT before you use it. Here’s how. #include "Nokia6300.h" using namespace lcd; typedef Nokia6300_Portrait_16M TftPanel; TftPanel *tft; DefaultBacklight *backlight;); } void loop() { // use the panel here } In the above example we show how to initialise the TFT and switch on the backlight. When the TFT is being initialised it contains random data. This is ugly for the user to see so we begin by ensuring that the backlight is off which makes the data on the panel invisible. We then initialise the TFT, clear down the display to a solid colour (black in this case) and then fade up the backlight smoothly. backlight=new DefaultBacklight; This is the line that creates the backlight and initialises it to zero brightness (off). The brightness is expressed as a percentage in the range 0..100. You must connect PWM pin #2 to the EN pin on the board. You can change both the PWM pin number and the default starting brightness percentage by changing how you declare and construct the Backlight class. See the source code for details. Note the use of the ColourNames namespace. Take a look at ColourNames.h to see the full set of available names. The names correspond to the X11 colours. Of course you can specify your own colour by supplying the hex value in the form 0xRRGGBB. Drawing rectangles Rectangles can be drawn as an outline in the foreground colour or filled with either the background or foreground colour. Here’s an example that shows all of that. To keep the code samples concise and focused on the example I’m going to show only the loop() function. You can take the above example code that demonstrates the backlight initialisation and just paste in the code for loop(). void loop() { Rectangle rc; // draw a red border around the display rc.X=rc.Y=0; rc.Width=tft->getXmax(); rc.Height=tft->getYmax(); tft->setForeground(ColourNames::RED); tft->drawRectangle(rc); // fill a rectangle in the center with blue rc.X=20; rc.Y=20; rc.Width=tft->getXmax()-40; rc.Height=tft->getYmax()-40; tft->setForeground(ColourNames::BLUE); tft->fillRectangle(rc); // erase a central rectangle from the blue one rc.X+=40; rc.Y+=40; rc.Width-=80; rc.Height-=80; tft->setBackground(ColourNames::BLACK); tft->clearRectangle(rc); // the end for(;;); } Unfortunately TFTs photograph and film very badly indeed. I’ll try my best but the images and videos on this page are not representative of the actual picture quality that your eye perceives. Bands and pattern effects seen in the photographs are not present on the actual screen and the colours are a lot more vivid – the rectangle that appears cyan in the picture below is actually a deep solid blue. The rectangle demo See how easy it is to draw on to the display? The graphics library remembers two colours, a foreground and a background colour. Most operations will use the foreground colour but some, such as clearRectangle will use the background colour. The Rectangle object is used to define the co-ordinates of the rectangle on the display. For clarity I’ve shown explicit initialisation of the members but there are constructors that allow you to initialise the members in various different ways. The whole library is const-correct so you should have no problem anonymously constructing the structure for one-off use like this: tft->clearRectangle(Rectangle(x,y,w,h)); Gradient filled rectangles The graphics library contains a linear gradient fill algorithm of my own design. This can be used to fill a rectangle with a gradient calculated from a starting and ending colour and a horizontal or vertical direction. Here’s some example code that illustrates the function in action. void loop() { doGradientFills(true); doGradientFills(false); } void doGradientFills(bool horz) { Rectangle rc; uint16_t i; static uint32_t colours[7]={ ColourNames::RED, ColourNames::GREEN, ColourNames::BLUE, ColourNames::CYAN, ColourNames::MAGENTA, ColourNames::YELLOW, ColourNames::WHITE, }; rc.Width=tft->getXmax()+1; rc.Height=(tft->getYmax()+1)/2; for(i=0;i<sizeof(colours)/sizeof(colours[0]);i++) { rc.X=0; rc.Y=0; tft->gradientFillRectangle(rc, horz ? HORIZONTAL : VERTICAL, ColourNames::BLACK, colours[i]); rc.Y=rc.Height; tft->gradientFillRectangle(rc, horz ? HORIZONTAL : VERTICAL, colours[i], ColourNames::BLACK); delay(2000); } } It’s unfortunate that I have to pass the direction as a boolean to the doGradientFills function but there is a bug in the Arduino IDE that prevents an enum value being passed to a function in your sketch. Ideally I would have liked to have provided the gradient fill functions as template specialisations for horizontal and vertical but due to a limitation in the C++ standard around specialisation of template members of template classes I can’t do it without some ugly hacking. There is an API change from version 1.0.1 onwards. gradientFillRectangle() now takes start and end colours as parameters instead of using the foreground and background colours. You can watch a demo video of the gradient fill in action. As you can see it performs very well. Drawing lines Drawing lines follows much the same pattern as drawing rectangles. Here’s some sample code. void loop() { Point p1,p2; int i; TftPanel::TColour randomColour; for(i=0;i<1000;i++) { p1.X=rand() % tft->getXmax(); p1.Y=rand() % tft->getYmax(); p2.X=rand() % tft->getXmax(); p2.Y=rand() % tft->getYmax(); randomColour=(((uint32_t)rand()<<16) | rand()) & 0xffffff; tft->setForeground(randomColour); tft->drawLine(p1,p2); } tft->clearScreen(); } This example shows a loop drawing 1000 random coloured lines at random positions on the display. Perhaps of interest here is the type name used for holding colour variables. TftPanel::TColour. It actually resolves down to uint32_t which you can use instead if you like. The type name is for portability if and when I use this library to control other TFTs. The algorithm used is the Extremely fast line drawing algorithm from here. Please respect the author’s copyright: Freely useable in non-commercial applications as long as credits to Po-Han Lin and link to is provided in source code and can been seen in compiled executable. Commercial applications please inquire about licensing the algorithms. You can watch a video of the line drawing demo in action. The performance is very good. Ellipses, filled and outlined An ellipse is defined by the position of the center of the shape and the two X and Y radii. A circle is just a special case of an ellipse so this is the method you should use to draw or fill circles. void loop() { Size s; Point p; // draw an outline of ellipse around the edge p.X=(tft->getXmax()+1)/2; p.Y=(tft->getYmax()+1)/2; s.Width=((tft->getXmax()+1)/2)-1; s.Height=((tft->getYmax()+1)/2)-1; tft->setForeground(ColourNames::GOLDENROD); tft->drawEllipse(p,s); // fill a circle in the center tft->setForeground(ColourNames::INDIANRED1); tft->fillEllipse(p,Size(100,100)); // finished for(;;); } A photograph of the above demo output Drawing text The graphics library supports fixed-width and proportional bitmap fonts (the former being merely a special case of the latter). TrueType Fonts can be downloaded from the bitmap fonts section of DaFont and converted to a C++ header file that you can include in your code. The Windows font conversion utility is included in the zip file that you downloaded. Let’s start with an example that shows a text string being repeatedly displayed at various positions on the screen. I’ll show the whole sketch this time because there are additions to the includes and to the initialisation. #include "Nokia6300.h" #include "Font_volter_goldfish_9.h" //#include "Font_apple.h" // fixed width //#include "Font_kyrou9_regular_8.h" //#include "Font_kyrou9_bold_8.h" //#include "Font_tama_ss01.h" using namespace lcd; typedef Nokia6300_Portrait_16M TftPanel; TftPanel *tft; DefaultBacklight *backlight; Font *font;); // create the font to use later font=new Font_VOLTER__28GOLDFISH_299; // font=new Font_APPLE8; // font=new Font_KYROU_9_REGULAR8; // font=new Font_KYROU_9_REGULAR_BOLD8; // font=new Font_TAMA_SS0117; // select the font so we can use the // streaming operators *tft << *font; } void loop() { int i; const char *str="The quick brown fox"; Size size; Point p; TftPanel::TColour randomColour; size=tft->measureString(*font,str); for(i=0;i<3000;i++) { p.X=rand() % (tft->getXmax()-size.Width); p.Y=rand() % (tft->getYmax()-size.Height); randomColour=(((uint32_t)rand() << 16) | rand()) & 0xffffff; tft->setForeground(randomColour); *tft << p << str; } } We need to add an include for each font header file that you want to use. Uncomment one of the #include lines and put it at the top of your sketch with the other #include directives. In the setup() function we construct the font class that we’re going to use. The obscure looking name of the class is auto-generated by the font conversion utility and can be found by looking in the header file. font=new Font_VOLTER__28GOLDFISH_299; // font=new Font_APPLE8; // font=new Font_KYROU_9_REGULAR8; // font=new Font_KYROU_9_REGULAR_BOLD8; // font=new Font_TAMA_SS0117; After constructing the Font object it’s ready to use. This demonstration uses the stream operator << to control text output. These operators are much more convenient than calling the writeString and measureString member functions directly because you can chain together multiple operations in one line. The stream operators can take a font object to change the font that will be used next, a point object to change where the next output will be and of course a string, character, integer or floating point number to write. The current output location is automatically updated in the X direction so you can write out multiple strings and have them tacked on end-to-end. The default precision for floating point numbers (double’s) is 5 decimal places. If you want to override that you can do so like this example where I show PI to 3 decimal places: *tft << DoublePrecision(3.14159,3); There is a double-to-string conversion in the arduino standard libraries but this version is 17% faster at the expense of 40 bytes of SRAM for an internal lookup table. For the curious, the implementation is a port of this open source library. Here’s a video that shows the demo code in action. The font conversion utility There are hundreds of free bitmap fonts available online that you can browse and then convert for use in your sketch. I use the DaFont website. Only the pixel/bitmap fonts are compatible. The vector fonts require a sophisticated anti-aliasing engine to make them look as great as they do, and typically they include special algorithms that help them to maintain their looks at small font sizes. Browse to the Arduino library installation directory and navigate to the xmemtft/utility/fontconv sub-directory. Run FontConv.exe. Font conversion utility (click for larger) Follow these instructions to convert and save a font. - Find a font you like and obtain the .ttf file for it. Save this to somewhere permanent on your system because the font conversion utility saves a reference to the pathname so it can read the font back later on. - Click Browse for font file… and load it. If the font contains a great many characters then there may be a delay while it is processed. - Select the characters you want to include when you save it. Don’t include characters you don’t use – in an embedded system that’s just a waste of memory. I have included Select all 7-bit and Select all alphanumeric buttons to help you select the most common characters. - Set the correct font size. Most bitmap fonts look hopeless at any size other than the one they were designed for. - If the characters are not centered in their boxes or the boxes are not wide enough then adjust the Extra Lines and Offset parameters until it looks right. - If the characters are tight up against the edges of their boxes (like in the screenshot above) then add on a pixel or two of Character spacing so that the characters will appear spaced apart on screen. There is no preview for this option. - Select the Arduino target button and click Save. The adjustments that you have made are saved in an XML file and the font source code in a header file. For example, enter MyFont as the name to save and you will get MyFont.h and MyFont.xml on disk. - You can now include the font header file in your project. If, in the future you need to make adjustments to the saved font then use the Load option and browse for the XML file that you saved in the above instructions. Fonts are saved as a packed bitstream with no padding or wastage at all so flash memory usage is kept to a minimum. Bitmap graphics The graphics library supports bitmap graphics compiled into SRAM or flash, compressed or uncompressed. A utility is provided to convert almost any popular format to an internal format that you can include directly into your project. The bitmap conversion utility Bitmaps have to be converted from the efficient file storage format such as PNG, JPEG etc. to an internal format for optimised for transferring quickly from memory to the display. A Windows command-line utility is provided for this purpose, called bm2rgbi.exe. You can find it in the xmemtft/utility/bm2rgbi sub-directory of your Arduino libraries folder. The syntax is as follows: bm2rgbi <input-file> <output-file> mc2pa8201 [16|262] An example would be: bm2rgbi picture.png picture.bin mc2pa8201 16 This would convert the file picture.png to a new file picture.bin with 16M colours ready for including in your program. Uncompressed bitmaps Uncompressed bitmaps are good for small icons and are the fastest to display. Even simple animation is possible with these and I will demonstrate that in this example code. The drawback is the amount of flash memory required to store the bitmap. Let’s take a look at a complete example that shows a bitmap being animated by being bounced around the screen. #include "Nokia6300.h" using namespace lcd; // set up in Landscape mode typedef Nokia6300_Landscape_16M TftPanel; TftPanel *tft; DefaultBacklight *backlight; // reference to the bitmap pixels and size in flash extern const uint32_t GlobePixels; extern const uint32_t GlobePixelsSize; // some program control variables int8_t xdir,ydir; Bitmap bm; Size panelSize; Point bmPos;); // set up the bitmap descriptor bm.Dimensions.Width=66; bm.Dimensions.Height=66; bm.DataSize=GET_FAR_ADDRESS(GlobePixelsSize); bm.Pixels=GET_FAR_ADDRESS(GlobePixels); // store the panel width and height panelSize.Width=tft->getWidth(); panelSize.Height=tft->getHeight(); // starting co-ordinates and directions bmPos.X=(panelSize.Width/2)-33; bmPos.Y=(panelSize.Height/2)-33; xdir=ydir=1; } void loop() { // draw the bitmap tft->drawUncompressedBitmap(bmPos,bm); // move it bmPos.X+=xdir; bmPos.Y+=ydir; // if the edge is hit, bounce it back if(bmPos.X==panelSize.Width-66) xdir=-1; else if(bmPos.X==0) xdir=1; if(bmPos.Y==panelSize.Height-66) ydir=-1; else if(bmPos.Y==0) ydir=1; } You’ve seen most of this before. Let’s take a look at the important points related to bitmaps. extern const uint32_t GlobePixels; extern const uint32_t GlobePixelsSize; The pixels are stored in flash and we need to know where they are and how much memory they occupy. These two extern references will resolve to those values. We’ll see later how we get the pixels compiled into your program. bm.Dimensions.Width=66; bm.Dimensions.Height=66; bm.DataSize=GET_FAR_ADDRESS(GlobePixelsSize); bm.Pixels=GET_FAR_ADDRESS(GlobePixels); Before we can display a bitmap we need to set up a structure that tells the library about it. The structure needs to receive the pixel width and height and the external references that we declared before. The GET_FAR_ADDRESS macro is a very useful hack that allows us to reference 24-bit addresses in flash. It’s required because AVR pointers are normally 16-bits wide and without this we would never be able to reference data above 64K in flash… kind of pointless when we’ve got 128K or 256K to play with. tft->drawUncompressedBitmap(bmPos,bm); This is where we draw the bitmap. The method takes a Point structure telling it where to display the bitmap and a reference to the bitmap structure itself that we prepared above. Now we need to explain how we include that .bin converted bitmap in your compiled program. There are a couple of ways to do this and I’ve selected a method that means you don’t have to hardcode the start address and it should work with any size of bitmap limited only by your flash memory size, and it doesn’t matter if it ends up above the 64K memory boundary. void _asmStub() { __asm volatile( ".global GlobePixels nt" ".global GlobePixelsSize nt" "GlobePixels: nt" ".incbin "globe64x64.bin" nt" "GlobePixelsSize=.-GlobePixels nt" ".balign 2 nt" ); } In the Arduino IDE I include this hack in a separate tab. What it’s doing is using the GNU assembler .incbin directive to include arbitrary binary into your program. Two symbols are declared (GlobePixels and GlobePixelsSize) and made global so that the C++ code can see them. Wrapping it all in a function that will never be called (_asmStub) ensures that it ends up in flash with your code. Don’t ever call this function because the MCU will try to execute your binary picture as program code! Here’s a video showing the demo code in action: Compressed Bitmaps Large bitmaps cost memory. An uncompressed QVGA bitmap would occupy 320 x 240 x 3 = 230400 bytes. Far too much for our little MCU. Thankfully we support compression of bitmaps using the tiny liblzg codec. The level of compression is almost identical to PNG – that’s very good indeed and easily suitable for full-screen bitmaps. There is a cost to using the LZG compression. The authors claim that the algorithm does not require any memory during decompression but this is only true if it’s set up to decompress to RAM because the algorithm needs random access to a preceding ‘window’ of bytes from the decompressed stream, the size of which is determined by the level of compression that was selected. I have taken steps to limit the size of the compression window to 2Kb and implemented it as a ring buffer in the decompressor. Therefore the algorithm requires 2Kb of stack space to run which is de-allocated when it’s completed. To get a compressed bitmap we need to add the -c flag to the bm2rgbi conversion utility, for example: bm2rgbi picture.png picture.bin mc2pa8201 16 -c In this next example we will really showcase how our little Arduino can play with the big boys by simulating a media player interface complete with a live 16 channel ‘graphic equaliser’ that displays the amplitudes of the frequency ranges in an input signal calculated in real-time by the Fast Fourier Transform (FFT). The compressed bitmap that we will use for a background #include "Nokia6300.h" using namespace lcd; // the bitmaps we'll use extern const uint32_t mediaPlayerOrigin; extern const uint32_t mediaPlayerSize; extern const uint32_t screenStripOrigin; extern const uint32_t screenStripSize; // set up in Landscape mode typedef Nokia6300_Landscape_16M TftPanel; TftPanel *tft; DefaultBacklight *backlight; Bitmap bmBack; // the FFT funciton extern int fix_fft(char fr[],char fi[],int m,int inverse); // constants used here enum { CHANNELS=16 }; void setup() { Bitmap bm; // create a backlight manager and switch off the backlight // so the user doesn't see the random data that can appear // during initialisation // create a backlight controller and use it // to switch the backlight off backlight=new DefaultBacklight; backlight->setPercentage(0); // reset and initialise the panel tft=new TftPanel; // clear to black tft->setBackground(ColourNames::WHITE); tft->clearScreen(); // the background gradient bmBack.Dimensions.Width=10; bmBack.Dimensions.Height=78; bmBack.Pixels=GET_FAR_ADDRESS(screenStripOrigin); bmBack.DataSize=GET_FAR_ADDRESS(screenStripSize); // the bar colour tft->setForeground(0x38808a); // load the media player background bm.Dimensions.Width=316; bm.Dimensions.Height=200; bm.Pixels=GET_FAR_ADDRESS(mediaPlayerOrigin); bm.DataSize=GET_FAR_ADDRESS(mediaPlayerSize); tft->drawCompressedBitmap(Point(2,20),bm); // fade up the backlight to 100% // in 4ms steps (400ms total) backlight->fadeTo(100,4); } void loop() { uint8_t channels1[CHANNELS],channels2[CHANNELS]; memset(channels2,0,sizeof(channels2)); for(;;) { getSamples(channels1); plotSamples(channels1,channels2); getSamples(channels2); plotSamples(channels2,channels1); } } void getSamples(uint8_t *channels) { int i,val; uint32_t now,last; char data[128],im[128]; uint16_t newvalue; // capture 128 samples last=0; i=0; while(i<128) { // get a sample (at best) each millisecond if((now=millis())!=last) { val=analogRead(0); data[i]=(val/4)-128; im[i]=0; last=now; i++; } } // do the fft fix_fft(data,im,7,0); // compute the amplitude for(i=0;i<64;i++) data[i]=sqrt(data[i]*data[i]+im[i]*im[i]); // average down to 16 channels and scale the amplitude for(i=0;i<64;i+=4) { newvalue=((uint16_t)data[i]+ (uint16_t)data[i+1]+ (uint16_t)data[i+2]+ (uint16_t)data[i+3])/4; channels[i/4]=min(78,newvalue*4); } } void plotSamples(uint8_t *channels,uint8_t *previous) { int16_t i; Rectangle rc; Point bmPoint(26,58); rc.X=26; rc.Width=10; for(i=0;i<CHANNELS;i++) { if(channels[i]!=previous[i]) { if(channels[i]<previous[i]) { // replace the gradient background behind the bar // because we need to show a shorter bar tft->drawUncompressedBitmap(bmPoint,bmBack); // the new bar will be this tall rc.Height=channels[i]; } else { // the new bar is taller, we fill up from the // previous to the new height rc.Y=136-channels[i]; rc.Height=channels[i]-previous[i]; } // draw the new bar rc.Y=136-channels[i]; tft->fillRectangle(rc); } rc.X+=11; bmPoint.X+=11; } } This code depends on the Modified 8-bit FFT in C code posted on the old Arduino Forum. Most of the example code is dedicated to the program logic. I’ve highlighted the lines where we use bitmaps. A compressed bitmap is used for the media player interface because without compression it would be about 190Kb. With LZG compression it’s a mere 32Kb. As before, the raw bitmaps are included into the program code using some inline assembler like this example. Adjust the filenames of the .bin files to match your system. void _asmStub() { __asm volatile( ".global mediaPlayerOrigin nt" ".global mediaPlayerSize nt" ".global screenStripOrigin nt" ".global screenStripSize nt" "mediaPlayerOrigin: nt" ".incbin "MediaPlayer.bin" nt" "mediaPlayerSize=.-mediaPlayerOrigin nt" "screenStripOrigin: nt" ".incbin "ScreenStrip.bin" nt" "screenStripSize=.-screenStripOrigin nt" ".balign 2 nt" ); } Here’s a video showing the demo code in action JPEG images I’m pleased to announce that as from version 2.1.0 of the driver I now support JPEG images courtesy of the excellent picojpeg library. The author of picojpeg has gone to great lengths to limit SRAM memory use but it will still cost you about 2.5Kb to call the JPEG decoder. The original version of the library would take that 2.5Kb as global variables which meant that you pay the memory cost for the lifetime of your program, even when you’re not actually decoding a JPEG. I have modified picojpeg so that all but about 200 bytes of that memory comes off the stack and is only consumed whilst a JPEG is being decoded. Another key limitation is that progressive JPEGs are not supported. Displaying JPEG images from flash We can display JPEG images that are compiled into flash memory. My sample images take up about 15Kb each at full-screen (240×320) and 70% quality. Here’s an abbreviated sample that shows the technique: #include "NokiaN82.h" using namespace lcd; // Graphics compiled in to flash extern const uint32_t Test0Pixels,Test0PixelsSize; void loop() { // show the demo with no fade out/in between frames showJpeg( GET_FAR_ADDRESS(Test0Pixels), GET_FAR_ADDRESS(Test0PixelsSize) ); } void showJpeg(uint32_t pixelData,uint32_t pixelDataSize) { // draw the image JpegFlashDataSource ds(pixelData,pixelDataSize); tft->drawJpeg(Point(0,0),ds); } drawJpeg is the key function. It takes a point location on the screen of where to draw the jpeg and a reference to the data-source object that tells the drawing function where the jpeg data is, and how much of it there is. As in all the previous bitmap examples the pixel data is included directly into flash using a little assembly language file. You can see the entire demo code in the driver zip file. Here’s a video that shows the JPEG decoder in action: Displaying JPEG images over the serial port I have included driver support for displaying JPEG images streamed over the serial port from a connected computer. This frees your application from the memory limitations of the Arduino Mega and opens up the possibility of creating applications such as digital photo frames to showcase your portfolio to unsuspecting family and friends. Serial support is a little more involved than flash support because we have to marshal the data between the two ends of the wire, ensuring that both ends stay in sync with each other. Here’s a sample application in its entirety: #include "NokiaN82.h" #include "Font_volter_goldfish_9.h" using namespace lcd; // We'll be working in portrait mode, 262K typedef NokiaN82_Portrait_262K LcdAccess; LcdAccess *tft; DefaultBacklight *backlight; Font *font; void setup() { // 1Mb/s serial rate Serial.begin(1000000); // create a backlight manager and switch off the backlight // so the user doesn't see the random data that can appear // during initialisation backlight=new DefaultBacklight; backlight->setPercentage(0); // create and initialise the panel and font tft=new LcdAccess; font=new Font_VOLTER__28GOLDFISH_299; // clear to black tft->setBackground(ColourNames::BLACK); tft->setForeground(ColourNames::WHITE); tft->clearScreen(); // fade up the backlight to 100% in 4ms steps // (400ms total) now that we are in a good state backlight->fadeTo(100,4); // select the font used througout *tft << *font; } void loop() { int32_t jpegSize; // show a prompt and wait for the file size to arrive tft->clearScreen(); *tft << Point(0,tft->getYmax()-font->getHeight()) << "Awaiting jpeg file size"; jpegSize=readJpegSize(); // show a new prompt and receive the jpeg data tft->clearScreen(); *tft << Point(0,tft->getYmax()-font->getHeight()) << "Receiving " << jpegSize << " bytes"; // 63 is the size of each data chunk that we receive // before sending an ack back to the sender. The // size should be less than the receive ring buffer // capacity (64 on the mega, 16 on the standard) JpegSerialDataSource ds(Serial,jpegSize,63); tft->drawJpeg(Point(0,0),ds); // wait 5 seconds and then go around and read // another file delay(5000); } uint32_t readJpegSize() { uint32_t size; // read directly on to the 4-byte size. that implies // that the data must be sent little-endian (LSB first) while(Serial.readBytes( reinterpret_cast<char *>(&size),4)!=4 ); return size; } The key points are that you first initialise the serial link with the desired board rate, then you must initialise a JpegSerialDataSource with the serial object, the size of the data that you are going to transmit, and the size of each chunk of data to receive before sending back a ‘you may continue’ flow-control byte to the sender. This last number, the chunk size, is important. The Arduino Mega library can, by default, receive 63 bytes before its internal buffer overflows. Therefore the ideal chunk size is 63, and that’s what we’ll use. How you get the jpeg data size is up to you. In my demo I choose to transmit the size as a 32-bit number ahead of the data itself and you can see in readJpegSize that I just receive those bytes directly on to a uint32_t and return it. Now for the other end. I created a small C# command line utility to do the work of sending the jpeg over the serial port. In my demo code I use the Arduino’s built in USB connection, the same one you use to flash your programs. using System; using System.IO.Ports; using System.IO; namespace SendJpeg { /* * main program class. example usage: * sendjpeg.exe mytest.jpg com5 1000000 63 */ class Program { static void Main(string[] args) { try { if (args.Length != 4) { Console.WriteLine("usage: sendjpeg <jpegfile> <com-port> <baud-rate> <chunk-size>"); return; } // open the port Console.WriteLine("Opening port "+args[2]); SerialPort serialPort = new SerialPort(args[1],int.Parse(args[2]),Parity.None,8,StopBits.One); serialPort.Handshake = Handshake.None; serialPort.Open(); // get the size of the file to send FileInfo fi=new FileInfo(args[0]); long size=fi.Length; Console.WriteLine("Writing file size ("+size+") bytes"); // send the file size, LSB first byte[] buffer=new byte[4]; buffer[3]=(byte)((size >> 24) & 0xff); buffer[2]=(byte)((size >> 16) & 0xff); buffer[1]=(byte)((size >> 8) & 0xff); buffer[0]=(byte)(size & 0xff); serialPort.Write(buffer,0,4); // get ready to send the file buffer=new byte[1000]; long remaining=size; int count,value; int chunkAvailable,chunkSize=int.Parse(args[3]); Console.WriteLine("Writing file data"); using(BufferedStream bs=new BufferedStream(new FileStream(args[0],FileMode.Open,FileAccess.Read))) { chunkAvailable=chunkSize; while(remaining>0) { // read either 1000 or what's left count=(int)(remaining<1000 ? remaining : 1000); bs.Read(buffer,0,count); for(int i=0;i<count;i++) { // send a byte serialPort.Write(buffer,i,1); // if we have just sent the last of a chunk, wait for the ack if(--chunkAvailable==0) { value=serialPort.ReadByte(); if(value!=0xaa) throw new Exception("Unexpected chunk acknowledgement"); // new chunk on its way chunkAvailable=chunkSize; } } remaining-=count; Console.Write("."); } } Console.WriteLine("\nDone."); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } } Example usage for this tool is: SendJpeg.exe test.jpg com5 1000000 63 You can find the Visual Studio source code in the JpegSerial example directory, and the compiled executables are in the utility directory. The serial port support is not limited to actual serial ports. It should work with any peripheral that has a driver that derives from the Arduino Stream class. Let’s see a video of the serial jpeg link in action. Naturally this mode of operation is not as fast as when the data is compiled into flash because the little Arduino has to devote some time to receiving data over the wire. Hardware Scrolling The Nokia 6300 supports hardware scrolling. Well, they call it hardware scrolling but no pixel moving takes place. It’s actually simulated scrolling by offsetting the rows by a user-defined amount. For example, a scroll amount of 1 means that row zero is actually output one row down and so on until you get to the last row that is wrapped around and will appear at the top where row zero usually is. Hardware scrolling is officially supported in portrait mode but the current batch of screens that I’ve tested also support it in landscape mode where the scroll direction comes out as horizontal. Here’s a demo that shows the hardware scrolling feature in action: #include "Nokia6300.h" #include "Font_volter_goldfish_9.h" using namespace lcd; typedef Nokia6300_Portrait_16M TftPanel; TftPanel *tft; DefaultBacklight *backlight; Font *font; int scrollPos,scrollDisp; void setup() { int numRows,i; Point p; // create a backlight controller and use it // to switch the backlight off backlight=new DefaultBacklight; backlight->setPercentage(0); // reset and initialise the panel tft=new TftPanel; // create the font font=new Font_VOLTER__28GOLDFISH_299; // set scroll parameters tft->setScrollArea(0,320); tft->setForeground(ColourNames::WHITE); scrollPos=0; scrollDisp=1; // clear to black tft->setBackground(ColourNames::BLACK); tft->clearScreen(); // fade up the backlight to 100% // in 4ms steps (400ms total) backlight->fadeTo(100,4); // print the text numRows=((tft->getYmax()+1)/font->getHeight())/3; p.X=0; for(i=0;i<numRows;i++) { p.Y=(numRows+i)*font->getHeight(); tft->writeString(p,*font,"Test text row"); } } void loop() { tft->setScrollPosition(scrollPos); scrollPos+=scrollDisp; if(scrollPos==100) scrollDisp=-1; else if(scrollPos==0) scrollDisp=1; delay(5); } Sleep mode The TFT supports a sleep mode in which the display and much of the controller circuitry is powered down, reducing the current usage to a few microamps. The backlight should also be switched off in sleep mode since it’s the biggest current drain. In sleep mode the content of the on-board graphics RAM is preserved so that when you wake up you don’t have to refresh the display. Here’s a demo of the sleep mode in action: #include "Nokia6300.h" using namespace lcd; typedef Nokia6300_Portrait_16M TftPanel; TftPanel *tft; DefaultBacklight *backlight; void setup() { Rectangle rc; //); // fill a rectangle in the center with green rc.X=20; rc.Y=20; rc.Width=tft->getXmax()-40; rc.Height=tft->getYmax()-40; tft->setForeground(ColourNames::RED); tft->fillRectangle(rc); } void loop() { // wait 3 seconds delay(3000); // fade out the backlight and go to sleep backlight->fadeTo(0,4); tft->sleep(); // wait 2 seconds delay(2000); // wake up and fade back in tft->wake(); backlight->fadeTo(100,4); } Using the TFT as a character terminal I have provided a high level class that builds on the primitives provided by the graphics library to implement a character terminal that you can use to output strings to. The terminal class takes care of maintaining a cursor position and implements hardware scrolling when used in portrait mode. The ‘<<' operator is overloaded for output in a manner that imitates the familiar way it's used with C++ streams. Here’s a demo that illustrates the terminal class being used. #include "Nokia6300.h" #include "Font_apple.h" using namespace lcd; typedef Nokia6300_Portrait_16M TftPanel; typedef Nokia6300_Terminal_Portrait_16M TerminalAccess; TftPanel *tft; DefaultBacklight *backlight; TerminalAccess *terminal; Font *font; // demo text static const char __attribute__((progmem)) demoText[] PROGMEM=" Lorem ipsum dolor sit amet, consectetur adipiscing elit.nn Mauris malesuada ornare mi, id semper eros congue nec.nn Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean nec arcu ac lorem pulvinar pretium. Etiam at ultricies est.nn Nunc nisl justo, ullamcorper vitae laoreet sit amet, tristique id est. Nulla imperdiet, massa et tincidunt ultricies, quam magna blandit nulla, vel aliquam tellus ipsum nec erat.nn Suspendisse dignissim consectetur iaculis. Morbi vel felis quis nibh placerat porttitor eu dignissim mauris. Nunc posuere tincidunt felis elementum molestie.nn Nunc nulla sem, imperdiet nec ullamcorper at, feugiat eu metus. Nunc congue congue lectus, sed accumsan metus hendrerit in.nn Nulla non vestibulum leo. Nam sodales dignissim libero non ultrices.nn Maecenas eget justo nunc. Aliquam erat volutpat. Ut pulvinar, massa id adipiscing blandit, ligula purus rhoncus ante, sed scelerisque tortor magna gravida libero.nn Curabitur eget neque nec ante porttitor ornare. Morbi congue fermentum pellentesque. Suspendisse nisi tellus, suscipit sed congue ac, accumsan ac quam.nn Nullam ullamcorper purus vitae diam vestibulum ultrices. Nullam vel libero ut justo imperdiet lobortis. Nullam sed lorem vitae nulla mattis faucibus.nn Sed a turpis non turpis ullamcorper hendrerit. Nulla et magna ac nunc tristique fermentum eget in ante.";(); // create a terminal implementation // the font must be fixed width font=new Font_APPLE8; terminal=new TerminalAccess(tft,font); tft->setForeground(ColourNames::WHITE); tft->setBackground(ColourNames::BLACK); // fade up the backlight to 100% // in 4ms steps (400ms total) backlight->fadeTo(100,4); } void loop() { const char *ptr; int i; char c; terminal->clearScreen(); // demo the terminal as a progress indicator *terminal << "Loading assets...n"; for(i=0;i<=100;i++) { terminal->clearLine(); *terminal << i << '%'; delay(50); } // demo the terminal as an output device terminal->writeString("nn"); ptr=demoText; for(c=pgm_read_byte(ptr++);c;c=pgm_read_byte(ptr++)) { *terminal << c; delay(rand() % 60); } } You can watch a video that shows the character terminal in action. Let’s take a look at the terminal-specific code from the above example. typedef Nokia6300_Terminal_Portrait_16M TerminalAccess; TerminalAccess *terminal; terminal=new TerminalAccess(tft,font); Here is where we declare the implementation of the terminal that we will use. It must match the orientation and colour depth of the TFT class. The font that you use must be fixed width. terminal->clearScreen(); // demo the terminal as a progress indicator *terminal << "Loading assets...n"; for(i=0;i<=100;i++) { terminal->clearLine(); *terminal << i << '%'; delay(50); } Here the demo simulates a percentage counter from 0 to 100. This is intended to show how the clearLine() method can be used to repeatedly show a changing status line. for(c=pgm_read_byte(ptr++);c;c=pgm_read_byte(ptr++)) { *terminal << c; delay(rand() % 60); } This part of the demo ‘types’ out some paragraphs from the lorem ipsum text that will be familiar to designers the world over. When the text hits the bottom of the screen it will be hardware-scrolled to make room for the next line. Big graphics library demo All of the above techniques are demonstrated together in the GraphicsLibraryDemo example available in the Arduino IDE. Here’s a video of the big demo in action..
http://andybrown.me.uk/wk/2012/06/04/nokia-qvga-tft-lcd-for-the-arduino-mega-graphics-library-part-2-of-2/
CC-MAIN-2014-52
refinedweb
6,884
54.63
1. CSS box model and weird box model 1、**Standard box modelinwidthRefers to the content areacontentWidth of the;heightRefers to the content areacontentThe height of the. Size of box under standard box model = content + border + padding + margin 2、Weird box modelMediumwidthThe width of border and padding refers to the total width of border and padding;heightIt refers to the total height of content, border and inner margin Size of box in weird box model = width (content + border + padding) + margin 3. Which box model to use in IE8 + browser can be triggered by box sizing (a new attribute in CSS), The default value is content box, which is the standard box model; If box sizing is set to border box, the IE box model is used 4、box-shadow: h-shadow v-shadow blur spread color inset; H-shadow and v-shadow must be. Position of horizontal and vertical shadows. Assignment is allowed. Blur optional, blur distance. Spread optional, the size of the shadow. Color optional, the color of the shadow. Inset optional. Change the outer shadow to the inner shadow. 2. New features of HTML5 in tags, attributes, storage and APIs • label: Add semantic tags( aside / figure / section / header / footer / navEtc.), Add multimedia Tags videoand audio, which makes the style and structure more separated • properties: Enhanced forms, mainly enhanced inputType attribute of; metaAdd charset to set the character set; scriptAdd async to load scripts asynchronously • storage: increase localStorage、 sessionStorageand indexedDB, introduced application cacheCaching web and Applications • API: add Drag and drop API、 Geographic location、 Svg drawing、 Canvas drawing、 Web Worker、 WebSocket 3. CSS3 animation 1: Transition animation — transitions 1: Transition animation transitions meaning: in CSS3, the transitions function realizes the animation function by smoothly transiting an attribute of an element from one attribute value to another within a specified time. The transitions attribute is used as follows: transition: property | duration | timing-function | delay transition-property:Represents a smooth transition to that attribute. transition-duration:Indicates how long it takes to complete the smooth transition of attribute values. transition-timing-functionIndicates how to smooth the transition. transition-delay:Defines how long the transition animation is delayed. The default value is all 0 ease 0 Browser support:Ie10, Firefox 4 +, Opera 10 +, Safari 3 + and chrome 8+ The following is a demo of the transitions transition function: The HTML code is as follows: < div transitions transition function < / div > The CSS code is as follows: .transitions { -webkit-transition: background-color 1s ease-out; -moz-transition: background-color 1s ease-out; -o-transition: background-color 1s ease-out; }.transitions:hover { background-color: #00ffff; } The effect is as follows: Transitions transition function If you want to transition multiple attributes, you can use comma separation, as shown in the following code: div { -webkit-transition: background-color 1s linear, color 1s linear, width 1s linear;} 2. We can use the transitions function to smoothly transition multiple attribute values at the same time. The following HTML code: <h2>Transitions smooth transition multiple attribute values < / H2 > < div transitions smooth transition multiple attribute values < / div > CSS code is as follows: .transitions2 { background-color:#ffff00; color:#000000; width:300px; -webkit-transition: background-color 1s linear, color 1s linear, width 1s linear; -moz-transition: background-color 1s linear, color 1s linear, width 1s linear; -o-transition: background-color 1s linear, color 1s linear, width 1s linear; }.transitions2:hover { background-color: #003366; color: #ffffff; width:400px; } The effect is as follows: Transitions smoothes the transition of multiple attribute values Transitions smoothes the transition of multiple attribute values be careful:Transition timing function indicates what method is used for smooth transition. Its values are as follows: There is ease | linear | ease in | ease out | ease in out | cubic Bezier For now, we can understand that c-out and so on can be ignoredmeaning; ease:First fast and then slow down; ease-in:Slow before fast easy-out:Fast before slow easy-in-out:Slow first, then fast, then slow Understand the above attribute values, as shown in the following Demo: The HTML code is as follows: <div id="transBox" class="trans_box"> <div class="trans_list ease">ease</div> <div class="trans_list ease_in">ease-in</div> <div class="trans_list ease_out">ease-out</div> <div class="trans_list ease_in_out">ease-in-out</div> <div class="trans_list linear">linear</div></div> The CSS code is as follows: .trans_box { background-color: #f0f3f9; width:100% }.trans_list { width: 30%; height: 50px; margin:10px 0; background-color:blue; color:#fff; text-align:center; }.ease { -webkit-transition: all 4s ease; -moz-transition: all 4s ease; -o-transition: all 4s ease; transition: all 4s ease; }.ease_in { -webkit-transition: all 4s ease-in; -moz-transition: all 4s ease-in; -o-transition: all 4s ease-in; transition: all 4s ease-in; }.ease_out { -webkit-transition: all 4s ease-out; -moz-transition: all 4s ease-out; -o-transition: all 4s ease-out; transition: all 4s ease-out; }.ease_in_out { -webkit-transition: all 4s ease-in-out; -moz-transition: all 4s ease-in-out; -o-transition: all 4s ease-in-out; transition: all 4s ease-in-out; }.linear { -webkit-transition: all 4s linear; -moz-transition: all 4s linear; -o-transition: all 4s linear; transition: all 4s linear; }.trans_box:hover .trans_list{ margin-left:90%; background-color:#beceeb; color:#333; -webkit-border-radius:25px; -moz-border-radius:25px; -o-border-radius:25px; border-radius:25px; -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } The effect is as follows: ease ease-in ease-out ease-in-out linear 2: Animations function: define multiple keyframes The animations function is the same as the transitions function, which realizes the animation effect by changing the attribute value of the element. The difference between them is that the transition function can only be used by specifying the start value and end value of the attribute. Then the animation effect is realized by smooth transition between the two attribute values, so the complex animation effect cannot be realized; Animations achieves more complex animation effects by defining multiple keyframes and defining the attribute values of the elements in each keyframe. Syntax:animations: name duration timing-function iteration-count; Name: key frame set name (set of keys created by this name) Duration: indicates how long it takes to complete the smooth transition of attribute values Timing function: indicates the method of smooth transition Iteration count: the number of iteration cycles. It can be set to a specific value or set to infinite for infinite loop. The default is 1 Usage:@-WebKit keyframes collection name of key frames {code for creating key frames} As shown in the following code: @-webkit-keyframes mycolor { 0% {background-color:red;} 40% {background-color:darkblue;} 70% {background-color: yellow;} 100% {background-color:red;}} .animate:hover { -webkit-animation-name: mycolor; -webkit-animation-duration: 5s; -webkit-animation-timing-function: 4. Flex layout After setting as flex layout, the of child elements float、 clearand vertical-alignProperty will be invalidated. Elements with flex layout are called flex containers - flex-direction - flex-wrap - flex-flow - justify-content - align-items - align-content 4.1.1 flex direction attribute flex-directionProperty determines the direction of the spindle (that is, the arrangement direction of items). .box { flex-direction: row | row-reverse | column | column-reverse; } It may have four values. - row(default):. 4.1.2 flex wrap attribute By default, items are arranged on a single line, also known as a grid line. flex-wrapProperty defines how to wrap a line if an axis cannot be arranged. .box{ flex-wrap: nowrap | wrap | wrap-reverse; } It may take three values. (1) nowrap(default): no line breaks. (2) wrap: wrap, first line above. (3) wrap-reverse: wrap, first line below. 4.1.3 flex-flow flex-flowAttribute is flex-directionProperties and flex-wrapAttribute. The default value is row nowrap。 .box { flex-flow: <flex-direction> || <flex-wrap>; } 4.1.4 justify content attribute justify-contentProperty defines the alignment of the item: align right - center: Centered - space-between: both ends are aligned, and the spacing between items is equal. - space-around: equal spacing on both sides of each item. Therefore, the interval between items is twice as large as that between items and borders. 4.1.5 align items attribute align-itemsProperty defines how items are aligned on the cross axis. : the baseline alignment of the first line of text of the item. - stretch(default): if the item is not set to height or set to auto, it will occupy the height of the whole container. 4.1.6 align content attribute align-contentProperty defines the alignment of multiple grid lines.. 2、 Properties of the project The following six properties are set on the project. - order - flex-grow - flex-shrink - flex-basis - flex - align-self 4.2.1 order attribute: defines the order of items 0 orderProperty defines the order in which items are arranged. The smaller the value, the higher the arrangement. The default value is 0. .item { order: <integer>; } 4.2.2 flex growth attribute: defines the magnification of the item 0 flex-growProperty defines the magnification of the item. The default is 0That is, if there is no space left, it is also enlarged. .item { flex-grow: <number>; /* default 0 */ } If all items flex-growIf the attributes are all 1, they will equally divide the remaining space, if any. If a project flex-growIf the attribute is 2 and all other items are 1, the remaining space occupied by the former will be twice that of other items. 4.2.3 flex shrink attribute: defines the reduction scale of the project 1 flex-shrinkProperty defines the reduction scale of the item. The default is 1, that is, if there is insufficient space, the item will be reduced. .item { flex-shrink: <number>; /* default 1 */ } If all items flex-shrinkThe attributes are all 1. When the space is insufficient, it will be reduced in equal proportion. If a project flex-shrinkIf the property is 0 and other items are 1, the former will not shrink when the space is insufficient. Negative values are not valid for this property. 4.2.4 the flex basis attribute will occupy a fixed space flex-basisProperty defines the main size occupied by the project before allocating extra space. Based on this attribute, the browser calculates whether the spindle has excess space. Its default value is auto, that is, the original size of the project. .item { flex-basis: <length> | auto; /* default auto */ } It can be set to follow widthor heightProperty (for example, 350px), the item will occupy a fixed space. 4.2.5 flex properties flexAttribute is flex-grow, flex-shrinkand flex-basisThe default value is 0 1 auto。 The last two properties are optional. .item { flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ] } This property has two quick values: auto ( 1 1 auto)And none( 0 0 auto)。 It is recommended to use this attribute first rather than write three separate attributes separately, because the browser will calculate the relevant values. 4.2.6 align self attribute align-selfProperty allows a single item to have a different alignment from other items and can be overwritten align-itemsProperties. The default value is auto, which means inheriting the parent element align-itemsProperty. If there is no parent element, it is equivalent to stretch。 .item { align-self: auto | flex-start | flex-end | center | baseline | stretch; } This attribute may take six values. Except auto, all other values are completely consistent with the align items attribute. 5. Realize the horizontal and vertical center of an element 1) Disadvantages: if you don’t know the width and height, this effect can’t be achieved. If the data can not be divided, there is error in the effect. {width:200px; height:200px; Position: absolute or fixed; top:50%; margin-top:-100px; left:50%; margin-left:-100px;} 2) Disadvantages: it is not suitable for elements with unknown width and height to be centered horizontally and vertically {width:333px; height:333px; position:fixed; margin:auto; top:0; left:0; right:0; bottom:0;} 3) Advantages: it can realize the horizontal and vertical centering of an element with unknown width and height. Disadvantages: display: Flex; CSS3 newly added; Compatible with ie10 or above html{ height:100%;} body{ margin:0; display:flex; height:100%;} div{ margin:auto;} Where: display: the nearest parent element given by flex 4) body{ margin:0;} div{ position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); } /*top:50%; left:50%; This is half the overall width and height of the browser viewport; transform:translate(-50%,-50%); Is half the width and height of the current element*/ 6、BFC Elements with BFC characteristics can be regarded as isolated independent containers, and the elements in the container will not affect the external elements in layout The BFC characteristic can be triggered as long as the element meets any of the following conditions: - HTML root element - Floating element: float values other than none - Absolute positioning element: position (absolute, fixed) - Display is inline block and flex - Overflow values other than visible (hidden, auto, scroll) The best way to establish BFC is overflow: hidden Characteristics and application of BFC 1. When the elements are in the same BFC, the margins in the vertical direction will overlap. The solution is to put them in different BFC containers. 2. BFC can contain floating elements (clear floating), as long as the container overflow: hidden is set 3. BFC can prevent elements from being overwritten by floating elements (text wrapping problem), as long as the element overflow: hidden is set 7. Clear float In the document flow, the height of the parent element is supported by the child element by default, that is, how high the child element is, how high the parent element is. However, when the child element is set to float, the child element will be completely separated from the document flow. At this time, the child element will not be able to support the height of the parent element, resulting in the height collapse of the parent element. Solution 1: after + zoom (the best to use, the most recommended, and the compatibility is also very good) Parent element:: after {content: ”; display: block; height: 0; visibility: hidden; clear: both;} Parent element: {zoom: 1} Suggestion: define public classes to reduce CSS code Solution 2: add the declaration overflow: hidden to the parent element; zoom:1; (need to be compatible with IE6) Advantages: simple, less code and good browser support Disadvantages: it cannot be used with position, because the exceeding size will be hidden** 8. Processing browser compatible Style compatibility (CSS) Interactive compatibility (JavaScript) 1. For the problem of event compatibility, we usually need to encapsulate the method of an adapter to filter event handle binding, removal, bubble blocking and default event behavior processing var helper = {} //Binding event helper.on = function(target, type, handler) { if(target.addEventListener) { target.addEventListener(type, handler, false); } else { target.attachEvent("on" + type, function(event) { return handler.call(target, event); }, false); } }; //Cancel event listening helper.remove = function(target, type, handler) { if(target.removeEventListener) { target.removeEventListener(type, handler); } else { target.detachEvent("on" + type, function(event) { return handler.call(target, event); }, true); } }; Copy code Browser hack 1、 Browser compatibility summary ** **1. Double floating margin: Reason: multiple parallel floating elements have set the left or right boundary value (x), and the left or right boundary value of the first floating element under IE6 is 2 times (2x); Solution: add display: inline for the first floating element; Style; 2. Height not adaptive: Reason: the parent height of multiple parallel floating elements cannot be extended. Solution: add < div class = “clear” > < / div > after the last floating element clear {clear:both;} 3. The upper and lower boundaries are not recognized: Cause: the parent element does not specify the height, and the margin top and margin bottom parsing errors Solution: add style: overflow: Auto on the parent element of this element; display:inline-block; Note: when the element is set to inline block, finally specify the width for the element; 4. IE6 does not recognize micro height: Reason: IE6 cannot recognize the height lower than the current word height Solution: set font size: 0 / overflow: hidden for this element; 5. IE6 link pseudo class problem: Reason: IE6 does not recognize P: hover, but only a: hover Solution: replace it with a: hover. 6. IE6 and 7 ladder list problems: Reason: floating element does not specify width; Solution: specify a fixed width for the floating element 2、 Compatible (hack) technology ** **1. Attribute filtering: #nav { _ margin:100px; /* IE6 only*/ *margin:100px; /* Only IE6 and IE7 are recognized*/ margin:100px/; /* IE8 only*/ {IE6-10} }/; /* IE8 only*/ {IE6-10} } #nav { _ margin:100px; /* IE6 only*/ *margin:100px; /* Only IE6 and IE7 are recognized*/ margin:100px\0/; /* IE8 only*/ \9{IE6-10} } 2. Selector filtering: * html #nav {margin:10px; border:1px #f00 solid;} /* IE6 recognition only*/ *+html #nav {margin:100px; border:1px #f00 solid;} /* IE7 recognition only*/ /*For Firefox*/ @-moz-document url-prefix() { #nav{ width:200px; } } /*For Safari & Chrome*/ @media screen and (-webkit-min-device-pixel-ratio:0) { #nav{ width:300px; } } Note: as for the unrecognized font size below 12 in chrome Chinese version, the solution is to set the style as follows: html {-webkit-text-size-adjust:none;} /*For opera*/ @media all and (-webkit-min-device-pixel-ratio:10000), not all and (-webkit-min-device-pixel-ratio:0) { #nav{ width:400px; } } 3. Style sheet filtering <!-- [if IE 6] > only HTML recognized by IE6 <! [endif]--> <!-- [if LT IE 6] > less than the HTML recognized by IE6 <! [endif]--> <!-- [if GT IE 6] > greater than HTML recognized by IE6 <! [endif]--> <!-- [if ie] > only HTML recognized by IE <! [endif]--> <!-- [if LTE IE 6] > HTML recognized less than or equal to IE6 <! [endif]--> <!-- [if GTE IE 6] > HTML recognized by IE6 <! [endif]--> 3、 Precautions **Remember to clear the float. (add clear float at the bottom of the container with float element) Try to give floating elements a definite width. Try to use padding instead of margin. If there are both float and margin, add display: inline. Try to avoid using absolute positioning for layout; If used, specify Z-index, top, left; Try to avoid using translucent PNG pictures (png-24); If used, repair it with PNG patch; If the width is stretched, set overflow: hidden; In case of inexplicable padding, set font size: 0 and overflow: hidden; 4、 Other skills 1. Setting padding for div in Firefox will increase width and height, but ie will not (can be solved with! Important) 2. Centering problem a). Center vertically Set the line height to the same height as the current div, and then use vertical align: middle (be careful not to wrap the content.) b). Center horizontally margin: 0 auto; (of course not everything) 3. If you need to add a style to the contents of a tag, you need to set display: block; (common in navigation tabs) 4. The difference between FF and IE’s understanding of box leads to the difference of 2px, and the double margin of div set as float under ie 5. UL tag has list style and padding under FF by default It’s best to make a statement in advance to avoid unnecessary trouble (common in navigation tabs and content lists) 6. As an external wrapper, do not set the dead height of div, and it is better to add overflow: hidden To achieve a high degree of adaptation 7. About hand cursor cursor: pointer. Hand is only applicable to ie 9. Compatibility of different resolutions I Load different CSS style files according to different resolutions The idea of this method is to create different CSS files for 800, 1280, 1440, 1600, 1920 and other resolutions. Then write CSS style sheets at various resolutions. You may feel that writing so many different CSS style sheets for a page must be a lot of work. In fact, not necessarily. According to my practice in this project, I found that the workload is actually relatively small. First of all, when we are working on a project, we usually have some range restrictions. For example, this project only needs to adapt to 1280 ~ 1920 resolution. And between the resolutions, sometimes we just adjust the width, height, size and position of the elements on the page. The overall framework is similar or the same. Not only that, sometimes the requirements of the project are not high and the design draft is not restored by comparing the height of 1:1. At this time, our style sheet at 1440 resolution is also practical at 1280 resolution. At this time, our workload is further reduced. At this time, we can first complete the CSS style sheet under a resolution. Then, on this basis, adjust other resolutions. In this process, we only need to adjust some parameters. For example, in my project, I only made three style sheets for different resolutions style sheet At this time, we only need to be on our HTML page In the tag, use js to load different CSS style sheets according to different computer resolutions** Note that the JS here must be written inTag, so you can load the CSS style sheet in advance before loading the page content** <script> //Call this CSS when the resolution is greater than or equal to 1680, mostly 1920 if(window.screen.width >= 1680){ document.write('<link rel="stylesheet" href="css/index_1920.css">'); } //When the resolution is 1600-1680, call this CSS else if(window.screen.width >= 1600){ document.write('<link rel="stylesheet" href="css/index_1600.css">'); } //Call this CSS when the resolution is less than 1600 else{ document.write('<link rel="stylesheet" href="css/index.css">'); } </script> In this way, you can use different CSS style sheets according to the resolution of different computers. This completes the page using different resolutions. II Using media query Media query is a new feature of CSS3, which is compatible with most browsers. The idea of this method is to apply different CSS styles according to different resolutions. This idea is similar to method 1, or the idea of method 1 is similar to this idea. After all, this is also an official practice. We have two ways to use media query. Summary of all media parameters Width: the visual width of the browser. Height: the visual height of the browser. Device width: the width of the device screen. Device height: the height of the device screen. Orientation: whether the detection equipment is in the horizontal or vertical state at present. Aspect ratio: detect the proportion of the browser’s visual width and height. (for example: aspect ratio: 16 / 9) Device aspect ratio: measure the ratio of the width and height of the device. Color: the number of bits to detect the color. (for example, min color: 32 will detect whether the device has 32-bit color) Color index: check the color in the device color index table. Its value cannot be negative. Monochrome: detects the number of bits per pixel in the monochrome frame buffer. (this is too advanced. I guess we seldom use it) Resolution: detects the resolution of the screen or printer. (for example: Min resolution: 300dpi or min resolution: 118dpcm). Grid: detect whether the output device is a grid device or a bitmap device. 1. Introduce different CSS style sheets according to different resolutions This method is the same as method 1. It also introduces the corresponding CSS style sheet by judging the resolution of the computer. <!-- The resolution is lower than 1280, and test-01 is adopted CSS style sheet -- > <link rel="stylesheet" media="screen and (max-device-width:1280px)" href="test-01.css"> <!-- The resolution is higher than 1400, and test-02 is adopted CSS style sheet -- > <link rel="stylesheet" media="screen and (min-device-width:1440px)" href="test-02.css"> 2. In the same CSS style sheet, write different CSS styles according to different resolutions This method has only one CSS demo table, in which different CSS styles are written according to different resolutions. <style media="screen"> /*If the resolution is lower than 1280, use the following style*/ @media screen and (max-device-width:1280px){ div{ width: 200px; height: 200px; background-color: green; } } /*The resolution is higher than 1440, and the following style is adopted*/ @media screen and (min-device-width: 1440px){ div{ width: 300px; height: 300px; background-color: red; } } </style> PC side page adaptation Take the width of design drawing 1920 as an example: There is a unit called VW in CSS, which is a percentage unit based on the width of the browser. The difference from% is that the child element% is calculated relative to the width of the parent element, while VW is calculated according to the width of the browser. For example, the browser width is 1920px, the parent element width is 100px, and the child element width written at 50% is 50px; If the child element is written 50Vw, its width is 50% of the browser width, i.e. 960px; After making this clear, we can calculate: 100vw = 1920px; 1vw = 19.2px 1px = 1 / 19.2vw; Thus, we can set the variable @1px: 1 / 19.2vw; In this way, when writing styles, you can use @1px for calculation, as shown in the figure: In this way, if the browser size changes, the corresponding VW value will also change, and naturally the PX calculated by VW will also change, so as to achieve the purpose of being compatible with all kinds of browsers; However, the drawback of this method is that when the browser width becomes smaller and smaller, the margin padding equivalent will become smaller and smaller, and the minimum font is 12px, so the elements will be crowded together when it is about 800px. Although we don’t need to be compatible with 800 resolution PC now, generally the minimum compatibility is 1200, but in order to be rigorous, Is it compatible with the media below 1200 Of course, it doesn’t mean rewriting the element attribute value according to the 1200 design drawing a key 1200 / 1920 = 0.625 We know the ratio of the two. At this time, we can set a variable, which can also be called a constant, because at this time, we need to set a fixed value Because it is based on the 1920 design drawing, we set each 1px under 1200 as 0.625px of 1920; @1200-1px : 0.625px Write at this time @media screen and(max-width:1201){ Copy the above CSS code and replace @ 1px globally with @ 1200-1px; } As shown in the figure: Layout scheme of mobile terminal 1. Use media query + REM unit 2. Layout using VW units + REM units 3. Use js + REM unit layout 4. Use sass + VW unit layout 1. Use media query + REM unit Principle: use the characteristics of the media query detection device to change the font size of the root node according to the device Implementation steps: (1) Change the font size of the root node through media query @media all and (min-width: 320px) { html { font-size: 32px; } } @media all and (min-width: 375px){ html{ font-size: 37.5px; } } (2) The layout of elements in the page is in rem units, which can achieve the adaptive state div { width: 10rem; height: 100px; background: red; } Disadvantages: it cannot be finely adapted to each device, and the amount of code is large 2. Layout using VW units + REM units Principle: when the screen size changes, the value of VW as the unit will also change. VW is used as the unit of font size of the root node. Therefore, in different screen sizes or devices, the value of font size of the root node is different, and the value of REM unit is different Implementation steps: (1) Use VW unit as the unit of HTML font size (calculation) //If the design drawing is 750px, we need to set the code html{ font-size: 13.33333333vw } (2) All page layouts use REM units div{ //In this way, 1rem is the 100px on the design draft width:1rem; // The value displayed in the page is 50px height:1rem; } Question: why is the font size of the root node 13.33333vw and why is 100px = 1rem? 750px = 100vw 1px = 100 / 750 = 0.133333333333333vw 100px = 0.133333333333333vw *100px = 13.33333333vw The value of REM is calculated according to the font size of the root node. The font size of the root node is set to 100px to facilitate calculation The final result is 100px = 1rem 3. Use js + REM unit layout Principle: get the width of the device through JS to calculate the font size of the root node. The value obtained by rem is different, and it can be adapted to different pages We can install an extension in the editor to automatically calculate PX – > rem (1) Install the plug-in in vscode extension: cssrem (2) Then change in the vscode configuration file: rootfootprint is the number of design drawing / 10 (3) Use the script tag in the page to introduce and obtain the characteristics of the device and change the JS file of the geological body size of the root node (4) All layouts in the page use rem as the unit. You can write as much as the value at the design drawing quantity, but you should choose the value converted to rem 4. Use sass + VW unit layout Principle: use VW as the layout unit of all elements of the page to simplify the layout combined with REM + VW (1) Functions using sass: @function vw($px) { @Return ($PX / width of design drawing) * 100vw; } (2) Layout in page header { Height: VW (measured value); background: green; font-size: vw(48); } postcss-px-to-viewport 10. CSS selector Classification and priority of selectors - Label selector: priority weighted value is 1. - Pseudo element or pseudo object selector: priority weighted value is 1. - Class selector: priority weighted value is 10. - Attribute selector: priority weighted value is 10. - ID selector: priority weighted value is 100. - Other selectors: priority weighted value is 0, such as universal selector, etc. Then, take the above weighted values as the starting point to calculate the total weighted values of selectors in each style. The calculation rules are as follows: - Count the number of ID selectors in the selector and multiply by 100. - Count the number of class selectors in the selector and multiply by 10. - Count the number of label selectors in the selector and multiply by 1. By analogy with this method, finally add all the weighted values to get the total weighted value of the current selector, and finally decide which style has the highest priority according to the weighted value. Difference between import and @ link There are three main ways to use CSS in the page: adding and defining style attribute values in the line, embedded calls in the page header and external link calls, of which there are two kinds of external references: link and @ import. There are two ways to externally reference CSS: link and @ import: XML / HTML code < link XML / HTML code <style type="text/css" media="screen"> @Import URL ("CSS file"); </style> Both of them refer to CSS externally, but there are some differences: Difference 1: link is an XHTML tag. In addition to loading CSS, it can also define RSS and other [email protected] Import belongs to the category of CSS. You can only load CSS Difference 2: when link references CSS, it is loaded at the same time when the page is [email protected] Import requires the page to be loaded after the page is fully loaded. Difference 3: link is an XHTML tag, and there is no compatibility [email protected] Import is in CSS2 1, which is not supported by lower versions of browsers. Difference 4: link supports using JavaScript to control DOM to change style; @ import is not supported. Supplement: @ import optimal writing method @Import is generally written in the following ways: @import 'style. CSS' // windows IE4 / NS4, Mac OS X IE5, Macintosh IE4 / IE5 / NS4 not recognized @Import "style. CSS" // windows IE4 / NS4, Macintosh IE4 / NS4 not recognized @Import URL (style. CSS) // windows NS4, not recognized by Macintosh NS4 @Import URL ('style. CSS') // not recognized by windows NS4, Mac OS X IE5, Macintosh IE4 / IE5 / NS4 @Import URL ("style. CSS") // windows NS4, not recognized by Macintosh NS4 According to the above analysis, @ import URL (style. CSS) and @ import URL (“style. CSS”) are the best choices, with the most compatible browsers. From the perspective of byte optimization, @ import URL (style. CSS) is the most recommended 11. Draw a line of one pixel Set media query + transfrom Scaley and border on canvas, height, HR and pseudo elements ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(10, 100); ctx.lineTo(300,100); ctx.stroke(); 12. Gets the width and height of the DOM element 1、Element.style.width/height Only inline styles can be obtained var ele = document.getElementById('element'); console.log(ele.style.height); // '100px' 2、window.getComputedStyle(ele).width/height IE9 and above can obtain real-time information var ele = document.getElementById('element'); console.log(window.getComputedStyle(ele).width); // '100px' console.log(window.getComputedStyle(ele).height); // '100px' 3、Element.currentStyle.width/height The function is the same as the second point. It only exists in the old version of IE (below IE9). Don’t use it unless it is compatible with the old version of IE. 4、Element.getBoundingClientRect().width/height In addition to obtaining width and height, it can also obtain information such as element position var ele = document.getElementById('element'); console.log(ele.getBoundingClientRect().width); // 100 console.log(ele.getBoundingClientRect().height); // 100
https://developpaper.com/basic-javascript/
CC-MAIN-2022-33
refinedweb
5,578
51.78
This hack shows you how to go much further than mere clipboard access by digging into the lower levels of the Drag and Drop APIs and building a program that can save files directly to the desktop via dragging, complete with proper file icons and drag feedback. When you use an editor to write a large document, you often save it to a particular location on your filesystem—in a Projects folder perhaps. This is because you will keep the file around for a long time, so you want to store it for later use. Small documents, however, are often created for transient reasons. I often write a few paragraphs and then immediately post it to a weblog or attach it to an email. Some applications (particularly those on Mac OS X) let you save something quickly by dragging a small marker into another application or the desktop. The marker represents the file and lets you quickly move the entire file into another context (a blog editor, for example) without thinking about where to save the file (and trying to remember where you stashed it 10 minutes later). Since drag-to-save behavior is not a standard part of the Java platform, you will have to build it from scratch using the Drag and Drop APIs. First, you will need a class that can trigger the drop action. The plan is to detect the gesture, create a temp file to be saved, and then start the real drag with the appropriate cursor and user feedback. Here's a starting point: class FileDragGestureListener extends DragSourceAdapter implements DragGestureListener { JTextArea text; Cursor cursor; public FileDragGestureListener(JTextArea text) { this.text = text; } The FileDragGestureListener implements DragGestureListener and extends the DragSourceAdapter. Swing sends all drag events to a DragSource listener. TIPExtending the DragSourceAdapter, instead of implementing DragSource directly, lets your class avoid implementing all of the required methods. DragSourceAdapter gives you empty, no-op implementations of all the methods in DragSource. Extending the DragSourceAdapter, instead of implementing DragSource directly, lets your class avoid implementing all of the required methods. DragSourceAdapter gives you empty, no-op implementations of all the methods in DragSource. FileDragGestureListener accepts a component to grab the text from. Any provider of text would work, but I chose a JTextArea because it's the most likely to be used in a text editor. All operating systems define a drag gesture, which usually means something like "click and drag for more than 10 pixels," though it varies from platform to platform. Swing will detect the drag gesture and send an event to a DragGestureListener, which is why FileDragGestureListener also implements that interface. DragGestureListener defines one method: dragGestureRecognized( ). This is where the real work of this hack is done: public void dragGestureRecognized(DragGestureEvent evt) { try { // generate the temp file File proxy_temp = File.createTempFile("tempdir",".dir",null); File temp = new File(proxy_temp.getParent( ),"myfile.txt"); FileOutputStream out = new FileOutputStream(temp); out.write(text.getText( ).getBytes( )); out.close( ); The implementation of dragGestureRecognized( ) starts by creating a temp file to store the text. Actually, first it creates a fake temp file, proxy_temp, using the File.createTempFile( ) method. Then it creates the real temp file in the same directory and writes the text data to the file. You could skip the proxy_temp part, but then if the user drags to the desktop, he will end up with a filename like myfile158392.txt instead of myfile.txt. Using the proxy file lets you create a file with a useful name, while still keeping the file in the default temp directory. Now that the file is done, it's time to create an icon: // get the right icon FileSystemView fsv = FileSystemView.getFileSystemView( ); Icon icn = fsv.getSystemIcon(temp); Toolkit tk = Toolkit.getDefaultToolkit( ); Dimension dim = tk.getBestCursorSize( icn.getIconWidth( ),icn.getIconHeight( )); BufferedImage buff = new BufferedImage(dim.width,dim.height, BufferedImage.TYPE_INT_ARGB); icn.paintIcon(text,buff.getGraphics( ),0,0); In most operating systems, each type of file has a different icon, such as a little piece of paper for a text file or musical notes for MP3 files. You could bundle such icons with your program, but then they wouldn't look right on all operating systems. FileSystemView provides a platform-independent way to get the appropriate icon for any file type with the getSystemIcon( ) method. Once you have the icon, you just need the underlying image. You could cast the icon to an ImageIcon because most platforms use those—but the odd platform here or there might not. It's much safer to draw the icon into a new buffered image. Drawing into a new image also lets you convert the icon to the right cursor size without resizing it. Without this step, the operating system might resize the image on its own, resulting in a messy drag icon that looks horrible. Note the BufferedImage is created with TYPE_INT_ARGB. This preserves any transparency that may be in the native system icons (e.g., on Mac OS X). With the file and image in place, it's time to start the drag: // set up drag image if(DragSource.isDragImageSupported( )) { evt.startDrag(DragSource.DefaultCopyDrop, buff, new Point(0,0), new TextFileTransferable(temp), this); } else { cursor = tk.createCustomCursor(buff,new Point(0,0),"billybob"); evt.startDrag(cursor, null, new Point(0,0), new TextFileTransferable(temp), this); } // end the try/catch block and handle exceptions Some operating systems support the idea of a drag image. This is a small image underneath the cursor representing what is being dragged. For OS X, this is usually a translucent version of the file icon. Windows doesn't support drag images, so you can just make the cursor itself be the file icon. That's not quite as nice, but it gives the user the same effect. In the previous code, DragSource.isDragImageSupported( ) lets you know which way to go. If drag images are supported, then it starts a new drag with evt.startDrag( ), passing in the default copy cursor, the drag image, the cursor hotspot on the drag image, a Transferable for the temp file (more on this later), and a DragSource. FileDragGestureListener just passes in this because it also extends the DragSourceAdapter. If drag images are not supported, then the code creates a custom cursor using the icon and starts the drag using the new cursor. Once the drag is started, Swing will provide you with callbacks each time the user moves the cursor and enters or exits an area where the file could be dropped. To provide feedback about whether a file can be dropped over the current location, you should override the dragEnter( ) and dragExit( ) methods in DragSourceAdapter to switch the cursor and reflect the current drop target: public void dragEnter(DragSourceDragEvent evt) { DragSourceContext ctx = evt.getDragSourceContext( ); ctx.setCursor(cursor); } public void dragExit(DragSourceEvent evt) { DragSourceContext ctx = evt.getDragSourceContext( ); ctx.setCursor(DragSource.DefaultCopyNoDrop); } Earlier, I mentioned the TextFileTransferable class. The Drag and Drop APIs, along with the clipboard, define something known as a Transferable. This is a wrapper around some data that describes the flavor of the data and provides access to the data itself. You can think of a flavor as a MIME type. Thus, a transferable for images would support the DataFlavor.imageFlavor flavor, and a text transferable would support the stringFlavor. You can create your own flavors, too, but it's always better to use the standard ones if you can. The TextFileTransferable (in ) holds a single text file and can transfer it using the javaFileListFlavor, which represents a java.util.List containing File objects. class TextFileTransferable implements Transferable { File temp; public TextFileTransferable(File temp) throws IOException { this.temp = temp; } public Object getTransferData(DataFlavor flavor) { List list = new ArrayList( ); list.add(temp); return list; } public DataFlavor[] getTransferDataFlavors( ) { DataFlavor[] df = new DataFlavor[1]; df[0] = DataFlavor.javaFileListFlavor; return df; } public boolean isDataFlavorSupported(DataFlavor flavor) { if(flavor == DataFlavor.javaFileListFlavor) { return true; } return false; } } TextFileTransferable implements Transferable and only recognizes the javaFileListFlavor. getTransferData( ) returns the single file wrapped in an ArrayList. getTransferDataFlavors( ) returns an array with only one element: javaFileListFlavor. And isDataFlavorSupported returns true if the specified flavor is a javaFileListFlavor. With all of the components in place, it's time to make a simple application to pull it all together (see ). public class FileDropper { public static void main(String[] args) throws IOException { JFrame frame = new JFrame(": Drag-and-Drop with Files"); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); FileSystemView fsv = FileSystemView.getFileSystemView( ); Icon icon = fsv.getSystemIcon(File.createTempFile("myfile.",".txt")); ImageIcon iicn = (ImageIcon)icon; frame.getContentPane( ).setLayout(new BorderLayout( )); JTextArea text = new JTextArea( ); JLabel label = new JLabel("myfile.txt",icon,SwingConstants.CENTER); DragSource ds = DragSource.getDefaultDragSource( ); DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer( label, DnDConstants.ACTION_MOVE, new FileDragGestureListener(text)); frame.getContentPane( ).add("North",label); frame.getContentPane( ).add("Center",text); frame.pack( ); frame.setSize(400,300); frame.setVisible(true); } } FileDropper creates a new frame with a label and a text area. The label gets a text file icon, the same as the drag operation from earlier. The crucial part of the code is the ds.createDefaultDragGestureRecognizer( ) call. This ties the system-wide drag class to your custom recognizer. Without this call, the system would know nothing about your customizations, and nothing would happen when the user tries to drag the label to another application or the desktop. With the call, though, the cursor will switch to show a small text icon and the user can successfully drag the file to any place that accepts it (see ). Now you can save files or transfer them without ever going to a Save File dialog or having to navigate hierarchies of folders. O'Reilly Home | Privacy Policy © 2007 O'Reilly Media, Inc. Website: All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/pub/h/4873
CC-MAIN-2015-06
refinedweb
1,612
56.66
Name: [14849] antiRTFM Member: 67 months Authored: 50 videos Description: Video tutorials about programming in the C++ programming language. ... C++ Tutorial (6) - Absolute n00b spoonfeed [ID:1279] 6: * Text vs Code * Escape characters * Math Calculations Forum: Got any questions? Get answers in the ShowMeDo Learners Google Group. Video statistics: - Video's rank shown in the most popular listing - Video plays: 1476 << keep going! I am new to C++.I find the tutorials very helpful.Thanks. Good explanation!! I learned more here in 1hr. than elsewhere in a month. your free videos are worth thousands to me. now , if only i had some money. after watching this video i am very much interested in c++ programming. in my opinion any one can learn c++ after watching this video. 2 years ago my teacher told me you can not become a programmer because you have no logic to understand programming language but today i think they do not know how to teach. good tutorial Very cool! Very smooth to understand. Wow you are much better than my college instructor. I really like the videos. GUYS, mke sure you play around with your code. here's mine. #include"stdafx.h" #include <iostream> using namespace std; int main () { cout << "Okay, here we go with fucking math right? \n" ; cout << "What is 10 + 10? \n" ; cout << endl; cout << 10 + 10 ; cout << endl; cout << "OR IS IT? DUN DUN DUN" ; cin.get (); return 0; } I love your videos so far #4... But it would help if you actually named what some of the commands are, by their proper name. cout is console output. - cin is console input. - endl is end line. I come vrom Basic WAAAAYYYY back in the day, and it helps to tell people what a command actually stands for, esp if it is plain language what it is doing. Hey, thank you very much for your videos. I will learn a lot on C++.. Having some problems while debugging. When i try to add multiple lines it will show a failed part of debug. such as cout << "etc." ; But other wise, great video! Nice intro tutorials, looking forward to the rest of the series.
http://showmedo.com/videotutorials/video%3Fname%3D6780050
CC-MAIN-2014-42
refinedweb
361
86.6
Let's give a go at a very simple program that prints out "Hello World" to standard out (usually your monitor). We'll call our little program hello.c. #include <stdio.h> main() { printf("Hello, world!\n"); return 0; } What's all this junk just to print out Hello, World? Let's see what's happening: Seems like trying to figure all this out is just way too confusing. Let's break things up one at at time: return 0statement. Seems like we are trying to give something back, and it is an integer. Maybe if we modified our main function definition: int main()Ok, now we are saying that our main function will be returning an integer! So remember, you should always explicitly declare the return type on the function! #include <stdlib.h>to our includes. Let's change our return statement to return EXIT_SUCCESS;. Now it makes sense! int printf(const char *format, ...);printf returns an int. The man pages say that printf returns the number of characters printed. Now you wonder, who cares? Why should you care about this? It is good programming practice to ALWAYS check for return values. It will not only make your program more readable, but in the end it will make your programs less error prone. But in this particular case, we don't really need it. So we cast the function's return to (void). fprintf, fflush, and exit are the only functions where you should do this. More on this later when we get to I/O. For now, let's just void the return value. /* */. The comment begins with /*and ends with */. Let's see our new improved code! #include <stdio.h> #include <stdlib.h> /* Main Function * Purpose: Controls program, prints Hello, World! * Input: None * Output: Returns Exit Status */ int main(int argc, char **argv) { printf("Hello, world!\n"); return EXIT_SUCCESS; } Much better! The KEY POINT of this whole introduction is to show you the fundamental difference between correctness and understandability. Both sample codes produce the exact same output in "Hello, world!" However, only the latter example shows better readability in the code leading to code that is understandable. All codes will have bugs. If you sacrifice code readability with reduced (or no) comments and cryptic lines, the burden is shifted and magnified when your code needs to be maintained. Document what you can. Complex data types, function calls that may not be obvious, etc. Good documentation goes a long way! You will most likely be using the GNU C compiler, gcc in a Linux or *nix-like environment. Most environments will have the cc variable set which is much more suitable when using Makefiles. A superficial look at compiling would entail: gcc file.c But is this what you really want? We get a file called a.out in our directory. This is because you aren't specifying the correct compiler options. Taking the theory of "that which is learned first is learned best", compile your programs using the "anal retentive" flags. This will not only catch more errors at compile time, but will help you create a program with less errors at run time. The recommended options to include while compiling are: So here is an example command line: gcc -ansi -pedantic -Wall -O2 -o hello hello.c This produces an executable called hello in the directory where hello.c resides.
http://randu.org/tutorials/c/intro.php
crawl-001
refinedweb
564
68.87
23 August 2011 23:59 [Source: ICIS news] LONDON (ICIS)--European base oil solvent neutral (SN)150 and SN500 export prices have fallen $50/tonne (€35/tonne) this week because of rising supply and sluggish demand, markets sources said on Tuesday. In order to move product in a slow market, European suppliers are indicating lower prices. For several weeks, buyers and traders expected prices to come down, citing slow offtake, a lack of arbitrage opportunities and price declines upstream. However, producers held prices up at prevailing levels. As August draws to a close, supply and demand has proved to be decisive as faced with mounting stocks and low buying interest, supplier resistance has ended. “We are one of the people offering lower,” said a northwest European producer. “We have seen a slower domestic market in July and August.” The producer dropped its price by $80/tonne in one case, to secure export business. “Supply and demand is the main thing.” the producer added. Another producer confirmed it would accept a reduction of $35-50/tonne on its existing SN150 and SN500 price in order to move some product. In the week ending 23 August, ICIS assessed SN150 and SN500 FOB (free on board) ?xml:namespace> Sources were unclear how long this downtrend would last or how far prices would need to fall to generate better demand. (
http://www.icis.com/Articles/2011/08/23/9487409/europe-base-oil-export-prices-fall-on-rising-supply-weak-demand.html
CC-MAIN-2014-35
refinedweb
226
62.98
Have you tried to add new column in pandas dataframe? So this is the recipe on how we can assign a new column in a Pandas DataFrame. import pandas as pd We have only imported pandas which is needed. We have created a empty dataframe and added columns to it. df = pd.DataFrame() df["StudentName"] = ["John", "Steve", "Sarah"] print(df) We have added a column with values of marks assigned in the function. df = df.assign(Marks = [71, 82, 89]) print(df) So the output comes as StudentName 0 John 1 Steve 2 Sarah StudentName Marks 0 John 71 1 Steve 82 2 Sarah 89
https://www.projectpro.io/recipes/assign-new-column-in-pandas-dataframe
CC-MAIN-2021-43
refinedweb
105
80.11
This tutorial will demonstrate how to use the Twitter API in WebMatrix using Razor. If you do not understand the basic concepts of WebMatrix you should go to for discussion and additional tutorials. You can also download WebMatrix from this site. These steps will create the initial web site. At this point there is no code specific to WebMatrix or Twitter. 1. Create a new site using “Site From Template”->”Empty Site” setting the Site Name to “Twitter API Tutorial”. 2. Now we’ll add the default cshtml page. Click on the “Files” icon near the lower left corner of the window. Then click the “Create a new file” link. This will give you a choice of what type of file to add – we’re going to add a CSHTML file named “default.cshtml”. 3. Add some text to the default body and title elements for a quick test. The file should look something like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Twitter API Tutorial</title> </head> <body> Twitter API Tutorial </body> </html> Click on the “Run” button in the toolbar; your browser should launch displaying the text that you entered. Now we’ll create a helper that will access the Twitter API using the search function.. There isn’t a lot of code and it could go in the default.cshtml file but by creating a helper file we see how to make calls to helpers. The Twitter API is accessed through http calls. We’ll use the “search” function as it is straight-forward and does not require the use of authentication. Use of authentication through OAuth is beyond the scope of this tutorial; you’ll want to go to the Twitter documentation at for details on using it. The search URI is. It can be accessed using whatever web function you want. We’ll use WebClient – you could also just load it as an xml stream. 1. Create a new folder in the project called “App_Code” and create a new cshtml file in it called “MyCustomHelpers.cshtml”. 2. Delete the default html content and add an empty Razor functions block: @functions{ } 3. Put this using statement at the top of the file: @using System.Xml.Linq; This will allow us to parse the Xml string that is returned from Twitter. 4. Now add this function to the functions block: public static string TwitterSearch(string value) { string xml; // The WebClient class is located in the System.Net namespace; it provides // methods for sending data to and from uri resources. In this case we’ll // download the uri content as a string. WebClient web = new WebClient(); xml = web.DownloadString(String.Format("{0}", "deviantART")); return xml; } This is the actual helper function that will be called from the html; it can now be called from the body element of the default page (default.cshtml): <body> @MyCustomHelpers.TwitterSearch("deviantArt"); </body> This will just display the Twitter feed as a string – not very exciting. We’ll add some code that will allow us to modify the display of the entries. Now we’ll create a class that will allow us to parse the Twitter feed items and manipulate their elements. This will let us right code that is neater and easier to maintain. 1. Create a new C# class file in the App_Code folder by right-clicking on the App_Code folder, then clicking on “New File”, select “Class (C#)”. Name the file “TwitterClasses” Change the default ClassName to “TwitterEntry”. All of the code in this step will be added to this class in this file. 2. Each entry in the Twitter feed has elements for an id, the date and time published, a couple of link, title, content, date and time updated, geodata, possible metadata and source info, and author name and uri. We’ll add properties for some of these elements to the class. Properties are generally placed right after the class declaration before any constructors or other methods: public class TwitterEntry { public string Id { get; set; } public DateTime Published { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime Updated { get; set; } public string Source { get; set; } public string AuthorName { get; set; } public string AuthorURI { get; set; } } 3. Also add a constructor to the class to initialize these properties: public TwitterEntry(string id, string published, string title, string content, string updated, string source, string authorName, string authorURI) { Id = id; Published = DateTime.Parse(published); Title = title; Content = content; Updated = DateTime.Parse(updated); Source = source; AuthorName = authorName; AuthorURI = authorURI; } 4. Add the “IComparable” interface to the class and implement the CompareTo() method; this will allow us to sort the feeds (in this case we’ll sort by author name). The class statement should look like: public class TwitterEntry : IComparable<TwitterEntry> and the CompareTo() method: public int CompareTo(TwitterEntry other) { return AuthorName.CompareTo(other.AuthorName); } Now we’ll update the TwitterSearch(string value) helper function in the MyCustomHelpers.cshtml file to return a sorted List of TwitterEntries rather than the xml. The modified function will look like: public static List<TwitterEntry> TwitterSearch(string value) { // create the empty TwitterEntry List List<TwitterEntry> twitterEntries = new List<TwitterEntry>(); // Get the Twitter feed // The WebClient class is located in the System.Net namespace; it // provides methods for sending data to and from uri resources. WebClient web = new WebClient(); string xml = web.DownloadString(String.Format("{0}", value)); // Declare the namespaces that we'll need to select the different // elements using LINQ.. XNamespace ns = ""; XNamespace nsTwitter = ""; // Select the entry elements var entries = from elem in XDocument.Parse(xml).Descendants(ns+"entry") select elem; // Create an instance of TwitterEntry for each entry eleent and add it to the list foreach (var entry in entries) { TwitterEntry twitterEntry = new TwitterEntry(entry.Element(ns+"id").Value, entry.Element(ns+"published").Value, entry.Element(ns+"title").Value, entry.Element(ns+"content").Value, entry.Element(ns+"updated").Value, entry.Element(nsTwitter+"source").Value, entry.Element(ns+"author").Element(ns+"name").Value, entry.Element(ns+"author").Element(ns+"uri").Value); twitterEntries.Add(twitterEntry); } // Sort the list twitterEntries.Sort(); // Return the list return twitterEntries; } Finally we’ll update the html code in default.cshtml file to call the helper (MyCustomHelpers.TwitterSearch()), iterate through the resulting list, and display part of each entry. We’ll use Razor code to access the properties in the Twitter item (such as “@entry.Title”) and add anchor links for the author uri. The default.cshtml file should now look like: @using System.Xml.Linq; <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Twitter API Tutorial</title> </head> <body> @{ // Get the TwitterEntry list and iterate through it foreach (TwitterEntry entry in Helpers.TwitterSearch("deviantART")) { // Dress up the Title <font face="Times New Roman" size="+1" color="#ff0000"> <b>@entry.Title</b> </font> <p></p> // Add the authors uri to their name <a href=@entry.AuthorURI> @entry.AuthorName; </a> // include the TTwitter content @entry.Content <hr/> } } </body> </html> Download WebMatrix Learn more More tutorials Twitter Dev Twitter For any questions or comments about this tutorial please contact the Aeshen team at You can discuss this article using the adjacent Facebook talkback. For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!
http://www.microsoft.com/web/post/learning-the-basics-of-using-the-twitter-api-in-aspnet-web-pages-with-razor-syntax?category=WebMatrix
CC-MAIN-2014-52
refinedweb
1,218
55.24
Namespaces tab Namespaces are URIs (Uniform Resource Identifiers) that uniquely identify a set of resources on the Internet. Because URIs can be very lengthy, shorthand aliases called prefixes are typically defined and used in XML files to make the XML more readable. The Namespaces tab lists all of the namespace URIs and their prefixes in scope for the currently selected activity. Whenever you create a reference to an external property (an element defined in an XSD) whose namespace has not yet been assigned a prefix, the BPEL Designer will prompt you to create a prefix. This can also be done beforehand through the Namespace tab of the Properties sheet for the property by clicking the Assign Prefix button.
http://help.eclipse.org/2019-09/topic/org.eclipse.bpel.help/html/Reference/CommonProperties/namespacesTab.html
CC-MAIN-2019-43
refinedweb
118
55.98
Question: I am relatively new to Flex/ActionScript, but I have been using a pattern of creating one file per function in my util package - with the name of the file being the same as the name of the function. Like if the file was convertTime.as: package util{ public function convertTime(s:String):Date{ ... } } This way I can import the function readily by doing: import util.convertTime; ... convertTime(...); I like this way better than importing a class object and then calling the static methods hanging off of it, like this: import util.Util; ... Util.convertTime(...); But, the more I do this, the more files I'll end up with, and it also seems a bit wasteful/silly to put only one function into a file, especially when the function is small. Is there another alternative to this? Or are these two options the only ones I have? Update: after some research, I've also posted my own answer below. Solution:1 Yes, these are your two main options for utility libraries. We actually use both of these approaches for our generic utility functions. For a very small set of functions that we feel should actually be builtins (such as map()), we put one function per file, so that we can use the function directly. For more obscure/specialized utility functions, we don't want to pollute our global namespace so we make them static functions on a utility class. This way, we're sure that when someone references ArrayUtils.intersect(), we know what library intersect() came from, and what roughly it's for (it intersects two arrays). I would recommend going with the latter route as much as possible, unless you have a function that a) you use very frequently and b) is really obvious what it does at a glance. Solution:2 I came across some other alternatives after all and thought I'd share them here. Alternative 1 - use inheritence This is probably an obvious answer, but is limited. You would put your static methods into a parent class, inherit them to get them in the subclasses. This would only work with classes. Also, because ActionScript is single inheritence, you can only inherit once. Alternative 2 - Alias the methods You still write utility functions as static methods hanging off util classes, but you alias them so you can access them with a shorter name, ex: import mx.binding.utils.BindingUtils; var bind:Function = BindingUtils.bindProperty; Now you can just call bind(...); rather than than the lengthy BindingUtils.bindProperty(...); You can do this within the class scope and the function scope, but not the package scope - because apparently you can only have one visible attribute inside a package. If you do this in the class scope, you will want to make sure it doesn't conflict with your other class attribute names. Alternative 3 - use include As described in this flexonrails blog post you can use include to simulate a mixin in ActionScript. An include is different from an import in that all it's doing is copying the entirety of the file you are including from and paste it into the place you are including it at. So, it has completely no handling of namespace issues, you can not reference its full path name afterwards like you can with imports, if you have conflicting names, you are on your own with this. Also unlike import, it creates different copies of the same code. But what you can do with this is put any number of functions in a file, and include them into class or function scope in another file. Ex: // util/time_utils.as function convertTime(..){ ... } function convertDate(..){ ... } To include: include 'util/time_util.as'; // this is always a relative path ... convertTime(...); Solution:3 @ an0nym0usc0ward OOP is simply the method of consolidating like functions or properties into an object that can be imported and used. It is nothing more that a form of organization for your code, ALL code executes procedurally in the processor in the end, OOP is just organization of sources. What he is doing here may not be OOP as you learn from a book, but it does the exact same thing in the end, and should be treated with the same respect. Anyone that truly understands OOP wouldn't be naive enough to think that the approved and documented form of OOP is the only possible way to object orient your code. EDIT: This was supposed to be a comment response to an0nym0usc0ward's rude comment telling him to learn OOP. But I guess I typed it in the wrong box :) Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/05/tutorial-one-file-per-functionareally.html
CC-MAIN-2018-47
refinedweb
787
61.36
State is a structure that provides a functional approach to handling application state. State<S, A> is basically a function S -> Tuple2(S, A), where S is the type that represents your state and A is the result the function produces. In addition to returning the result of type A, the function returns a new S value, which is the updated state. Let’s build a simple Stack using Arrow’s NonEmptyList and Option: import arrow.* import arrow.core.* import arrow.data.* typealias Stack = Option<Nel<String>> Now we only need the push and pop methods, as follows: import arrow.* fun pop(stack: Stack) = stack.fold({ None toT None }, { Nel.fromList(it.tail) toT it.head.some() }) fun push(stack: Stack, s: String) = stack.fold({ Nel.of(s).some() toT Unit }, { Nel(s, it.all).some() toT Unit }) fun stackOperations(stack: Stack): Tuple2<Stack, Option<String>> { val (s1, _) = push(stack, "a") val (s2, _) = pop(s1) return pop(s2) } stackOperations(Nel.of("hello", "world", "!").some()) // Tuple2(a=Some(NonEmptyList(all=[world, !])), b=Some(hello)) stackOperations(Nel.of("hello").some()) // Tuple2(a=None, b=Some(hello)) As you can see, since we cannot modify the immutable Stack, we need to create a new instance every time we push or pop values from it. For that same reason we have to return the newly created Stack with every operation. However, it is a bit cumbersome to explicitly pass around all of this intermediate state. It’s also a bit error-prone. It would have been easy to accidentally return pop(s1), for example. State’s special power is keeping track of state and passing it along. Recall the description of State at the beginning of this document. It is basically a function S -> Tuple2(S, A), where S is a type representing state. Our pop function takes a Stack and returns an updated Stack and a String. It can be represented as Stack -> Tuple2(Stack, String), and therefore matches the pattern S -> Tuple2(S, A) where S is Stack and A is String. Let’s write a new version of pop and push using State: import arrow.* fun pop() = State<Stack, Option<String>> { stack -> stack.fold({ None toT None }, { Nel.fromList(it.tail) toT it.head.some() }) } fun push(s: String) = State<Stack, Unit> { stack -> stack.fold({ Nel.of(s).some() toT Unit }, { Nel(s, it.all).some() toT Unit }) } The flatMap method on State<S, A> lets you use the result of one State in a subsequent State. The updated state ( S) after the first call is passed into the second call. These flatMap and map methods allow us to use State in for-comprehensions: import arrow.typeclasses.* import arrow.instances.* fun stackOperations() = State().monad<Stack>().binding { val a = push("a").bind() val b = pop().bind() val c = pop().bind() c }.fix() At this point, we have not yet interacted with any Stack; we have written instructions to operate one. We need to pass in an initial stack value, and then we actually apply our operations to it: stackOperations().run(Nel.of("hello", "world", "!").some()) // Tuple2(a=Some(NonEmptyList(all=[world, !])), b=Some(hello)) stackOperations().run(Nel.of("hello").some()) // Tuple2(a=None, b=Some(hello)) If we only care about the resulting String and not the final state, then we can use runA: stackOperations().runA(Nel.of("hello", "world", "!").some()) // Some(hello) Contents partially adapted from Cats State
http://arrow-kt.io/docs/datatypes/state/
CC-MAIN-2018-17
refinedweb
569
59.19
Please visit our new home community.embarcadero.com. By: Wayne Niddery Abstract: Created as an ECO learning vehicle for myself, it acts as a practical example demonstrating various abilities of ECO and that, even for such a modest project, ECO is an advantage and should never be considered “overkill”. As part of learning to use ECO, I decided to create something I need anyway. As an independent developer I work on different projects over time and often at the same time. To protect myself and my clients, I like to back up my work to an offsite location. Now there are certainly lots of existing backup products of various capabilities, and it’s even possible to use WinZip and batch files. But I decided I wanted something easy to use and specific for my needs, and it would be a good exercise. In developing it, I also answered for myself a frequent question I hear: Isn’t ECO overkill for small projects? My answer is no. Despite this being a very modest project, I saved a great deal of time by not having to define relationships in code, manage lists of objects, and design and manage some kind of storage mechanism. So first let’s define the requirements. Note: for the ability to zip up the selected files I used open source library called SharpZipLib available from. This library is distributed under a modified GPL license that allows the library to be used by executables without requiring the executable to be GPL. Let’s start. Create a new ECO Winform Application project. Save the project with the name ECOBackup. We will need persistence in order to store the project definitions we create with our utility, so we will define that first. Due to the nature of this project, simple XML storage will be ideal. In the Project Manager, find the EcoBackupEcoSpace and open it. In the tool palette, under the Enterprise Core Objects node, there is a PersistenceMapperXML component that can be dropped on our ECO Space. Keyboard shortcut: Focus the tool palette with Ctrl-Alt-P, then just type “pe” and the palette will display the ECO persistence components. Scroll down to the PersistenceMapperXML and hit Enter. In the Object Inspector for the PersistenceMapperXML, we need to set a file name. This can just be “ECOBackup.xml”. You can give it a complete path if desired. At this point take a moment to Save All and compile the project. Then open Winform1 from the Project Manager. In the set of components at the bottom will be one called rhRoot. This is a reference handle used to provide access to the model from the form. In the Object Inspector for rhRoot you will see an EcoSpaceType property and you should now be able to click on the dropdown arrow and select the EcoSpace. As mentioned above, this is a tiny model. There are only four classes, and only three of those will be persisted. We’ll start by defining the necessary attributes and associations to get us started, and we’ll add some extra bits to it as needed. Click on the Model View tab of the project manager and expand the ECOBackup node. There you should see a “Package_1”, open this to get to the model surface. From the tool palette, drag an ECO class on to the diagram and name it Project. This class will represent a single backup project, so we’ll define attributes needed at that level. The attributes that initially need to be added are a Name for the project, and what name to give the backup file being made. Since the goal is to be able to backup somewhere remotely, we will also need information about the destination computer: ServerName, ServerPath, ServerUserID, and ServerPassword. The Project class also needs two public methods: Preview and Backup. Keyboard shortcut: Use Ctrl-W to add attributes and Ctrl-M to add operations to a class. Hide image According to our requirements, for a Project, we need to be able to define folders on the computer that we want backed up, and whether the backup should process a folder’s sub-folders. So we’ll add a second class to the project called Folder. Folder only needs two attributes: Path (String) and Recurse (Boolean). In addition to Folder, we need to be able to define file masks to control which files are backed up, so a 3rd class needs to be created which we’ll call FileMask and it will contain just one string attribute named Mask. Before our project can work, we need to define associations between them. For both the Folder and FileMask classes, there can be one to many of them for each Project, therefore we will add an association to each of these. If you create the associations by first clicking on Project and dragging to the other class, then for both, End 1 will be the Project. For the End 2 property then, we want to change the Multiplicity of each to 0..*. Strictly speaking this is enough, but to make the model better, we should recognize that both Folder and FileMask cannot logically exist apart from a Project, therefore they should be marked Composite in the End 2 Aggregation property. This will give the correct visual representation in the model as well. With this much defined in the model, we could go ahead and start defining the user interface. However, thinking ahead a bit, in order for Project to do its work, either Backup or Preview, it will need to process its Folders and FileMasks in order to generate a list of files to be backed up – which means we need something to store that information in - another class. Drop a new class on the diagram and name it “FileEntry”. Add two attributes, FilePath (string) and FileSize (double). Just like Folder and FileMask, we need to add a one-to-many composite association between Project and FileEntry. An important difference between FileEntry and the other classes in our model is that there is no need to store a FileEntry permanently, it is only needed while Project performs its tasks, therefore we need to mark the Persistence property of FileEntry as transient so that ECO will not bother storing them. Here’s our diagram so far: At this point we are ready to start developing our user interface. We will revisit the model later in order to add some additional details. Go back to Winform1. We’ll start by setting up display for Projects and the ability to create or delete them. Drop a DataGrid and a couple of buttons on the form. For the grid, I found a size of roughly 225 wide by 275 high, and placed at the upper left to be about right. Set the CaptionText of the DataGrid to “Projects”. Position the two buttons under it. Name the DataGrid to “ProjectList” and the buttons to “AddProject” and “DeleteProject” respectively. Here we’ll add our first ECO ExpressionHandle component. Name it to “ProjectsHandle” and set its RootHandle to rhRoot in order to connect it to the EcoSpace. The Expression property needs to be set to Project.allInstances, this can just be typed in or you can click on the ellipsis and use the expert to help you – selecting Project from the class node then allInstances from the Ocl Operations node. Now we can connect the DataGrid and buttons. Set the DataSource property of the DataGrid to the new ProjectsHandle. For the buttons you will see a property called RootHandle on EcoListActions, set this also to the ProjectsHandle. You can now set the actions for these buttons. Since they will be operating on the list of Projects, find the EcoListAction on EcoListActions property and set this to Add and Delete respectively. ECO even changes the button captions for you. Finally, for the Delete button, we want to disable it if there are no projects to delete. This can be done using the property EnabledOcl on EcoListActions, set it to self->notEmpty. Because this button is tied to the ProjectsHandle expression handle, “self” in this OCL statement refers to the ProjectsHandle. Drop one more button for now and place it somewhere below the Add and Delete buttons, name this “SaveButton”. Find the EcoAction on EcoGlobalActions property and set it to UpdateDatabase. While not very pretty yet, you can now compile and run this project and you will be able to add and delete projects and edit them in the grid. You can click the Update DB button to save the project to file, and as you can see, the Delete button will correctly be disabled whenever there are no projects in the list. It’s never too early to start making the UI nicer. I prefer to edit records in individual controls instead of grids. Since we will also need to manage other classes as well, we’ll use a Tab Control to divide up the functionality. Drop one down to the right and set its Dock property to Right, then size it to take up all the space right of the Datagrid. Add three tabs and label them “Project”, “Folders”, and “File Masks”, respectively. On the Projects tab, we need an edit control for each of the six current Project attributes and corresponding labels. Now we could hook these edit controls directly to the ProjectsHandle handle and everything would work, however we will soon need to access the current project in code anyway and to do that we will need a CurrencyManager, therefore we’ll do that now. .Net binding is designed to allow any list type component (DataGrid, Listbox) link to many kinds of data containers whether a DataSet, DataView, ArrayList, or an ECO ExpressionHandle. However, the interface that allows this has no concept of a current position in the list. This is done separately via a BindingContext. The ECO CurrencyManager wraps this functionality. Drop a CurrencyManager on the form and name it to “ProjectsCM”. Set its RootHandle to ProjectsHandle and its BindingContext to the ProjectList Datagrid. We’ll now be able to use this CurrencyManager to hook up to the currently selected Project. For each of the edit controls, in the DataBindings.Text property, you’ll now be able to select the desired attribute from the ProjectsCM handle. Don’t forget to set the PasswordChar property of the edit control hooked to the ServerPassword attribute! Now that we have separate edit controls hooked up, we don’t need the Datagrid to be editable, or to show all attributes. The first thing to do is set its ReadOnly flag to True. Now click the ellipsis of the TableStyles property and in the dialog add a TableStyle. Click its GridColumStyles property ellipsis. Here you can add a Member, set its HeaderText to “Name” and select the Name attribute in the MappingName property. You can also set the column width here. Here’s our form so far: Now let’s add functionality for Folders and File Masks. On the Folders tab we need another Datagrid and a couple of buttons to add and delete folders. These can be laid out any way desired, each line of the grid will display a folder path. For the DataGrid, you can turn off the CaptionVisible property since we already know we’re on the Folders tab. To power these controls, we need a new ExpressionHandle. Drop one down and name it “FoldersHandle”. Since we want this handle to present the set of folders linked to the currently selected Project, we need to set this expression’s RootHandle to the CurrencyManager, ProjectsCM. This is very much like creating a master/detail link between two datasets in Win32 Delphi applications. The expression property needs to access the list of folders. Since the FoldersHandle is tied to the current Project, this means that “self”, specified in the Expression property, will refer to that Project object. Because of the association between Project and Folder in the model, there will be a Role available in the Project object called Folders. Thus the Expression property needs to be set to self.Folders. Now the grid can be hooked to the FoldersHandle via its DataSource property. On doing this, the grid will display all three members – the 3rd being the Project this object belongs to. We don’t need the Project to display here. This is solved simply by adding a TableStyle to the grid, adding a GridColumnStyle to that and adding two columns, setting these to the Path and Recurse attributes respectively. Set the column widths while there. For the Delete button, set the RootHandle on EcoListActions to the FolderHandle, the EcoListAction on EcoListActions to Delete, and the Enabled on EcoListActions to self->not Empty. For the Add button, we can’t use the EcoAction property because we need to prompt the user to enter a folder path, so we need to write our first code here! Label the Add button appropriately, and then double click the Add button’s Click event. The following code will do what we need. After typing in this code, you will notice that LastBrowsePath has not been declared. We can use the Declare Field refactoring feature to do this (from the menu or Shift-Ctrl-D), set the type to string. This variable is not necessary, but simply adds a nice touch – each time the user selects a folder, it will start the browse dialog in the location that was last selected from. var f: Folder; p: Project; dlg: FolderBrowserDialog; begin dlg := FolderBrowserDialog.Create; try dlg.ShowNewFolderButton := False; dlg.SelectedPath := LastBrowsePath; if dlg.ShowDialog(Self) = System.Windows.Forms.DialogResult.OK then begin f := Folder.Create(EcoSpace); f.Path := dlg.SelectedPath; p := ProjectsCM.CurrentElement(ProjectList).AsObject as Project; p.Folders.Add(f); LastBrowsePath := dlg.SelectedPath; end; finally dlg.Free; end; The above code presents a folder browser to the user to allow a selection and, if selected, adds a new Folder object to the Project. The try/finally block isn’t really needed here since it will be garbage-collected anyway, but good habits die hard. As you can see, creating a new object in code and adding it as a member of another object’s list is very simple in ECO. The only line that looks weird is the one getting access to the current Project object. We use the CurrencyManager object to get the current element from the ProjectList Datagrid. We need to use the AsObject property of that element to get an actual Project object, and finally it needs to be cast as a Project object in order to assign it to our variable. The Folders tab is now functional, the project can be run and tested. The grid is left editable so the Recurse attribute can be edited to True or False (this could be enhanced to be done with a button or checkbox, to do so would also require another CurrencyManager for the Folders list). Different folders can be assigned to different projects and all is saved properly. The File Masks tab will be similar, but here we’ll just use a Listbox instead of a DataGrid. Again we need two buttons to add and delete File Masks, and we need a TextBox to allow entry of masks. Lay these out as desired, the ListBox does not need to be too wide. Once again we need an ExpressionHandle, drop one down and name this one “MasksHandle”. Again its RootHandle will be ProjectsCM and the expression will be self.FileMasks. For the Listbox, name it “MaskList” and set its Datasource to the MasksHandle. In addition, set its DisplayMember property to the Mask attribute. You can optionally set Sorted to True. Name the textbox to “MaskText”. Using the same pattern as described for the Delete button on the Folder tab, the delete button for File Masks can be hooked up also using the MasksHandle. Again like the Add button on the folders tab, set its caption and then create a Click event for it. The code needed for adding a File Mask is as follows: var fm: FileMask; p: Project; begin if MaskText.Text.Trim = '' then begin MessageBox.Show('Please enter file mask specification'); Exit; end; if MaskList.FindStringExact(MaskText.Text) >= 0 then begin MessageBox.Show('File mask already added'); Exit; end; fm := FileMask.Create(EcoSpace); fm.Mask := MaskText.Text; p := ProjectsCM.CurrentElement(ProjectList).AsObject as Project; p.FileMasks.Add(fm); end; Most of the above code is merely checking that there is something entered and that it isn’t duplicating an already added mask. Then it simply creates a new FileMask object, sets its Mask attribute, and adds it to the current Project object. At this point we can completely create and configure backup projects. One of our main requirements was to be able to preview a backup as well as execute it and we have endowed our Project class with a Preview method. Now it’s time to implement it. We need a place to display the preview – the list of actual files that would be backed up by the Backup method. We can add another tab to the Tab control and label it Preview. To this, add a DataGrid named “PreviewGrid”, and a button labeled “Preview”. Again we need an ExpressionHandle to power this feature, add one and name it “FileEntriesHandle”. The RootHandle will once again be ProjectsCM, and the Expression will be self.FileEntries. Link the Datagrid up by setting the DataSource to FileEntriesHandle. Once again it will show the unneeded Project column in the grid. Get rid of this as before by adding a TableStyle and defining just two columns for the FilePath and FileSize attributes. Create a Click event for the Preview button. The code needed here is: var p: Project; begin p := ProjectsCM.CurrentElement(ProjectList).AsObject as Project; p.Preview; end; As elsewhere, we need to get access to the current Project. Then we call the Preview method of the Project. Of course we don’t yet have any functionality in the Preview method. We’ll fix this now. Go to the model and right click on the Preview method in the Project class. Here you can click on “Go to Definition”. This takes you to the interface declaration of Preview (actually the attribute line above it). Move down to the Preview method and you can use Ctrl-Shift-DownArrow to move to the implementation section. In this method, you only need type one line: BuildEntryList; Now of course we need to define the BuildEntryList method. We’re placing this in a separate method because our Backup method is also going to need to call this. Following is the BuildEntryList method. Note that you need to add the System.IO namespace to the unit’s Uses clause. procedure Project.BuildEntryList; var fld: Folder; di: DirectoryInfo; // find requested files for passed directory procedure ProcessMask(d: DirectoryInfo); var mask: FileMask; fi: FileInfo; files: array of FileInfo; fe: FileEntry; begin // apply each mask in turn for mask in FileMasks do begin files := d.GetFiles(mask.Mask); for fi in files do begin fe := FileEntry.Create(self.AsIObject.ServiceProvider); fi.Refresh; fe.FileSize := fi.Length; fe.FilePath := fi.FullName; self.FileEntrys.Add(fe); end; end; end; // recurse folders from passed starting point procedure RecurseFolders(di: DirectoryInfo); var dirs: array of DirectoryInfo; di2: DirectoryInfo; begin dirs := di.GetDirectories; for di2 in dirs do begin ProcessMask(di2); RecurseFolders(di2); end; end; begin FileEntrys.Clear; for fld in Folders do begin di := DirectoryInfo.Create(fld.Path); ProcessMask(di); if fld.Recurse then begin RecurseFolders(di); end; end; end; This method makes use of Delphi nested procedures and should make the code easier to understand. The mainline of the method starts by clearing any existing FileEntry objects from the Project. It then loops through the list of Folder classes that have been added by the user for this Project. For each, it calls ProcessMask to find and add any matching files in that folder. It then checks to see if it should recurse sub-folders, and if so, calls RecurseFolders. RecurseFolders is a recursive procedure. It asks the passed DirectoryInfo object for a list of sub-folders. If any are returned, it loops through them, calling ProcessMask and then calling itself in order to continue the recursion. This will continue for any depth of sub-folders. ProcessMask loops through each of the FileMask objects the user has added and, for each, asks the passed DirectoryInfo object for a list of matching files (much easier then the equivalent FindFirst/FindNext/FindClose technique needed in Win32!). For each file found, a FileEntry object is created and added to the Project’s FileEntrys list. Note the FileInfo object returned by the system must be refreshed in order for it to correctly report the size of the file. With this complete, we have some actual functionality, run the application and, with folders and masks defined, go to the Preview tab and click the button! Before we can add the functionality, first we need to make a reference to the needed zip dll. As noted at the beginning of this article, you need to download and install SharpZipLib. We also need to reference the Indy components in order to use its FTP component. Right click on the References node in the Project Manager and click Add Reference. Here in the list you should be able to find the needed Indy assemblies, these are IndyCore, IndyProtocols, and IndySystem. Highlight these 3 and click Add Reference. You can then click the browse button to find the ICSharpCode.SharpZipLib.dll assembly, wherever you installed it. Clicking OK on this dialog will add the four selected references to the project. You will then also be able to add these to the Uses clause. Add a new button on the main form under the ProjectList datagrid and label it “Backup”. Name it as “BackupButton” and create a Click event for it. The Click event will contain the following code: var p: Project; begin BackupButton.Enabled := False; try p := ProjectsCM.CurrentElement(ProjectList).AsObject as Project; // clear the file list display p.FileEntrys.Clear; if PreviewGrid.Visible then PreviewGrid.Update; p.Backup; finally BackupButton.Enabled := True; end; Here we use a try/finally block to disable the Backup button and re-enable it at completion, just to ensure it cannot be clicked again while a backup is in progress. As usual, we get the current Project object and clear out any FileEntry objects it may be holding. To make the display a little cleaner, we also update the PreviewGrid to show it empty prior to starting the backup. It will be regenerated by the backup process. Finally, we call the Backup method. Find your way to the Project class’ Backup method. In that package unit, add the following references to the Uses clause: ICSharpCode.SharpZipLib.Zip, ICSharpCode.SharpZipLib.Core, IDFTP, and IDComponent. Now we can add the code for the Backup method.); // now process the entries for fe in FileEntrys do begin zentry := ZipEntry.Create(fe.FilePath); infile := &File.OpenRead(fe.FilePath); SetLength(buffer, infile.Length); infile.Read(buffer, 0, infile.Length); zip.PutNextEntry(zentry); zip.Write(buffer, 0, infile.Length); end; zip.Finish; zip.Flush; memfile.Position := 0; // upload to a server? if ServerName <> '' then begin // yes ftp := TId; try := ServerName; := ServerUserID; := ServerPassword;;;(memfile, BackupName); finally; end; end else begin // save locally infile := &File.OpenWrite(ServerPath + '\' + BackupName); memfile.WriteTo(infile); infile.Close; end; memfile.Free; zip.Close; The first thing Backup does is call the BuildEntryList method we created earlier. This gives it an up-to-date list of files to be backed up. Then we make sure there’s a name for the backup file, if one was not specified then we generate one combining the Project name with the current timestamp. We then create a zip file using a memory stream and add each of the target files to it. Finally, if server information has been specified, we attempt to FTP the file to the specified location on the server, otherwise we assume the ServerPath attribute is a local file path and attempt to save the zip file to there. We now have a fully functional backup utility. However, it has one major flaw: there is no feedback of any kind while it’s performing a backup, no way to see its progress. Typically, a backup utility is going to have a progress meter, and usually displays the file names as they are processed, so we’ll do that. We’d like to get feedback from our Project object as it’s performing its work. However, under no circumstances do we want the model to know anything about our user interface, thus it cannot directly access our form. In order to get feedback, we need to observe our Project object. ECO implements the Observer (also know as Publish and Subscribe) pattern in all ECO classes you define and provides the necessary methods to let you set up such subscriptions. You can observe an object or a specific attribute (property) of an object. We will add some new attributes to our Project class specifically to provide information about its progress. The attributes we will add are as follows: BackupSize: Int64 ProgressPoint: Integer ProgressState: string Because these are only intended for use while the Project object is performing a backup, we do not want these attributes to be stored when saved to file. Therefore be sure to set the Persistence property of all three of these to Transient. Now we need to add some code to make use of these attributes. Navigate to the BuildEntryList method and as the first line of its (main) code, add: ProgressState := 'Preparing File List'; We will want to report the status of the FTP process, so we need to provide a couple of event handlers to hook to. These will look as follows, use code-completion after entering the code in order to declare them in the class: procedure Project.FTPStatus(ASender: TObject; const AStatus: TIDStatus; const AStatusText: string); begin ProgressState := AStatusText; end; procedure Project.FTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: integer); begin ProgressState := 'Writing ' + AWorkCount.ToString('N0') + ' of ' + BackupSize.ToString('N0'); end; In the Backup method, there are a number of additional lines to be added, rather than listing each one, here is the complete backup method again with the new lines in bold. procedure Project.Backup;); ProgressState := 'Compressing Files'; ProgressPoint := -1; // tell subscribers to initialize ProgressPoint := 0; // start // now process the entries for fe in FileEntrys do begin ProgressState := fe.FilePath; zentry := ZipEntry.Create(fe.FilePath); infile := &File.OpenRead(fe.FilePath); SetLength(buffer, infile.Length); infile.Read(buffer, 0, infile.Length); zip.PutNextEntry(zentry); zip.Write(buffer, 0, infile.Length); ProgressPoint := ProgressPoint + 1; end; zip.Finish; zip.Flush; BackupSize := zip.Length; ProgressState := 'Writing Backup File'; memfile.Position := 0; // upload to a server? if ServerName <> '' then begin // yes ftp := TId; try := ServerName; := ServerUserID; := ServerPassword; := FTPStatus; := FTPWork;;;(memfile, BackupName); finally; end; end else begin // save locally infile := &File.OpenWrite(ServerPath + '\' + BackupName); memfile.WriteTo(infile); infile.Close; end; memfile.Free; zip.Close; ProgressState := 'Backup complete'; end; To take advantage of subscriptions, the observer must implement the ISubscriber interface. ISubscriber is defined in the Borland.Eco.Subscription namespace, so add this to the Uses clause of the form. We can then alter our form to implement the interface by changing the first line of the form definition to be: TWinForm1 = class(System.Windows.Forms.Form, ISubscriber) The ISubscriber interface requires two methods to be implemented, these are IsAlive and Receive. The IDE can help here, just scroll down to the bottom of the TWinform1 class and, in the public section, hit Ctrl-Space, Delphi will show you a list of overrideable methods with IsAlive and Receive at the top and in red. Highlight both of these (the list allows multi-select) and hit return, then Shift-Ctrl-C to create the implementation stubs. The IsAlive method needs only one line – set the Result to True to indicate you want the subscription to continue. Before implementing the Receive method, let’s set up the subscriptions. These will go in the click event of the Backup button, just before the call to Backup: p.AsIObject.Properties['ProgressState'].SubscribeToValue(self); p.AsIObject.Properties['ProgressPoint'].SubscribeToValue(self); Underlying our Project (and other) objects, is an ECO object that implements the plumbing ECO needs to do its work for us. The AsIObject property gives us access to that underlying object and the Properties property gives access to the plumbing for our individual properties. The ability to subscribe exists at that level. The above lines set up a subscription for our form (self) on two of the attributes we added. When passing self, we are actually passing the ISubscriber interface we’ve implemented, and so ECO will now be able to call our Receive method whenever either of these Project attributes changes. We now need to add a couple of items to our user interface to display progress, a label and a progress gauge. Name them “ProgressLabel” and “ProgressBar” respectively. Below is the code for the Receive method. The first line gets the actual attribute that has changed. When the type of the object is a string, it must be ProgressState that has changed, if an integer, then it must be ProgressPoint. If an integer, we check if it is -1, the signal from Project that it is about to start the counting, this gives us an opportunity to initialize our progress gauge. var o: TObject; p: Project; begin o := (ElementChangedEventArgs(e).Element.AsObject); if o is string then begin ProgressLabel.Text := o.ToString; ProgressLabel.Refresh; end else if o is Integer then begin if Integer(o) = -1 then begin p := ProjectsCM.CurrentElement(ProjectList).AsObject as Project; ProgressBar.Value := 0; ProgressBar.Maximum := p.FileEntrys.Count; end else if Integer(o) <= ProgressBar.Maximum then begin ProgressBar.Value := Integer(o); end; ProgressBar.Refresh; end; Result := True; end; You should now be able to compile and run the application and, pressing the backup button on a project, you should see visible feedback. This way of doing things is acceptable for our purposes; however, if your application needs to set up subscriptions to many different classes or attributes, then trying to sort it all out in a single Receive method is going to get ugly very quickly and becomes almost impossible as soon as you need to receive two attributes of the same type. Fortunately, because subscriptions are done using interfaces, we can easily create a separate class to handle individual subscriptions, create as many of these as we need, and use event handlers to get the subscription events into our main form for processing. Because this class will be handy for any project needing such subscriptions, we’ll put it in its own unit. Create a new code-only unit (File | New | Other | Delphi for .Net Projects | New Files | Unit). Save this file as “ECOSubscribe.pas”. The unit should look like this: unit ECOSubscribe; interface uses Borland.Eco.Subscription; type TECOSubscriber = class(TObject, ISubscriber) private FOnReceive: EventHandler; published public function IsAlive: Boolean; function Receive(sender: TObject; e: EventArgs): Boolean; procedure set_OnReceive(const Value: EventHandler); property OnReceive: EventHandler add FOnReceive remove set_OnReceive; end; implementation { TECOSubscriber } function TECOSubscriber.IsAlive: Boolean; begin Result := True; end; function TECOSubscriber.Receive(sender: TObject; e: EventArgs): Boolean; begin if Assigned(FOnReceive) then FOnReceive(Self, e); end; procedure TECOSubscriber.set_OnReceive(const Value: EventHandler); begin FOnReceive := Value; end; end. This class acts as a relay, it is able to receive calls from a subscribed object and pass that call onto whoever attaches to its OnReceive event. We can create an instance of this class for each subscription we wish to make, and attach a different event handler to each one. We can now improve our implementation in the main form. Add ECOSubscribe to the main form’s Uses clause. In the main form’s private section, add the following declarations: FProgressState: TECOSubscriber; FProgressPoint: TECOSubscriber; procedure ProgressStateChanged(sender: TObject; e: EventArgs); procedure ProgressPointChanged(sender: TObject; e: EventArgs); Complete the procedures with Shift-Ctrl-C and add code to the implementations so they look as follows: procedure TWinForm1.ProgressStateChanged(sender: TObject; e: EventArgs); begin ProgressLabel.Text := (ElementChangedEventArgs(e).Element.AsObject).ToString; end; procedure TWinForm1.ProgressPointChanged(sender: TObject; e: EventArgs); var p: Project; point: integer; begin point := Integer(ElementChangedEventArgs(e).Element.AsObject); if point = -1 then begin p := ProjectsCM.CurrentElement(ProjectList).AsObject as Project; ProgressBar.Value := 0; ProgressBar.Maximum := p.FileEntrys.Count; end else if point <= ProgressBar.Maximum then ProgressBar.Value := point; end; This is much nicer than our catch-all Receive method since we don’t have to guess what object is being sent or figure out how to distinguish from, say, two different string attributes. We need to create instances of our ECOSubscribers and attach our event handlers to them. This is added to the main form’s Create event following the line setting the EcoSpace active: FProgressState := TECOSubscriber.Create; Include(FProgressState.OnReceive, ProgressStateChanged); FProgressPoint := TECOSubscriber.Create; Include(FProgressPoint.OnReceive, ProgressPointChanged); Now we can change our subscriptions to use the ECOSubscribers instead of the form directly (this is in the Backup button’s Click event): p.AsIObject.Properties['ProgressState'].SubscribeToValue(FProgressState); p.AsIObject.Properties['ProgressPoint'].SubscribeToValue(FProgressPoint); Finally, with that complete, we can remove Winform1.IsAlive and Winform1.Receive, and remove ISubscriber from the Winform1 class declaration. You should be able to recompile and successfully run the project with the feedback working as before. While out application is now pretty complete, there are still a number of improvements that can be made. These improvements show additional ECO features and abilities. The first thing we’ll correct is an annoyance: when you create a new Project, that Project does not become current, whatever Project was selected previously remains current. This is simply the way the controls work in .Net. To fix it, we need to attach to an event provided by the IBindingList interface of the ProjectsList datagrid and in that event handler, make the new Project current. To do this, manually add the following event handler then use Shift-Ctrl-C to complete it (this assumes you have not renamed the default form name from WinForm1, if so then edit it appropriately): procedure TWinForm1.ProjectsChanged(sender: TObject; e: ListChangedEventArgs); begin // if new project added set focus to it if e.ListChangedType = ListChangedType.ItemAdded then ProjectsCM.Position := ProjectsHandle.GetList.Count - 1; end; Find the Load event for the form in the Object Inspector and create a handler for it. In that handler, add the following code: Include((ProjectsHandle as IBindingList).ListChanged, ProjectsChanged); One last detail here: go into the TableStyle of the ProjectsList and set the column definition to be Read-only. Without this, it seems the first time a row is added, the ItemAdded event does not happen (it gets a Reset event instead). Now when a new Project is added, it will become the current Project as well, ready to edit. While we’re on new Projects, we can add a minor improvement: instead of leaving the Project Name blank, we can default it to something. To do this, return to the ECO model diagram. Click on the Name attribute of the Project class, and in the Object Inspector, set the Initial property to “<New Project>”. You can define default values for any of a class’ attributes this way. It can be frustrating to set up a backup project, and then forget to click the Update DB button before exiting, so let’s check for any unsaved changes. The form has a Closing event, create an event handler for it. Here’s the body: var res: System.Windows.Forms.DialogResult; begin if EcoSpace.DirtyListService.HasDirtyObjects then begin res := MessageBox.Show('There are unsaved changes.'#10#13 + 'Press Yes to save them, No to exit without saving, ' + 'or Cancel to continue editing.', 'Unsaved Changes', MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if res = System.Windows.Forms.DialogResult.Yes then EcoSpace.UpdateDatabase else if res = System.Windows.Forms.DialogResult.Cancel then e.Cancel := True; end; end; To do this we need to determine if the user has clicked on a column header and, if so, which one. Then we need to manually change the OCL Expression of the FileEntries expression handle. Create an event handler for the PreviewGrid’s MouseUp event that looks like this: var hit: DataGrid.HitTestInfo; fld: string; begin hit := PreviewGrid.HitTest(e.X,e.Y); if hit.&Type = DataGrid.HitTestType.ColumnHeader then begin case hit.Column of 0: fld := 'FilePath'; 1: fld := 'FileSize'; end; if FileEntriesHandle.Expression.StartsWith('self.FileEntrys->orderBy') then FileEntriesHandle.Expression := fld.Format('self.FileEntrys->orderDescending({0})', fld) else FileEntriesHandle.Expression := fld.Format('self.FileEntrys->orderBy({0})', fld); end; end; It would be convenient to be able to see when a project was last backed up, so we’ll add a new attribute to the Project called LastBackup (DateTime). Open the model diagram and add this to the Project definition. Save and compile the application. Now add a new column to the TableStyle in the ProjectList datagrid. You should be able to map this to the new LastBackup field. Set this new column to Read-only. Set the header and adjust the size of both columns. At the end of the Project.Backup method, add the following line: LastBackup := DateTime.Now; There are certainly other improvements you can add to this project. For example, it is possible exceptions could be raised when attempting to read a file requested for backup (perhaps it is locked or you do not have permissions for that file). One way reporting for this could be handled would be to add a Boolean Error attribute to the FileEntry class along with an ErrorText string and, if there is an error while processing this file, set these attributes. On completion of the preview or backup, you can now query the FileEntry objects for those that have an error using another Expression Handle and display these in another grid. The complete project can be downloaded from. Hopefully this article gives you a taste of how ECO can be an advantage even for small projects such as this. Download Delphi 10 now! Webinars on demand! More social media choices: Delphi on Google+ @RADTools on Twitter Server Response from: ETNASC04
http://edn.embarcadero.com/article/33669
CC-MAIN-2018-09
refinedweb
6,374
65.01
"A.M. Kuchling" <amk at amk.ca> wrote in message news:<vu-cnZQgo5841mWjXTWcrg at speakeasy.net>... > On 24 Jun 2003 01:52:27 -0700, > Paul Boddie <paul at boddie.net> wrote: > > The thing is that Python and its developers quite often have to live > > (and work) alongside other technologies; having a set of common APIs > > is important if you consider them in that context. > > In practice, there's no way to access those other technologies from Python. > There's a Python wrapper for the Xerces DOM implementation, but I never hear > about anyone using it; there's a wrapper for libxml2, but it has its own > API that's somewhat similar to ElementTree (but not as nice to use -- > someone should fix that, because libxml2 is blazingly fast). Yes, it's very tempting to write a PyXML-style DOM API for it. Then we can use XPath (whether it be from PyXML or 4Suite) on our documents without having to port our source code just because some underlying implementation detail has changed. > So any DOM implementation you use will likely have been built by the Python > world, and could have been written to a standard interface. Jython users could > use the Python interface or use the Jython mapping of Java interfacers. There is/was a certain amount of Java API support in PyXML that I wouldn't mind looking more closely at with Jython. PyXML's DOM API isn't radically different from the JAXP API, but there are advantages in being able to play with both standards, and the marginal benefits of PyXML's API are good enough for me at least. > When you think about it: how useful is it that the Python DOM interface uses > the same method names as the Java or Perl interface? What's gained by this? Experience that is portable between the languages/environments. Otherwise, one could easily be left guessing about certain mechanisms. How does one represent node names in the canonical "Pythonic" API? Simple strings with or without prefixes which are registered elsewhere (cf. XPath), tuples with such prefixes and local-names, tuples with namespaces and local-names? And so on... [...] > In this context, I find the existence of jDOM, a Java-centric DOM-like API, > to support this view. There's even a jDOM JSR, the Java world's equivalent > of a PEP. Yes, there's JDOM, DOM4J, XOM and loads of other Java packages that all have subtle incompatibilities and are only interchangeable thanks to packages like Jaxen. It doesn't help that even Sun Microsystems mix some of them together in their more recent, bizarre APIs (where they could have just used the DOM in many respects anyway), meaning that all of a sudden you're dealing with DOM4J objects which have method names which are just slightly different from the official DOM method names, and you find yourself asking, "Why TF did they see it as absolutely necessary to make their interfaces different even though the methods do practically the same thing? Is it just to be fashionably different?" In my opinion, one of the things that has made Java more attractive for XML processing has been the increasing standardisation. Once JAXP broke through, it arguably became less likely that one would come up against code that was specifically written for a particular special API. Moreover, one would need a very good reason to specifically target something like DOM4J these days, in my opinion. Anyway, those are my perspectives, but I guess they have evolved in their own way because I unfortunately have to spend pretty much all of my working hours not using Python. Paul
https://mail.python.org/pipermail/python-list/2003-June/228692.html
CC-MAIN-2016-36
refinedweb
609
68.1
Exercise 1: Dust off that Compiler In this second exercise, its all about writing code and seeing what happens. Click here for the tutorial’s index page. This is the code snippet for this exercise. #include <stdio.h> /*This is a comment*/ int main(int argc, char *argv[]) { int distance = 100; //This is another comment printf("You are %d miles away \n", distance); return 0; } Compiling To compile it you have to use make. GNU Make is a tool which controls the generation of executables and other non-source files of a program from the program’s source files. Make gets its knowledge of how to build a. But for now we shall not create/modify our make file. make ex1 Before we execute our program we need to check for errors(debug) using a special tool called lldb. The LLDB Debugger (LLDB) is the debugger component of the LLVM project. It is built as a set of reusable components which extensively use existing libraries from LLVM, such as the Clang expression parser and LLVM disassembler. LLDB is free and open-source software. lldb ex1 When it reports no errors, then you can exectute the program. To exit from lldb, just type: exit and hit enter. ./ex1 You are 100 miles away What I’ve Learnt First of all by running: man printf I got to realise that it was developed by MacKenzie and it takes a variety of parameters. To check how printf works, I shall run the above code but remove the last variable parameter and see what my program tells me. Here we go… printf("You are %d miles away \n"); The compilation stage passes with no errors. I then execute it to see what happens. This is the result I get. You are -969057704 miles away The reason why I get the negative result is because printf and C operate on raw memory. In C there is no virtual machine that protects the programmer from such errors. Its Raw memory as it is. Because C expects there to be a parameter it find nothing so returns whatever memory is available at the expected point. That is how raw things get here. I then check with lldb on whats happening inside.
https://wilfred.githuka.com/post/ex1/
CC-MAIN-2020-24
refinedweb
374
73.07
In our earlier blog The Tale of ‘Tail Recursion’, we have talked about tail recursion. And In this blog, we will be talking about limitation of tail recursion and its solution in scala. Unfortunately JVM doesn’t support tail call optimization, but scala does as we have seen. However, what if we are not doing simple tail recursion like we usually do. What if on the other hand we have a function where we don’t call the function from itself but we are doing something little different. def isEven(x: Int): Boolean = if (x == 0) true else isOdd(x – 1) def isOdd(x: Int): Boolean = if (x == 0) false else isEven(x – 1) Here i have defined both function as tail recursive, instead of that it gives stack overflow exception. But what’s the problem? The problem manifests itself in the stack trace: even calls odd, then odd calls even, which calls odd again. Each of these invocations causes the creation of a stack frame, eating away the space that’s reserved for them. Keeping all the stack frames would not really be necessary: when even calls odd, that is the very last thing that the even function will ever do! When odd returns, even itself returns immediately with that same value. This jumping back and forth between isEven() and isOdd() functions is the trampoline effect. In general, we have two tail recursive functions F(A) and G(A) and that F(A) calls G(A) but in turn G(A) also calls F(A) Then F(A) is said to be a trampoline tail recursive function because the call stack jumps back and forth between the two functions F(A) and G(A) – hence the name trampoline. The Scala compiler implements tail-recursion optimization for methods which call themselves in tail position, allowing the stack frame of the calling method to be used by the caller. It does this essentially by converting a provably tail-recursive call to a while-loop, under the covers. However, due to JVM restrictions there’s no way for it to implement tail-call optimization, which would allow any method call in tail position to reuse the caller’s stack frame. This means that if you have two or more methods that call each other in tail position, no optimization will be done, and stack overflow will be risked. Because of these limitations, you need to be careful when using recursion in Scala. When writing programs, you will need to keep in mind how both the compiler and the JVM work. Solution: Using @tailrec annotation, it ensures that function is tail recursive, otherwise it will trigger an error if the function is not actually tail-recursive. So this will protect you from accidentally changing a function that you want to be tail-recursive function into something that’s no longer tail recursive. To make anyone function to be tail recursive, there could be one possible solution. @tailrec def isEven(x: Int): Boolean = { if (x == 0) true else if(x == 1) false else isEven(x – 2) } def isOdd(x: Int): Boolean = !isEven(x ) Since i have made ‘isEven’ function to be tail recursive, now Scala compiler will be able to optimize it. Another solution is to use trampoline. Think for a minute, recursion as an infinite series of functions to evaluate. And the minute you think about this infinite series of functions to evaluate what you normally do at every single stage you got a function on your hand, either you evaluate it if there’s more to do or you are done if there is result. In other words, you can quickly turn into a lazy computation to say, keep calling it until there is no more work to do. So, it becomes a lazy infinite series problem if you wanna think about that way. Trampoline is a higher order function that takes a function as an argument and returns a new function – combinator. This new function(combinator) on invocation, will continuously call the original function passed to trampoline as long as it returns another function to execute. Once it gets back a result that is not a function, it stops executing and just returns the result of the last call. Well thankfully, we don’t need to do much work done, it is already done for us. We just need to import: scala.util.control.TailCalls._ Scala has a utility object called TailCalls that makes it easy to implement a trampoline. The mutually recursive functions have return type TailRec[A] and return either done[result] or tailcall(fun) where fun is the next function to be called. import scala.util.control.TailCalls.{ TailRec, done, tailcall } def isEven(x: Int): TailRec[Boolean] = if(x == 0) done(true) else tailcall(isOdd(x – 1)) def isOdd(x: Int): TailRec[Boolean] = if(x == 1) done(true) else tailcall(isEven(x – 1)) Now when i run this, notice it didn’t fail but instead, it gives a call object.What is that! it simply says i am going to be absolutely lazy so when you go and call the isEven method, isEven laid back and lazy it says i am not gonna do real work for you, i am just going to give you this call object say when i am done so this is absolutely lazy evaluation isn’t it. So how do i get the result out of it ? To obtain the final result from tailrec object, we use the result method. And you can see when you call the result method, it produces the result. So you can start going very large number of values and you can see it is evaluating. Let understand how it works: I am going to call isEven method with zero. Notice the object you got back on hand it is a done object you got back so what is done object ? A done object simply says i have got a result with me i have no computations to do and if you ever call me i will give you this result right that’s all it says. On the other hand, if you don’t call it with 0 but you call it with 1 Notice you got a call object and not a done. What is a call object? A call object says i am also a TailRec object so they both are inheriting from TailRec, while the done says i am the terminal object, i have no more work to do and the call object says i am going to sit here when you call me i will invoke the function, i carry with me and simply get you back the result of that function and be done with it and the result of that function either be a done or another call and you got to go back and call one more time then if you never call it you don’t really progress any further so it is extremely lazy until you on demand keep evaluating it until you get to the very end so you can imagine what the result is going to do when you call result on it, the result is the one that simply sit there in loop through and say keep calling it repeatedly until you get a done object. So it turns a recursion into a while loop and as a result we would never run into a stack overflow exception. So under the hood, we are just doing lazy evaluation. So when you say “.result”, it is repeatedly evaluating the value over and over and getting the result for us eventually. Hope that this blog is helpful for you. References: 1 Programming in Scala By Martin Odersky, Lex Spoon, and Bill Venners 2 3 Scala for Impatient By Cay S. Horstmann
https://blog.knoldus.com/2017/05/08/jump-higher-with-trampoline/
CC-MAIN-2017-26
refinedweb
1,305
65.46
I'm trying to use the GData API to synch some text files with Google Docs. When executing this through a plugin or the console: import urllib2 f = urllib2.urlopen("") I immediately get a timeout error: "urllib2.URLError: " I've tried changing the default timeout but it doesn't help. Any ideas? Note: the same code works when I execute it through my local Python 2.5.4 shell The initial code snippet works ok for me when I paste it into my console (i.e., there's no error, and I can call f.read() and get back the contents). Could this be a proxy issue of some sort? I found the problem.For some reason my _ssl.pyd file was last modified in 2006, while all the .pyd files in the same directory were last modified in 2008. I replaced_ssl.pyd from the one that comes with Python 2.5.2 (same version as sublime's) and it's working now. It's probably a bug in the installer then When I install a new beta, _ssl.pyd gets overwritten with the old (broken) 2006 version
https://forum.sublimetext.com/t/performing-an-https-connection/372/3
CC-MAIN-2016-22
refinedweb
188
86.81
Synchronous vs asynchronous MVC controllers Advantage of using asynchronous over synchronous controller in MVC Maybe you did not know but asp.net applications have limited number of threads available to process requests. This value is set in your machine.config in configuration/system.web/processModel node. This file is located at 32-bit %windir%\Microsoft.NET\Framework\[version]\config\machine.config 64-bit %windir%\Microsoft.NET\Framework64\[version]\config\machine.config <processModel maxWorkerThreads="num" maxIoThreads="num" minWorkerThreads="num" minIoThreads="num" ... /> If these values are not set in machine.config the default values are used. Default values for machine.config you can find at MSDN Usually your app does not reach maximum number of threads for your web app to handle requests sent to your app, but if your app depends on some external resource, let's say you are pulling values from Facebook or Twitter. These operations may take some time, so one of your threads will be busy waiting for a response from the external resource which it invoked. You probably will not run into a problem if your web application does not have many IO threads which take a lot of time. The real performance impact can be noticed during a high traffic. This is when async controllers come into the play. Basically you can split your long time operations into multiple threads and get back to working thread when long operation is over. The good thing is that it is really easy to transform your synchronous controller action to async and I'm about to show it in the next example. In the following method we will simulate some long time operation with simple anonymus method which puts thread to sleep for 1000 miliseconds public class SyncController : ApiController { public string get() { return new Func<string>(() => { Thread.Sleep(1000); return "done"; })(); } } While waiting for a response, this action will keep working thread occupied. The following is the same method but with the async operation. public class AsyncController : ApiController { public async Task<string> get() { return await new Task<string>(() => { return new Func<string>(() => { Thread.Sleep(1000); return "done"; })(); }); } } Async controllers are really good thing for optimizing your web application, but it does not mean that you need to rewrite all your controllers in existing applications just to make them async. If controller action does not use any remote resource or some complex logic which takes time or large IO operation, you are pretty good with sync controllers. But this is not where usage of async controller ends. Imagine you have to pull not only data for Facebook posts, but also you need to pull tweets from Twitter API. You can make multiple tasks from one call and tell invoking working thread to wait for all sync actions to complete before it goes back to working thread. Unfortunately I don have Ultimate version of Visual Studio to show you the results of a test, but if you do you can create Web Performance and Load Test Project and test both controller actions and see the difference. Disclaimer Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
https://dejanstojanovic.net/aspnet/2014/july/synchronous-vs-asynchronous-mvc-controllers/
CC-MAIN-2021-04
refinedweb
545
62.17
On Thu, 10 Jul 2008, Andres Salomon wrote: > On Tue, 8 Jul 2008 09:15:14 +0200 > maximilian attems <max@stro.at> wrote: > > > On Mon, Jul 07, 2008 at 10:09:43PM +0200, Frans Pop wrote: > [...] > > > > > > I'm having serious trouble parsing what you're trying to say here. > > > Could you rephrase? > > > > you never checked the rh kernel. they do a *lot* of backporting and > > have a big team working on that. so you'll notice that none of those > > patches landed in ours. so your argument sounds nice, but doesn't > > help in practise. > > > > .26 got a *lot* upstream attention and solves a number of .25 > > regressions. it is wanted for read-only bind mounts, kernel debugger, > > kvm + xen + wireless improvements, allmost net namespaces and uvc cam > > support. > > > > Not to mention OLPC support; it would be *really* nice to be able to > use d-i to install Debian onto an XO. Of course, other things > (grub-under-OFW or just plain OFW support, jffs2 formatting support, > etc) would need to be in place as well for it to work. I haven't kept > up on the status of those things, but I know that people have been > working on them. right forgot to mention PS3 efforts too. thanks -- maks
http://lists.debian.org/debian-kernel/2008/07/msg00377.html
CC-MAIN-2013-48
refinedweb
210
82.75
You’ve written (or are about to write) an API in Grails. Which is quite easy, especially with all the REST API improvements in Grails 2.3. Now you want to ensure your API works correctly when the first users start hitting it with JSON. But you don’t want to write and maintain raw JSON strings – what are some existing libraries you could use to help make testing your API easier? Let’s walk through some quick examples of testing a Grails API with the Grails Rest Client Builder plugin, the Groovy Http Builder library, and the Apache Fluent Http Client library. We’ll use JSON in these examples, but you could easily substitute XML if your API supports that format. Let’s start with a simple Grails API for a Person class with a first and last name. We’ll use the Grails 2.3 @Resource annotation to quickly create the API from the domain class: If your project doesn’t already have a plugin that enables functional testing (e.g. Geb, Webdriver, etc.), then you’ll need to add code similar to this to your scripts/_Events.groovy file to enable the functional test phase. I borrowed this code from the Functional Test plugin: If you do have a plugin that enables the functional test phase, don’t add this to your _Events.groovy file. Otherwise your functional tests may run twice. The Grails Rest Client Builder plugin is built to call Rest APIs from your application code, but it can easily be used to call APIs in your test as well. Here is a quick example of using a GET to retrieve a person: One thing to note when issuing a GET with the REST client builder plugin – I had to set the ‘accept’ type to JSON. Otherwise the plugin defaulted to accepting the String type and the API complained that String was an unsupported type and threw a 415 error. And using a POST to create a new Person: The Groovy Http Builder library provides a handy syntax to call APIs over Http. In these examples we’ll use the RESTClient subset of the Http Builder library since it is geared specifically towards calling Rest APIs and provides a more concise syntax for doing so. First, we’ll issue a GET to fetch an existing Person: Then we’ll POST a new Person to our API: The Apache Http Client library is a popular, well-worn Java library that dates back over a decade, but it is still widely used. We’ll use it’s Fluent version for its powerful and readable builder-like syntax. We’ll start with a GET to grab an existing Person: Then use a POST to create a new Person: I also wrote tests for updating and deleting a Person with PUT and DELETE, those tests are available on GitHub: PUT test and DELETE test I hope these examples will give you a starting place to see what options are available to test your Grails API. And check out the full source code for this testing project on GitHub: Happy testing! One thought on “Grails API Functional Testing” Hi This seems very useul but still i am missing some information in order to get the HTTPClient fluent api working “unable to resolve class Content”, same ofr Request. Are there additional dependencies or imports required? Hi, For enabling functional tests in Grails use the Grails Funky Spock Plugin (). For consuming the API in functional specs, another great client is groovy-wslite (). This client library is quite lighter than Groovy HTTP Builder. I really recommend you to give it a try. Enjoy! Nice post! It helped me a lot. I think it’s a good idea include in _Events.groovy this part from grails functional test plugin too: eventTestSuiteStart = { String type -> if (type == “functional”) { testingBaseURL = argsMap[“baseUrl”] ?: “” if (!testingBaseURL.endsWith(‘/’)) testingBaseURL += ‘/’ System.setProperty(“grails.functional.test.baseURL”, testingBaseURL) } } You can use it in your tests: def baseUrl def setup() { baseUrl = System.getProperty(“grails.functional.test.baseURL”) println “baseUrl: $baseUrl” } def “test get something”() { when: def resp = restBuilder.get(“$baseUrl/something”) ….. If you harcode the complete url you won’t be able to execute those tests to another server with the -baseUrl option
https://objectpartners.com/2014/07/15/grails-api-functional-testing/
CC-MAIN-2019-04
refinedweb
710
69.52
@avan The input was a text file that contained the following: The year 1866 was signalized. Latest posts made by Rachel O - RE: Argument for getc to check for EOF is not working. @avan - Argument for getc to check for EOF is not working. I am trying to read from a text file and print each sentence out with a comma in between each word and once I hit ten words, a new line must start. When I hit a new period, a new sentence marker is printed out. With this code I am able to do all of this. The problem I have is that when I test the code with a certain number of sentence's, there is always a trailing sentence header that is not needed. Output is pictured below. I thought I could solve this from being printed if I added the argument else if(c=='.' && (c=getc(input)) != EOF), but it doesn't work how I thought it would. I have tried moving arguments around and changing them, but nothing I have tried seems to work. If someone could be so nice as to point out what it is that I am doing wrong or not seeing I would be very grateful! #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { FILE *input, *output; char words[100],c; int sentenceCounter=1,wordCounter=0; if (argc < 3) { printf("\nCorrect usage is: ./mimir.out <name of input file> <name of output file>\n\n"); exit(EXIT_FAILURE); } if((input = fopen(argv[1], "r")) == NULL) { printf("\nUnable to open input file \"%s\".\n\n", argv[1]); exit(EXIT_FAILURE); } else { output=fopen(argv[2],"w"); c=getc(input); printf("\nSentence # %d\n",sentenceCounter); printf("--------------------------------------------------------------------------------\n"); while (c !=EOF) { if(c==' '||c=='\n') { wordCounter++; if(wordCounter>=10) { printf("\n"); wordCounter =0; }else { printf(", "); } } if(c==','||c=='\n'||c==' ') { printf(""); }else if(c=='.' && (c=getc(input)) != EOF) { sentenceCounter++; wordCounter=0; printf("\n\nSentence # %d\n",sentenceCounter); printf("--------------------------------------------------------------------------------\n"); }else { printf ("%c", c); } c = getc(input); } } fclose(input); return 0; }
https://askavan.com/user/rachel-o
CC-MAIN-2021-04
refinedweb
343
73.07
We are about to switch to a new forum software. Until then we have removed the registration on this forum. Well, I'm trying to display a random video with this code, but I want to know if I can use more String, and how I can write that. There is another problem: the random video (2Mb, 720x576 resolution, coverted in Internet from .avi to .mov) play in Quicktime very faster than in Processing. The question is... Is JAVA effective to play videos in PROCESSING? import processing.video.*; String[] moviesNames = { "1.mov", "2.mov", "3.mov", "4.mov", "7.mov", "6.mov" }; int index = int(random(moviesNames.length)); int colore = 1; int fondo = 0; Movie[] movies; void setup() { size(640, 480, P2D); movies = new Movie[moviesNames.length]; for (int i = 0; i < moviesNames.length; i++) { movies[i] = new Movie(this, moviesNames[i]); } } void draw() { //background(fondo); image(movies[index], 0, 0, width, height); fill(0,0,0,fondo); noStroke (); rect(0, 0, width, height); } void movieEvent(Movie _mov) { _mov.read(); } void keyPressed() { int k = keyCode; if (k == 'Q') fondo=0; pickRandomVideoIndex(); if (k == 'A') {fondo = 255;} } void pickRandomVideoIndex() { if (movies.length <= 1) return; movies[index].pause(); // pause current video. int rnd; // keep picking a new index till got a diff. 1: while ( (rnd = (int) random(movies.length)) == index ); // assign newly picked random value to index: movies[index = rnd].loop(); // and start playing it. } Answers Got 3 tips below. See if you got any improvements: size(640, 480, JAVA2D); frameRate(25); P.S.: Is that movieEvent() really necessary? Comment that callback function out! (~~)
https://forum.processing.org/two/discussion/comment/25990/
CC-MAIN-2022-05
refinedweb
262
78.55
On Wed, 11 Apr 2001 16:51:57 +1000, Peter Donald wrote: >At 10:55 10/4/01 -0700, David Rees wrote: .. > >Not really - I would see file="log.txt" a configuration of the Facility >rather than a task specific parameter. > Well, then I disagreed with what I understood and agreed with what you intended ;). >> >>I prefer the former approach because (IMO) it makes easier to >>install/uninstall whole approaches for running tasks: >> >><Project context="detailed" ... /> >><Copy context="ignoreMost" ... /> >> >>Now that I have looked at a possible API for what I suggest, I do >>agree that it may not really be simpler for the user since the basic >>user will not even be aware that namespaces are being used. However, I >>do think the flexibility for installing/uninstalling whole contexts is >>key and I am not sure how you propose to handle that from an XML api >>perspective. > >If I understand you correctly you are proposing a generalized version of >recorder task that can configure any facility rather than just logging? If >so then I like that idea and I think namespaces are othogonal to it >(assuming we make a clear distinction between task-specific parameters and >global Facility parameters). I had assumed we would continue to use the >command line for these things but I guess your approach is much better. > Yes, but then that is what I think you intended now also ;). d
https://mail-archives.eu.apache.org/mod_mbox/ant-dev/200104.mbox/%3Cksjvdtck8n6k3bul5fpq1guofhsk5tt19h@4ax.com%3E
CC-MAIN-2021-21
refinedweb
235
59.33
Some Eclipse 4 Application Platform was to make easy things easy by removing the need to know about all the concepts by hiding them using DI. The service responsible to deliver events in application built on top the Eclipse 4 Application Platform is the EventBroker-Service: package org.eclipse.e4.core.services.events; public interface IEventBroker { public String DATA = "org.eclipse.e4.data"; //$NON-NLS-1$ public boolean send(String topic, Object data); public boolean post(String topic, Object data); public boolean subscribe(String topic, EventHandler eventHandler); public boolean subscribe(String topic, String filter, EventHandler eventHandler, boolean headless); public boolean unsubscribe(EventHandler eventHandler); } This is all we need to know (assuming we have already understood how DI-works) to implement our sender and receiver views: public class SenderView { @Inject private IEventBroker eventBroker; private Button b; @PostConstruct void init(Composte parent) { parent.setLayout(new GridLayout()); b = new Button(parent, SWT.PUSH); b.setText("Send Event"); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Date d = new Date(); eventBroker.send("viewcommunication/syncEvent",d); eventBroker.post("viewcommunication/asyncEvent", d); } }); } @Focus void focus() { b.setFocus(); } } These are some fewer lines of code which is good but IMHO the more important fact is that you are independent from OSGi running now so the code you have there is much easier testable by simply mocking IEventBroker! Let’s look now at the receiver side of the story. If you take a look at the IEventBroker you see the subscribe methods which allows us to subscribe to various topics so we could as a first step implement it like this: public class ReceiverView { @Inject private IEventBroker eventBroker;); } }); EventHandler handler = new EventHandler() { public void handleEvent(final Event event) { if( parent.getDisplay().getThread() == Thread.currentThread() ) { viewer.add(event.getProperty(IEventBroker.DATA)); } else { parent.getDisplay().syncExec(new Runnable() { public void run() { viewer.add(event.getProperty(IEventBroker.DATA)); } }); } } }; eventBroker.subscribe("viewcommunication/*",handler); } @Focus void focus() { viewer.getTable().setFocus(); } } This is once more making your code looser coupled because you are independent from OSGi running but we can do even better by fully leveraging the Eclipse DI-Framework. By default Eclipse DI injects data it has stored in its IEclipseContext (you can think of the IEclipseContext as a Map where the value is thing that gets injected into you “POJO”). The important thing for us is that one can extend Eclipse DI to consult other resources like e.g. Preferences (@Preference) and e.g. Event-Data (@EventTopic) – a blog post explaining how this works will follow hopefully soon. So we can rewrite our receiver code like this: public class ReceiverView {); } }); } @Inject void eventReceived(@EventTopic("viewcommunication/*") Date date) { Display d = viewer.getControl().getDisplay(); if( d.getThread() == Thread.currentThread() ) { viewer.add(date); } else { parent.getDisplay().syncExec(new Runnable() { public void run() { viewer.add(date); } }); } } @Focus void focus() { viewer.getTable().setFocus(); } } [Update 2011-02-07] – Start But we can do even better so that we don’t need to take of the UI-Thread syncing all we need to do is use another annotation: @Inject void eventReceived(@UIEventTopic("viewcommunication/*") Date date) { viewer.add(date); } Now the DI-Framework takes care of the Event loop syncing. Thanks to Brian de Alwis for pointing this out. [Update 2011-02-07] – End If you are interested in how you can use things like this in your Eclipse 3.x applications and you are going to be at EclipseCon you should come to my talk about “Singlesourcing for Eclipse 4.x and Eclipse 3.x” Interesting that in e4 one still has to manually sync with the SWT components. That’s something I never have to do in plain win32 (c++) coding. I had hoped finally there would be an easy way like Display.exec(Runnable) which would determine the threading issue under the hood. Its just a PITA to remember to sync all the time and write the same sync code over and over again. well to keep the scope as narrow as possible I thing there is no way around Display.exec() having said this we could may add an annotation which guarantees the call is made on the display-thread. The thing is: Why do I even *have* to sync. Its not an issue in plain Win32. I can update the “display” from any thread I want. There are only race conditions (because of the message loop) with old OLE kind of stuff. And if it is an issue of constant mistakes by programmers the tools should help him to make less mistakes. How often have I forgotten to sync to the display thread? Its just annoying and I have written my own little helper class. I’ve just updated the blog to show how to sync at least things coming in through the event system to the UI-Thread Cool stuff Tom, thanks… didn’t know about @UIEventTopic Just watched “Leveraging Eclipse 4 API to Build Components for the Future”. Would loved to have come to your EclipseCon “Singlesourcing for Eclipse 4.x and Eclipse 3.x”. Is that on the internet in some form (slides, webinar, video) Tom, is this solution meant to be used with the compatibility layer in 3.x applications? I have the following problem: If i create an event handler like the one in ReceiverView, i’m getting an InjectionException (“unable to process ReceiverView#eventReceived: no actual value was found …”) when the view is created the first time. So i marked the parameter with @Optional. But then the eventReceived method is called during the injection phase with null as parameter value, without any sender having created the event. My current solution is to mark the whole method as optional, not the parameter. Are there any better solutions? Marking the method with @Optional is the way to use it in e4, so it is also the way to use it in the with the e4-bridge. Reblogged this on FunThomas Blog (de) und kommentierte: Gerade habe ich angefangen mich in Eclipse e4 einzuarbeiten. Was soll ich schreiben wenn es andere schon viel besser beschrieben haben. Zunächst eine kleine Beispielanwendung erstellen nach dem Tutorial von Lars Vogel: Und dann die Communikation zwischen den einzelnen Parts implementieren nach dem Beitrag vom Tomsondev Blog. Wünsche allen viel Spaß beim Ausprobieren
http://tomsondev.bestsolution.at/2011/02/07/enhanced-rcp-how-views-can-communicate-the-e4-way/
CC-MAIN-2014-49
refinedweb
1,038
55.13
Julie Lerman Published May, 2011 Download the code for this article: Entity Framework Code First tuning up relationships in the fluent API. Code First conventions are very adept at recognizing common relationships between classes based on properties that point to child collections or to a single class. When your classes don’t use foreign keys, Code First can infer database foreign keys for you. But there are times when your classes don’t provide enough information for Code First to handle these relationships in the way you intended. I’ll begin with a simple pair of classes, Blog and Post, where Blog has a one-to-many relationship with Posts. Blog Blog { get; set; } } A common way to define one to many relationships in classes is to have a child collection in the one class and then a foreign key property along with a navigation property in the child class. In the above example, Blog has a Posts property which is an ICollection of Post types. Post has a foreign key, BlogID as well as a navigation property, Blog that points back to its parent Blog. This setup fits into Code First convention’s expectations and as a result, Code First will create the following database tables: Figure 1 Notice that Code First made the BlogId a database foreign key (there is a Primary Key / Foreign Key constraint defined between Posts.BlogId and Blogs.Id) and that is non-nullable. That is what Code First convention determined from the classes. What if you didn’t want to have a BlogId property in your Post class, but you did have the navigation property, Blog. Code first is able still to create the relationship because it knows that the Blog property points back to the Blog entity. So it will still create the database foreign key, Posts.Blog_Id as you can see in Figure 2, along with a constraint linking it to Blog.Id. Figure 2 But there is one important difference. Blog_Id is nullable. It will be possible to add Posts that are not bound to a Blog. This is how Code First convention interpreted the class but it is probably not your intention. You can use the fluent API to fix this. Fluent API configurations are applied as Code First is building the model from the classes. You can inject the configurations by overriding the DbContext class’ OnModelCreating method shown here. public class BlogContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //configure model with fluent API } The DbModelBuilder gives you a hook into the configurations. Here we can tell the model builder that we want to affect one of the entities, and you can use generics to specify which entity, Post. Once you have access to that, you can use the HasRequired method, which is particular to relationships, to specify that a navigation property is required — in this case the Blog property. modelBuilder.Entity<Post>().HasRequired(p => p.Blog); This will have two effect. First, the Blog_Id field in the database will become not null again. But also, Entity Framework will perform a validation on-demand or prior to saving changes back to the database, to ensure that this requirement has been met. When you do have a foreign key in the class, that property name may not always match the Code First convention. The convention is that the key is a combination of the name of the class it points to, e.g., Blog, and either _Id or Id. That’s why Code First was able to work with original property in the class, BlogId. But what if your property didn’t fit the convention? Perhaps you use “FK” + parent + “Id”? public int FKBlogId { get; set; } Code first will have no clue that FKBlogId is supposed to be the foreign key. It will create a standard column to represent that property and it will also create the Blog_Id foreign key that it determined was needed because of the Blog property. Figure 3 Additionally, when you are working with Blog and Post in your code, FKBlogId will never be recognized as the foreign key back to blog. If you have code in place to fix up bi-directional relationships, it won’t do its job using the FKBlogId property. You can use the fluent API to fix this, telling Code First your true intent, for FKBlogId to be the foreign key property in the relationship to Blog. And you can start with the configuration already in place. In this configuration you’ll define both ends of the relationship — the property in Blog that points to the many relationship (Posts) and the property in Post that points back to the parent (Blog). First you need to add the WithMany method, which allows you to indicate which property in Blog contains the Many relationship. modelBuilder.Entity<Post>().HasRequired(p => p.Blog) .WithMany(b => b.Posts) Then you can add to that the HasForeignKey method to indicate which property of Post is the foreign key pointing back to blog. In the end, here is the complete mapping: modelBuilder.Entity<Post>().HasRequired(p => p.Blog) .WithMany(b => b.Posts) .HasForeignKey(p => p.FKBlogId); Now Code First has the information it needs to create the correct database schema (or to map correctly to an existing database) and to provide the expected behavior in your application with respect to bi-directional relationships. Figure 4 In your classes you can easily describe a many to many relationship with properties that point to each other. For example, if you added a Tag class to the model to track Tags for Posts, you will need a many to many relationship between the two. Here is the new Tag class: public class Tag { public int TagId{ get; set; } public string Name { get; set; } public ICollection<Post> Posts { get; set; } } And here is the new property added to the Post class: public ICollection<Tag> Tags { get; set; } Code first expects the join table to be named by combining the names of the two classes and to contain the foreign key properties that are each a combination of the class name and the key property. In this case I am working with Post.Id and Tag.TagId. If you are letting Code First create the database, here is what that table will look like using Code First conventions: Figure 5 When you are letting Code First build the database, this may not be a problem. But if you are mapping to an existing database, these namings may not line up at all with your table. You can use the fluent API to describe the table name and both of the column names and you can explicitly name only one, two or all three. Here’s how to achieve this mapping. Let’s use the example where we’ll need to define all three names. The table should be PostJoinTag and the columns should be TagId and PostId. You’ll need to start with the Entity mapping method and you can pick either the Post or the Tag to begin with. Here’ll I’ll use Post. Next you need to specify the two ends of the relationship. And similar to how you specified the one-to-many relationship in the previous mapping, you can do that with HasMany and WithMany. Here I’m saying that the Post entity has a many relationship through its Tags property and from there, Tag has a relationship to its Many relationship with its Posts property. modelBuilder.Entity<Post>() .HasMany(p => p.Tags) .WithMany(t => t.Posts) .Map(mc => { mc.ToTable("PostJoinTag"); mc.MapLeftKey("PostId"); mc.MapRightKey("TagId"); }); Figure 6 You’ll need to take care when specifying which is MapLeftKey and which is MapRightKey. Left will be the key of the first class you pointed to, which is Post, and right is for the other side of the relationship. If you get these backwards, your data will be stored incorrectly and your users will be very confused. You’ve seen some of the possibilities for relationship mappings that you can describe with Code First’s fluent API for relationships. Here I’ve fixed up the convention’s misinterpretation of my intent with one to many relationships and many to many relationships. There are additional mappings that you can use, alone or in combination with each other. And while at first they may seem confusing and redundant, for example IsRequired and HasRequired or WithMany and HasMany. But now you’ve seen that the mappings have very specific jobs that there is a reason for them to be different. Be sure to check the Entity Framework 4.1 MSDN Documentation and the Entity Framework team blog ( ) to discover more of the relationship mappings you can achieve with the fluent API. –. ]]>
http://msdn.microsoft.com/en-us/data/hh134698
CC-MAIN-2014-23
refinedweb
1,474
60.24
Greetings All. As a heads up, I am finding that examples may fail to compare correctly (leading to all examples failing) due to errors setting child process limits. I plan to look into resolving this tomorrow. --Andrew Black Martin Sebor wrote: > Andrew Black wrote: >> Revised ChangeLog. > > Okay. I found a couple of typos in the patch that I missed in > my first review so I fixed them myself and committed the whole > thing: > > Martin > > Here are the typos in case you're wondering (gcc only issues > a warning for them but other compiler might give an error): > > exec.cpp: > > @@ -690,7 +690,7 @@ > } > } > } > -#endif /* _XOPEN_UNIX *// > +#endif /* _XOPEN_UNIX */ > > /** > Entry point to the child process (watchdog) subsystem. > @@ -770,7 +770,7 @@ > > #ifdef _XOPEN_UNIX > limit_process (); > -#endif /* _XOPEN_UNIX *// > +#endif /* _XOPEN_UNIX */ > > execv (argv [0], argv);
http://mail-archives.apache.org/mod_mbox/stdcxx-dev/200609.mbox/%3C45089106.802@roguewave.com%3E
CC-MAIN-2014-23
refinedweb
130
58.92
Back in the good old days, C# was .NET was Windows. Sure there were antique languages like VB.NET and ivory tower academia from F# but real developers used C# and the language was just fine as it was. Sure, some additions helped, generics were ok even if they did smell suspiciously like Java. But honestly, a lot of the newer "features" of C# are just syntactic sugar that don't really help anything. I mean, who really needs things like type inference or ternary operators? And that LINQ syntax?! Who can honestly claim that this var squaredValues = intCollection.Select(x => x * x).ToList(); is clearer and simpler than this? List<int> squaredValues = new List<int>(); foreach (int i in intCollection) { int squared = i * i; squaredValues.Add(squared); } But now, now it gets even worse! C# 8.0 has polluted the language with such unnecessary things as nullable reference types. Maybe I like spending hours hunting through code to track down why something is null when it shouldn't be. As if that wasn't bad enough, now we have new operators too! We have a fancy new "null-coalescing" operator where a simple if statement would suffice. List<int> mayBeNull = null; // Who on earth would do this? List<int> mustNotBeNull = mayBeNull ??= new List<int>(); // When they can do this? // What does it matter if someone forgets to do the if check // when it's their tenth time writing code like this today? List<int> mustNotBeNull = mayBeNull; if (mustNotBeNull == null) { mustNotBeNull = new List<int>(); } But worst of all now they've taken ideas from dangerously fringe languages like F#, with such strange concepts as Pattern Matching, even going so far as to be able to use them on tuples! public enum Hand { Rock, Paper, Scissors } public static string RockPaperScissors(Hand first, Hand second) => (first, second) switch { (Hand.Rock, Hand.Paper) => "rock is covered by paper. Paper wins.", (Hand.Rock, Hand.Scissors) => "rock breaks scissors. Rock wins.", (Hand.Paper, Hand.Rock) => "paper covers rock. Paper wins.", (Hand.Paper, Hand.Scissors) => "paper is cut by scissors. Scissors wins.", (Hand.Scissors, Hand.Rock) => "scissors is broken by rock. Rock wins.", (Hand.Scissors, Hand.Paper) => "scissors cuts paper. Scissors wins.", (_, _) => "tie" }; If something like Rock, Paper, Scissors can be expressed in a single method that will even give a compiler warning if every possible combination isn't covered in the switch statement, then how on earth is a developer supposed to be able to justify a large design or testing budget?! But it gets even worse, the upcoming C# 9.0 is adding more features inspired by F#! Honestly, who has even heard of a successful company using F# in production? But no, it had to take inspiration from this "language" (it doesn't even use semicolons). Adding such unnecessary new things as an init accessor that allows you to specify that a property can only be written to at object initialisation. public class Person { public string FirstName { get; set; } public string LastName { get; set; } } var simon = new Person { FirstName = "Simon", LastName = "Reynolds" }; // Why does it matter that this code is legal? // Surely we'd all just remember to not make this mistake? simon.FirstName = "Evan"; public class Person2 { public string FirstName { get; init; } public string LastName { get; init; } } var simon = new Person2 { FirstName = "Simon", LastName = "Reynolds" }; // Is having to learn a new accessor really worth avoiding mistakes like this? // Who cares that this would be a compiler error instead of a bug report? simon.FirstName = "Arlo"; What does it matter if a property is mutable and can be changed at any point? If it's not meant to be written to after creation then that's on us as developers to be professional enough to remember not to write to it! But still that's not enough, C# 9.0 goes further and introduces the idea of a class being an automatically immutable "record" class. Why on earth would anyone want an object that just represents data and is guaranteed not to be accidentally modified? Why would we need an object that is considered equal to another simply because all the properties of it have the same values? public data class Person // What is this "data" keyword?! { public string FirstName { get; init; } public string LastName { get; init; } } // This is the same but what are we really gaining from this brevity? public data class Person { string FirstName; string LastName; } // Or even more extreme brevity? public data class Person(string FirstName; string LastName); Does it really help to compress 5 lines down to one? How does that make things simpler? What if we want to change a record? So instead of modifying it we just have to create a new one even though most fields will have the same values? How can that be done without having to copy each field manually? var simon = new Person("Simon", "Reynolds"); var evan = simon with { FirstName = "Evan" }; var (firstName, lastName) = evan; // ("Evan", "Reynolds") Oh.....ok, I guess that's pretty convenient. And granted, we got automatic deconstruction back into separate fields for free as well but still....this can't be that useful in real life scenarios, right? It's not as if there's an entire application architecture based on recording the entire history of an object at every point in its history instead of just updating a single instance of it, right? Why would we ever need to audit our records and tell you why, how or when a change occurred? C# needs to drop all these new plans and return to its roots as a plain object-oriented language where anything can be null, state can be changed by anything and where dozens of if/else statements are used instead of single switches that cover all cases. If we carry on down this dangerous path how are we supposed to show our skills? Which will look more impressive, fixing a critical bug at 3AM on a Sunday morning or leaving work on time each day because we've been able to prevent the bug in the first place?
https://simonreynolds.ie/the-continued-theft-of-good-ideas-by-csharp/index.html
CC-MAIN-2022-33
refinedweb
1,015
64.2
As we have long learned the fact that multiple inheritance is not directly supported in Java, well that was only till Java 7. In Java 8, we can realize the concept of multiple inheritance through use of default methods without getting into diamond problem. Let’s see how? Table of Contents 1. What are default methods? 2. How multiple inheritance is achieved via default methods? 3. Possible conflicts and their resolutions 1. What are default methods? If you been in java programming since enough long time, you may realize that how painful can be adding a new method in an existing interface. You will need to implement that new method in java classes which implement that interface. It’s really difficult job. Well, java 8 brought default methods to help you in exactly same situation. Default methods enable you to add new functionality to the interfaces and ensure backward compatibility for existing classes which implement that interface. As their name implies, default methods in interfaces are methods which will be invoked by default – if not overridden in implementing classes. Let’s understand with an example. Moveable interface is some existing interface and wants to add a new method moveFast(). If it adds moveFast() method using old technique, then all classes implemeting Moveable will also be changed. So, let’s add moveFast() method as default method. public interface Moveable { default void moveFast() { System.out.println("I am moving fast, buddy !!"); } } If all classes implementing Moveable interface do not need change themselves (until some class specifically wants to override moveFast() method to add custom logic). All classes can directly call instance.moveFast() method. public class Animal implements Moveable { public static void main(String[] args) { Animal tiger = new Animal(); //Call default method using instance reference tiger.moveFast(); } } 2. How multiple inheritance is achieved via default methods? We know that in java (until jdk 7), inheritence in java was supported by extends keyword which is used to create a child class from a parent class. You cannot extend from two classes.. package com.howtodoinjava.examples; interface Moveable { default void moveFast(){ System.out.println("I am moving fast, buddy !!"); } } interface Crawlable { default void crawl(){ System.out.println("I am crawling !!"); } } public class Animal implements Moveable, Crawlable { public static void main(String[] args) { Animal self = new Animal(); self.moveFast(); self.crawl(); } } 3. Possible conflicts during mutiple inheritance In above example, we have two different interfaces and two different methods – so there is no conflict. What if both interfaces decide to define a new method with same name. Well they can define without problem. But which method will be invoked when Animal instance will call it’s name. That’s conflicting situation. package com.howtodoinjava.examples; interface Moveable { default void run(){ System.out.println("I am running, kid !!"); } } interface Crawlable { default void run(){ System.out.println("I am running, daddy !!"); } } public class Animal implements Moveable, Crawlable { public static void main(String[] args) { Animal self = new Animal(); //What will happen when below statement will execute //self.run(); } } So solve above conflict, caller class must decide which run() method it want to invoke and then call using interface’s reference like below. Moveable.super.run(); //Call Moveable's run() method //or Crawlable.super.run(); //Call Crawlable's run() method That’s all you should know about multiple inheritance feature Java 8, using default methods. Happy Learning !! Even this code (note how I took the calls out of the static method by adding a Test class) still fails to pass the IDE’s error checking and you get an error on the Animal class with something like: Duplicate default methods named run with the parameters () and () are inherited from the types Crawlable and Moveable Yeh, it’s problem that class.super.method()solve. Maybe I misunderstand, but class.super.method() does not solve the problem in my example above. I still get errors and I’m not in a static context… It’s a cool idea and I’d like to understand. To help me, please post some code that will not generate errors either in the IDE or at compile time? Thanks! Many thanks! I see my error now – not having a method named “run()” to match the interface. The error message generated by that mistake was not helpful. It referenced “duplicate default methods” when in fact, the problem was the lack of a run() method in my Animal class… Great example – thanks for posting! This sounded great until I tried to put it into an IDE. Unless I made a mistake, the following code will not compile but will instead produce the error: “Cannot use super in a static context” Please let me know if I got it wrong… You are right. My point is to use Moveable.super.run()style method calls to avoid conflict. You can definitely use it outside static methods. Or you can test by removing static keyword from main mathod. This article very important for java developer and java new concepts It goes even further… Peter Verhas showed that you could use the default methods to induce attributes: I tried to adopt his idea for observability, but it sees somehow “wrong” Sorry, I am making a comment without knowing complete context. Have you considered Closeable and Observable separate; rather than try to combine them?
https://howtodoinjava.com/oops/multiple-inheritance-in-java/
CC-MAIN-2020-05
refinedweb
881
57.47
BBC micro:bit Lighting The Way. Programming The following program demonstrates the basics of working with neopixels on the micro:bit. from microbit import * import neopixel # Initialise neopixels npix = neopixel.NeoPixel(pin13, 12) # Define some colours red = (255,0,0) green = (0,255,0) blue = (0,0,255) # Make pixel 0 red npix[0] = red # Make pixel 6 green npix[6] = green # Make last pixel blue npix[-1] = blue # Cause the colour changes to be shown npix.show() sleep(5000) # Clear the neopixels npix.clear() The line that initialises the strip of pixels states the pin and the number of neopixels in the chain. For the Bit:Bot, this is pin 13 and 12 neopixels. Once this has been done, the variable we used becomes a list of tuples that can be accessed in the normal way. When we define colours, we need to remember to call the show() method in order to see them on the pixels. We can also clear all of the pixels with a single statement. If you want to turn off a single pixel, rather than all of them, set its colour to (0,0,0). Helper Functions Lighting Groups Of Pixels The functions in this first set are pretty basic. I use these as indicators when trying to get the robot to respond to its sensors. from microbit import * import neopixel # Initialise neopixels npix = neopixel.NeoPixel(pin13, 12) # Define some colours red = (255,0,0) green = (0,255,0) blue = (0,0,255) nocol = (0,0,0) # light all neopixels with given colour def LightAll(col): for pix in range(0, len(npix)): npix[pix] = col npix.show() return # light neopixels on the left fin def LightLeft(col): for pix in range(0, 6): npix[pix] = col npix.show() return # light neopixels on the right fin def LightRight(col): for pix in range(6, 12): npix[pix] = col npix.show() return while True: # All red LightAll(red) sleep(2000) # Clear all npix.clear() sleep(1000) # Light left pixels green LightLeft(green) # Light right pixels blue LightRight(blue) sleep(2000) # Clear left LightLeft(nocol) sleep(1000) # Clear right LightRight(nocol) sleep(1000) Colour Wipe A colour wipe is when you light each pixel one at a time with a colour. A small delay is used between each lighting up neopixel so that the colour seems to be wiped across the chain. There are 3 functions to do this. The first wipes the colour according to the numerical order of the neopixels. The other two wipe the colour from the back to the front of the robot and vice versa. from microbit import * import neopixel # Initialise neopixels npix = neopixel.NeoPixel(pin13, 12) # Define some colours red = (255,0,0) green = (0,255,0) blue = (0,0,255) nocol = (0,0,0) # Colour wipe functions def Wipe(col, delay): for pix in range(0, len(npix)): npix[pix] = col npix.show() sleep(delay) return def WipeForward(col, delay): for pix in range(0, 6): npix[pix] = col npix[pix+6] = col npix.show() sleep(delay) return def WipeBackward(col, delay): for pix in range(11, 5,-1): npix[pix] = col npix[pix-6] = col npix.show() sleep(delay) return while True: Wipe(red, 100) sleep(1000) Wipe(green, 100) sleep(1000) Wipe(blue, 100) sleep(1000) WipeForward(red, 100) sleep(1000) WipeForward(green, 100) sleep(1000) WipeForward(blue, 100) sleep(1000) WipeBackward(red, 100) sleep(1000) WipeBackward(green, 100) sleep(1000) WipeBackward(blue, 100) sleep(1000) Rainbows Some functions to use colours from a colour wheel distributed across the neopixels. from microbit import * import math import neopixel # Initialise neopixels npix = neopixel.NeoPixel(pin13, 12) def LightAll(col): for pix in range(0, len(npix)): npix[pix] = col npix.show() def hsv_to_rgb(h, s, v): if s == 0.0: return (v, v, v) i = int(h*6.0) # XXX assume int() truncates! f = (h*6.0) - i p = v*(1.0 - s) q = v*(1.0 - s*f) t = v*(1.0 - s*(1.0-f)) i = i%6 if i == 0: return (v, t, p) if i == 1: return (q, v, p) if i == 2: return (p, v, t) if i == 3: return (p, q, v) if i == 4: return (t, p, v) if i == 5: return (v, p, q) def MakeColour(h): hsv = hsv_to_rgb(h,1,0.5) r,g,b = hsv return (math.floor(r*255),math.floor(g*255),math.floor(b*255)) def Rainbow(delay): for pix in range(0, len(npix)): npix[pix] = MakeColour(pix/(len(npix)-1)) npix.show() sleep(delay) def RainbowCycle(delay): l = len(npix) colours = [MakeColour(i/(l-1)) for i in range(0, l)] for i in range(0, len(npix)): x = [colours[(i + j) % l] for j in range(0,l)] for pix in range(0,l): npix[pix] = x[pix] npix.show() sleep(delay) while True: LightAll((128,0,0)) sleep(1000) Rainbow(1000) sleep(1000) LightAll((128,0,0)) sleep(1000) Rainbow(50) for i in range(0,20): RainbowCycle(150) LightAll((128,0,0)) sleep(1000) for i in range(0,1000): RainbowCycle(20) sleep(1000) Challenges There's a fair bit of code on this page and it only scratches the surface of the lovely and varied effects you can make with Neopixels. It is well worth experimenting and exploring this at length. - An obvious starting point is in synchronising lights and movement. Using the functions on this page,. - You can fade in and out of colours by using a loop to change the amount of red, green or blue in small steps. Work out how to write a function that fades from no colour to full brightness red. Work out how to fade back to nothing again. Then develop a function that fades from no colour to any colour you choose. This is harder since you have to go up/down in different amounts. Finally make a function that fades from one colour to another. Now you have a robot car that can perform some basic mood lamp functions. - Set all of the pixels to a single colour, not one that gives full brightness on any channel. Let's say you start with a light red. Now make one pixel at a time in the strip show full brightness red. Muck around with the intervals you use so that it looks like the colour is running around the strip of lights. - Work out how to make a rainbow pattern across all of the lights, starting at one end of the colour spectrum and ending at the other. It's quite tricky to work out a general rule for doing this. You might find it easier to work out the 12 colours you need first and store them in a list of tuples. - Similar to the last challenge. Make a single pixel twinkle. Quickly brighten one pixel in a brighter version of the same colour used on the other pixels. Work out how to vary which pixel you twinkle and create a reusable function. -. - When you have written a decent number of functions and code snippets for the neopixels, it's worth collating them all into a single example program or into a reference you make for yourself. As you explore more of the functionality of the Bit:Bot, you will be able to pick and choose from your list more easily when writing new programs.
http://multiwingspan.co.uk/micro.php?page=botneo
CC-MAIN-2017-22
refinedweb
1,234
80.41
>>!" Back to BASIC (Score:3, Funny) 10 GOTO 20 20 GOTO 10 Re:Back to BASIC (Score:5, Informative) Re:Back to BASIC (Score:5, Funny) Lisp never 'comes back'. It merely recurses. Re:Back to BASIC (Score:4, Insightful) Lisp is easy to get good programs from. You just have to stop thinking in non-Lisp ways. What confuses people is the functional orientation, but if you don't understand functional style of programming then a lot of modern stuff will pass you by. Procedural stuff is very easy in lisp too. Re: (Score:3) Lisp is easy to get good programs from. Then name some "good programs" written in Lisp. I have worked with thousands of programs written in C. Plenty in C++, Java, Perl, Python, and even a few in Ruby. But other than Emacs scripts, I have never come across Lisp in a non-academic program., Insightful) But there's a famously quoted statement by Guy Steele, who wrote some of the Lisp language specs and Java language specs. "we were not out to win over the Lisp programmers; we were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp." ( [mit.edu] ) Going from C to C++ is easy, I did that. Going from C++ to Java is easy. I did that too. Going from Java to Lisp is damn difficult, at least for me. But the fact that teaching mainstream C, C++, and Java developers Lisp is difficult merely makes it unlikely Lisp will be popular. It does not prove Lisp is a poor language.: (Score:3, Insightful) Re: (Score:3) you think C++ is better than LISP? Seriously? It's absurd to talk about which is better except with respect to a certain type of application.). Re:Back to BASIC (Score:4, Insightful)). It's the best environment for Forth, and conversely, Forth is the best language for than environment. Re: (Score:3) It works fine if you're judicious about what C++ features to use, and when and where to use them. As much of a pig as C++ is, one thing Stroustrup got right was making it a true multi-paradigm language, and he stuck to the principle of not dragging in any baggage or overhead that you don't explicitly ask for.:Back to BASIC (Score:5, Insightful) it gives me somewhat of a sign of relief to see C, C++ and Java/C# be stable in the face of this recurring tide of fad languages Sheesh, kids today. I remember when C++, Java and C# were the fad languages. I even remember when C outside of the Unix world was a "fad" replacing Fortran, Basic and Pascal. The "classic" languages you grew up with are not the end of programming language evolution. OTOH I admit that the so-called Cambrian explosion of languages really needs to be followed by a mass extinction. Perl, Python, Ruby, Lua, etc., etc., etc. You could spend the rest of eternity debating their pros and cons, but do we really need all of them? It's great if you want to spend the rest of your life learning yet another genius's "best of" mix of existing language ideas, but it sucks if you just want to get work done. Then there's Clojure, because what the Lisp world really needs is yet another dialect, and F# because, uh, well OCaml has been around a while and we really want yet another variant, and ... Re:Back to BASIC (Score:5, Interesting) Re: (Score:3) So pick a language you're good at and get work done. The existence of other languages doesn't prevent that. The one true language is never going to happen. Re: (Score:3) Re: (Score:2) Your fork bomb fizzles due to running out of stack. Try this: main() { while(1) fork(); } } Re: (Score:3) Your fork bomb fizzles due to running out of stack. Any C compiler worth its salt will recognize the tail-call recursion and rewrite/optimize that code into a loop... so the bomb will go off after all as long as you compile with -O3. ;) Re: (Score:3) Things really started going downhill when BASIC came out. BASIC came out in 1964. Re: Back to BASIC (Score:5, Funny) It's not the programmers making the decisions (Score:5, Insightful) Re:It's not the programmers making the decisions (Score:5, Insightful) Parent post speaks truth (Score:5, Interesting) Actually, from the examples cited, it seems to me to be painfully obvious why in those cases information was not shared. For quite a long period of time, IBM and MS were stiff competitors (remember OS/2 warp?). I doubt MS would inform IBM what they were working on, much less seek help. In fact, it seems to be the exception rather than the rule for software companies to share code with each other. Selling code, after all, is usually how they make money. Im fairly confident that Apple would sue any company that copies its software written for the Mac. Let us also not forget how much problems Oracle caused for Google when they sued over the Java API in Android [wikipedia.org]. Yes, it is efficient to reuse old tried and tested code, but it also opens you up to a lawsuit. So it is not so much reinventing the wheel as trying to find a different way of doing things so you wont get sued. For that, you have current IP laws to thank. The problem here is with equating writing software to producing works of art. People are willing to go out of their way to learn and improve themselves to paint better or make beautiful music because it enables them to express themselves. It's emotionally satisfying. OTOH most software is programmed to achieve a certain utility and the programmer is faced with constraints e.g. having to use certain libraries etc. He is rarely able to express himself, and his work is subject to the whims of his bosses. For most everyday programmers, I think there is no real motivation to 'learn from the great masters'. An exception might be the traditional hacking/cracking community where the members program for the sheer joy/devilry of it. I understand there is a fair amount of sharing of code/information/knowledge/learning from the great masters within their community. Re: (Score:3, Insightful) It's managers and executives who make the decisions, and to them whether it's a browser or mobile app or SaaS or whatever the latest trend is, who cares if you're reinventing the wheel as long as profits are up. That hasn't changed either. Just the specific subject of the idiocy has changed. Idiotic managers are timeless. Lady Ada probably had the same thing to say about Charles Babbage. Cheers, Dave. Another interpretation (Score:5, Interesting) I've always felt like that quotation had another interpretation, one that's much more favorable to the MPs: If you're an MP, you've probably had to deal with a lot of people asking for money to fund what is essentially snake oil. If you don't understand the underlying 'cutting edge' technology (both plausible and acceptable), one simple test is to ask a question that you KNOW if the answer anything other than "No" that the person is bullshitting, and you can safely ignore them... and as reported the question is phrased in such a way that it would sorely tempt any huckster to oversell their device. I think Babbage's lack of comprehension was due to his inability to understand the idea that the MP was questioning HIM, rather than the device.. Re: (Score:3) Ah, so that's why progress was possible back then and near absent today? Re:It's not the programmers making the decisions (Score:5, Interesting) Re:It's not the programmers making the decisions (Score:5, Insightful) Re: (Score:3) You're missing the point. Developers may pick the language, but if you've only hired a tenth as many programmers for language A than as for language B (because those who use language A are ten times more productive), then when you come to start a new project you'll have ten times as many advocates for language B as you do for language A. Which language will your development team pick? Re:It's not the programmers making the decisions (Score:5, Insightful) That's such a cop out and it's not true. Most the managers making these decisions are technical managers who come from development backgrounds themselves. There is a problem at a more fundamental level, even outside of determining what buzzwords to use for a product and it's prominent even in some of the higher echelons of web society. The most obvious I'm going to point out is that of HTML5 - it's a braindead spec full of utterly amateur mistakes that could've been avoided if only Ian Hickson had spent 5 seconds understanding why existing things were the way they were and why that mattered. An obvious example is that of HTML5's semantic tags, using a study to determine a static set of tags that would be used to define semantic capabilities in a spec that was out of date before the ink had even dried was just plain stupid. The complaint that we needed more readable markup rather than div soup to make writing HTML was naive, firstly because amateurs just don't write HTML anymore, they all publish via Facebook, Wordpress and so forth, and secondly because there's a good reason markup had descended into div soup - because genericness is necessary for future-proofing. Divs don't care if they're ID is menu, or their class is comment, they're content neutral, they don't give a fuck what they are, but they'll be whatever you want them to be which means they're always fit for the future. In contrast HTML5 tried to replace divs with tags such as aside, header, footer and so forth which would be great except when you have a finite number of elements you end up with people arguing about what to do when an element doesn't fit. Do you just go back to using divs for that bit anyway or do you fudge one of the new tags in because it's kinda-loosely related which means you bastardise the semantics in the first place because we now don't really know what each semantic tag is referring to because it's been fudged in where it doesn't make a lot of sense? The real solution was to provide a semantic definition language, the ability to apply semantics to classes and IDs externally. Does that concept sound familiar? It should because we had the exact same problem with applying designs to HTML in the past and created CSS. We allowed design to be separate from markup with external stylesheets because this had many benefits, a few obvious ones: 1) Designers could focus on CSS without getting in the way of those dealing with markup making development easier 2) We could provide external stylesheets for no longer maintained sites and have the browser apply them meaning there is a method to retrofit unmaintained sites with new features 3) Our markup is just markup, it just defines document structure, it does one thing and one thing well without being a complete mess of other concepts. Consider that these could've been benefits for building a semantic web if HTML5 had been done properly too. The fact that Ian Hickson failed to recognise this with HTML5 highlights what the article is talking about exactly. He's completely and utterly failed to learn the lessons before him as to why inline styling was bad but on a more fundamental level demonstrates a failure to understand the importance of the concept of separation of concerns and the immense benefits that provides that was already learnt the hard way by those who came before him. His solution? Oh just make HTML5 a "living spec" - what? Specs are meant to be static for a reason, so that you can actually become compliant with them and remain compliant with them. Spec compliance once you've achieved it shouldn't ever be a moving target. That's when you know you need to release a new spec. It's a worrying trend because it's not just him, I see it amongst the Javascript community as they grow in their ambition to make ever bigger software but insist that Javascript is all they need to do it. The horrendously ugly fudges they implement to try and fudge faux-namespaces into the language in a desperate attempt to alleviate the fact the Javascript was just neve The thing about repeating the past (Score:2) I saw the Lady Gaga quip and Scott's fondness for effective ancient map-reducey techniques on unusual hardware platforms. It reminded me about things like discovering America. Did the Vikings discover it years before any other Europeans? Certainly. Did the Chinese discover it as well? There's some scholarly thought that maybe they did. But you know whose discovery actually effected change in the world? Lame old Christopher Columbus. Perhaps there's a lesson to be learned here from people who want to actuall Re: (Score:2) Eh? starting 15,000 years ago various waves of people came here from asia and huge and important civilizations have risen and fallen in the Americas since then. Some of those people are still around and their influence on art, food, medicine continues into our culture. One group of those asians was absolutely crucial to the United States winning its independence and also had influence on our Constitution. Talk about effecting change in the world; and they're still around by the way. Re:The thing about repeating the past (Score:4, Insightful) Lady Gaga is mentioned because she is both a classically trained artist and sui-generis of successful PopTart art through self-exploitation. Yes, the reference is recursive - as this sort of folk are prone to be. They can also be rude, if you bother to click through, as they give not one shit about propriety - they respect skill and art and nothing else. When I plussed this one on the Firehose I knew most of us weren't going to "get it" and that's OK. Once in a while we need an article that's for the outliers on the curve to maintain the site's "geek cred". This is one of those. Don't let it bother you. Most people aren't going to understand it. Actually, if you can begin to grasp why it's important to understand this you're at least three sigmas from the mean. Since you don't understand why it's important, I wouldn't click through to the article and attempt to participate in the discussion with these giants of technology. It would be bad for your self-esteem. For the audience though, these are the folk that made this stuff and if you appreciate the gifts of the IT art here is where you can duck in and say "thanks." Re:The thing about repeating the past (Score:4, Funny) Re:The thing about repeating the past (Score:4, Insightful) A (very) recent OSCON talk (Score:5, Informative) Re: (Score:2) We don't shun those who should be shunned. (Score:5, Insightful) It's pretty damn obvious why this is: as an industry, we no longer shun those who should definitely be shunned. Just look at all of the damn fedora-wearing Ruby on Rails hipster freaks we deal with these days. Whoa, you're 19, you dropped out of college, but you can throw together some HTML and some shitty Ruby and now you consider yourself an "engineer". That's bullshit, son. That's utter bullshit. These kids don't have a clue what they're doing. In the 1970s and 1980s, when a lot of us got started in industry, a fool like that would've been filtered out long before he could even get a face-to-face interview with anyone at any software company. While there were indeed a lot of weird fuckers in industry back then, especially here in SV, they at least had some skill to offset their oddness. The Ruby youth of today have none of that. They're abnormal, yet they're also without any ability to do software development correctly. Yeah, these Ruby youngsters should get the hell off all of our lawns. There's not even good money in fixing up the crap they've produced. They fuck up so badly and produce so much utter shit that the companies that hired them go under rather than trying to even fix it! The moral of the story is to deal with skilled veteran software developers, or at least deal with college graduates who at least have some knowledge and potential to do things properly. And the Ruby on Rails idiots? Let's shun them as hard as we can. They have no place in our industry. Re: (Score:3) Re: (Score:3) I think you were trolling, but there's a point under there. In the 70s you had to have a clue to get anything done. As more infrastructure and support system has been built, in the interest of not having to reinvent the wheel every project, you *can* have people produce things - or appear to produce things - while remaining clueless. Flash and sizzle have been replacing the steak. Now it's html5 and sizzle. indeed, too many bad code monkeys, few engineers (Score:5, Insightful) It's not entirely young vs old, either. I'm in my 30s. I work with people in their 50s who make GOOD money as programmers, but can't describe how the systems they are responsible for actually work. How do we fix it? If you want to be good, studying the old work of the masters like Knuth is helpful, of course. Most helpful, I think, is to become familiar with languages at different levels. Get a little bit familiar with C. Not C# or C++, but C. It will make you a better programmer in any language. Also get familiar with high level. You truly appreciate object oriented code when you do GUI programming in a good Microsoft language. Then, take a peek at Perl's objects to see how the high level objects are implemented with simple low level tricks. Perl is perfect for understanding what an object really is, under the covers. Maybe play with microcontrollers for a few hours. At that point, you'll have the breadth of knowledge that you could implement high level entities like objects in low level C. You'll have UNDERSTANDING, not just rote repetition. * none of this is intended to imply that I'm any kind of expert. Hundreds, possibly thousands of people are better programmers than I. On the other hand, tens of thousands could learn something from the approach I described. I'm not seeing your point (Score:3) Are you suggesting that it's not true, that C won't show you things that you don't learn from Ruby? Also the reverse - GUI programming in Re: (Score:3) Sorry, my point was not as clear as I had hoped, since I never actually made it directly... Are you suggesting that it's not true, that C won't show you things that you don't learn from Ruby? Not as such. I'm suggesting that some people are simply impervious to learning. Back then as now, people managed to struggle through careers in programming without seeming to gain knowledge, skill or apparently any understanding deep enough to write programs. For those people, they learned nothing really from C then and Re: (Score:3) To be honest, I sort of softened on ruby on rails after being forced to endure a project on it, and must to my teeth-grinding resentment, actually found it a decent and productive environment (Although I'd say Django more so because of its relative lack of magic, and hey who doesn't enjoy screwing around with python). Now don't get me started on javascript on the server and NoSQL systems. Somewhere between "lets call ourselves amazing because we got a god damn web browser script environment to implement a pa Re: (Score:2) Re: (Score:3) I Googled "A poor worker blames his tools". All I got was links to Craftsman and Harbor Freight. I bet you're blaming Google for this.... :-) Re:We don't shun those who should be shunned. (Score:4, Insightful) Re: (Score:3) Neither one of your meanings matches how I've always heard it. A poor worker will try to place the blame on someone else. "It couldn't have been my fault, they must have been bad tools." So the tools were the constant rather than the variable. Re: (Score:2, Insightful) I can tell that you're young simply because you used C++ in a debate where someone slightly older would have used C. Either that, or you're a Windows programmer. C utterly dominated open source (and thus the Slashdot community) until about 5 years ago. That's when the overwhelming number of university switched to C++. Of course, before that it was Java, so you can see the trend. Unless you're a Windows programmer, I'd stick with C, which is infinitely simpler, and provides you freedom to maintain competency i Re: (Score:3) The un-useful parts - overloading and inheritance for example, detract from that. C has overloading. The + operator is overloaded so that it operates differently on pointers, ints, chars, floats, doubles and various combinations of the two. Could you imagine actually using a language without overloading? I have used them and the result is not particularly pleasant. Likewise for C++ which has *user defined* overloading. The idea of writing complex maths in C is horrible compared to C++. And inheritance? How is t Re: (Score:3) "C has no un-useful parts" setjmp / longjmp ?!? Very very very useful when writing error handlers for functions way on down the stack. Much more crufty than C++ exceptions, but a helluva lot more helpful when debugging signal-based coded. Re: (Score:3) And Ruby is just a hobbled variant of Smalltalk anyway. Re:We don't shun those who should be shunned. (Score:5, Interesting) Re:We don't shun those who should be shunned. (Score:5, Interesting) Re: (Score:2) We just had an earthquake here, and one of the most heavily damaged buildings was Re: We don't shun those who should be shunned. (Score:2, Insightful) I'm offended that ruby keeps getting thrown in with this Node/NoSQL stuff. Node has a couple of real use cases, but outside of that its a waste of time. NoSQL has a couple of real use cases, but outside of them it's not something you build around. Ruby on the other hand is a really interesting language that has the benefit of being so flexible that its made for creating DSLs. Puppet, Chef, Capistrano and Rails just off the top of my head. Do some libraries have memory leak issues? Yes. Does its thread handli Re: We don't shun those who should be shunned. (Score:4, Interesting) Package management and fit for purpose tool chains don't exist in other languages? Is that a joke? Have you seen the Ruby gem ecosystem? Have you seen the Java ecosystem? You can do everything that you described in Ruby or Python without blinking and you won't incur the technical debt that Node's global insanity creates. Node came a long and people went "OMG! Non-blocking I/O!" and everybody else with a pulse looked at it and said...yea, that's what background workers are for but background workers encapsulate the logic instead of letting it all float around in one process. Eventually, node code grows to insanity. Mongo is awesome...for write heavy applications. In most applications that means that one table could probably be better served with Mongo. For logging or cloud based data aggregators it's EXCELLENT. It's a fantastic session store too. Also a great query cache. That doesn't make it the optimal tool for your entire system where you might actually care about normalization, data compression, data integrity or the amount of hard drive space required to store all the data bloat that comes with it. I can built a fully functional ecommerce system with an API, payment gateways, account system and analytics in 2 weeks (and most of that is just setting up the payment gateway and merchant account) with Ruby, Python, Groovy or Scala. With 1 person. Having it do $100k / month in sales is a product of what it's offering, how effectively it's marketed, how the supply chain side of the business can scale with demand and has absolutely zero to do with Node and/or Mongo. Are you actually serious with such an example? Re: (Score:3) That's why I don't work in areas where that can be done. In embedded systems you still need to know the basics and can't just rely on the web technology invented last week. Even in mobile devices they need bare metal C coders (I just got a recruiter letter for it too). Gotta know hardware, operating systems, some assembler, debug from core files, good algorithms, communication with other processors, etc. Try getting a $10/hour a guy doing that, or someone who thinks a certificate is proof of qualificati Paging Linus (Score:3, Insightful) [wordpress.com]. Re:Paging Linus (Score:4, Informative) Hive: distributed and free (Score:3, Interesting) That's genius: comparing a "$100k/CPU" non-distributed database to a free distributed database. Also no mention that, yes, everyone hates Hive, and that's why there are a dozen replacements coming out this year promising 100x speedup, also all free. And on programming languages, Locklin is condescending speaking from his high and mighty functional programming languages mountain, and makes no mention of the detour the industry had to first take into object-oriented programming to handle and organize the exploding size in software programs before combined functional/object languages could make a resurgence. He also neglects to make any mention of Python, which has been popular and mainstream since the late 90's. Re:Hive: distributed and free (Score:4, Interesting) large teams (Score:3) what the lack of QA and to much auto testing? (Score:2) With to much auto testing can just code to pass the test and even if some was looking at they would mark fail but it still passes what the auto system thinks is good. Optimal team size (Score:3) For any given software project there is an optimal team size. If the project is small enough, you can keep the team size down to what works with an agile development methodology. If the project is bigger than that, things get ugly. I started my career in a company that considered projects of 50 to 100 man-years to be small to medium sized. Big projects involved over a thousand man-years of effort and the projects were still completed in a few years calendar time. You can do the math as to what that mea 'Web Based' Coding is not the same... (Score:5, Funny) We marvel that the runtime environment of the web browser can do things that we had working 25 years ago on the Mac I don't remember that code running cross platform on varying architectures. The web as an platform for distribution should not be compared to an actual OS...that doesn't even make sense. Re:'Web Based' Coding is not the same... (Score:5, Interesting) I don't remember that code running cross platform on varying architectures. Yes. No code runs cross platform on varying architectures - INCLUDING the stuff that supposedly does, like Java and Javascript and all of the web distributed stuff. All of it DEPENDS on an interpretation level that, at some point, has to connect to the native environment. Which is what BASIC was all about. And FORTRAN. Expressing the algorithm in a slightly more abstract form that could be compiled to the native environment, and then in the case of BASIC turned into interpreted code (Oh, you thought Java invented the virtual machine?) In a lot of ways it is closed source vs open (Score:3) Competition for money might get people to strive to make better pieces of art. But on the flip side, this same competition will sue your pants off for any reason they can find so you don't compete with them either. An on an unrelated note, I had an idea for a zombie video game like Ground Hog day today. When you die, it starts out as the beginning of a zombie pandemic. As you die and play through it over and over, you get secrets to where weapons and supplies are. You find tricks you can use to survive and save people. Eventually you find out who caused the zombie pandemic. You can then kill him before he goes through with it. I'm not sure an ending where you serve in prison is a good ending though. I didn't think it the whole way through, but it sounded like a good premise for a zombie game. Re: (Score:3) That doesn't seem true for the most part. All open source does with regard to code reuse is that it makes it painfully obvious how much redundancy there is. The spat between the different Linux display managers is one recent example, but I'm sure you can think of many others. As for why this is In Browser (Score:5, Insightful). Re: (Score:2):In Browser (Score:5, Funny). Dude, just ignore this guy. Of all people who have the right to indulge in a good, old-fashioned 'get off my lawn' rant, Dave Winer ranks last. This is the man who, for our sins, gave us XMLRPC and SOAP, paving the way for the re-invention of... well, everything, in a web browser. Port 80 died for this man's sins.... The third link (Score:2) It would be great if he'd actually given examples of why APL is a good language. I would be interested in that. Instead he says mmap is really interesting, which actually doesn't have anything to do with programming language. He says that old programmers have left a lot of examples of good source code. It would be great if he'd actually linked to their code....... What past was he from? (Score:3, Funny) He says system performance is the same as it was way back then. He thinks that stuff just happened immediately on those systems because they were running very efficient code. So what. Here's a simple test. Go get one of those computers and set it next to yours. Turn them both on. Mine would be at a desktop before the old one even thinks about getting down to actually running the operating system. Or start a program. On a current system it loads now. As in, right now. Back then it was a waiting game. Everything was a waiting game. He must have simply forgotten or repressed those memories. Re:What past was he from? (Score:4, Insightful) Also those old programs did a lot less than many of our new programs. People often forget that when complaining about performance. That's not to say, of course, that modern programs couldn't be written more efficiently. Because of Moore's Law and other considerations, we have moved away from spending a lot of time on performance and efficiency. Re: (Score:3) Of course modern computers have faster CPUs and everything else, but I'd really like to know where along the line a 30 second boot time became acceptable...... Re:What past was he from? (Score:5, Informative) Re: (Score:3, Informative) However, compare Word from 1990 to Word from today. The 1990 one will start nearly instantly, by incredibly responsive, and have all the features most people use anyway. Re:What past was he from? Mine. (Score:3) I had an Atari ST at college. It booted (to a graphical, no less) desktop pretty much instantly, say a few seconds if you had a slew of SCSI peripherals (especially a CDROM drive), but otherwise it was about half a second. It was ready to go, too. None of this crap of *showing* the desktop and then spinning the busy cursor for another 30 secs... Simon. To much theory / lack of apprenticeships in CS? (Score:2) When people don't learn from people who have made mistakes or even had some real work place experience (not years of academic experience) it easy to end makeing mistakes that in theory seem like good ideas. Also similar to some of the certs type stuff there the book says this but in the real work place that does not work. Net, CPU and GPU bound (Score:5, Insightful) They faced the limits of the data on a floppy and cd. They had to think of updates over dial up, isdn, adsl. Their art had to look amazing and be responsive on first gen cpu/gpu's. They had to work around the quality and quantity of consumer RAM. They where stuck with early sound output. You got a generation of GUI's that worked, file systems that looked after your data, over time better graphics and sound. You got a generation of programming options that let you shape your 3d car on screen rather than write your own gui and then have to think about the basics of 3d art for every project. They also got the internet working at home. Re:Net, CPU and GPU bound (Score:5, Insightful) Some people seem to think this article is about going back to the past. They miss the entire point. We're not saying that older programs were better, or that older computers were better, or that we should roll back the clock. We're saying that they had to pay more attention to what they were doing, they had to learn more and be broad based, they had to learn on their own, and so forth. When they had good ideas they were shared, they were not continually being reinvented and presented as something new. They didn't rely on certification programs. Some things are missing (Score:5, Interesting) Remember the strategy gaming past... (Score:2) ... or be doomed to repeat it. And they have been for 20 years, every year. Strategy game development in particular seriously needs a persistent collective consciousness. Re: (Score:2) Well, maybe I should have been more specific and said 4X strategy game development.... A symptom of popular culture in the '60s (Score:5, Insightful) All Mozart's Works are Open Source (Score:5, Insightful) You can learn a lot from Mozart because you can read all the notes he published. You can listen to many interpretations of his works by different people. We don't have the chance to read through 25-year-old Mac symphonies^W programs. We aren't even writing for the same instruments. Back to chariots and horses (Score:2, Insightful) Chariots were masterpieces of art. They were often made of precious metals and had elegant design work. They were environmentally friendly, using no fossil fuels whatsoever. They didn't cause noise pollution, or kill dozens of people when they crashed. Aircraft makers should learn from the past. They have totally functional designs, no semblance of artistry anywhere. Accommodations are cramped, passengers treated like cattle. We should go back to the good old days, things were so much better back then. No The past was nice but today is not then (Score:5, Insightful) Library Code Archives (Score:2) Libraries should be archiving (and date-stamping) code. When copyright expires, that code can form public domain building blocks for a lot of cool stuff. The kids of the future won't have to reinvent the wheel, they'll be able to improve it. Software patents suck. Au Contraire! (Score:4, Interesting) For instance: As a cyberneticist I'm fond of programs that output themselves, it's the key component of a self hosting compiler... Such systems have a fundamental self describing mechanism much like DNA, and all other "life". While we programmers continue to add layers of indirection and obfuscation ( homeomorphic encryption ) and segmented computing (client / server), some of us are exploring the essential nature of creation that creates the similarities between such systems -- While you gloat over some clever system architecture some of us are discovering the universal truths of design itself. To those that may think Computer Science is a field that must be studied or be repeated, I would argue that there is no division in any field and that you haven't figured two key things: 0. Such iteration is part of the cybernetic system of self improvement inherent in all living things -- to cease is death, extinction. 1. Nothing in Computer Science will truly be "solved" until a self improving self hosting computing environment is created... So, while you look back and see the pains of Microsoft trying to implement POSIX poorly, I've studied the very nature of what POSIX tried and only partially succeeded to describe. While you chuckle at the misfortunes of programmers on the bleeding edge who are reinventing every wheel in each new language, I look deeper and understand why they must do so. While you look to the "great minds" of the past, I look to them as largely ignorant figures of self import who thought they were truly masters of something, but they ultimately did not grasp what they claimed to understand at a fundamental level -- The way a Quantum Physicist might acknowledge pioneers in early Atomic thinking... Important, but not even remotely aware of what they were truly doing. How foolishly arrogant you puny minded apes are... Upgrades and backward compatibility (Score:3). You hate Gates but... (Score:3) You don't like Gates but wish programmers looked towards more "Great Masters?" Bill Gates was a Great Master Programmer. Common rediscovered problems. (Score:4, Insightful) There are a few problems which keep being rediscovered. In many cases, the "new" solution is worse than the original one. Re: (Score:3) If the people in the middle ages had only realized it was the rats, and the fleas they brought with them, they wouldn't have suffered from plague for so long. Hindsight is 20/20. Re: (Score:3) LocalTalk file sharing, AIFF files, 8-bit audio support.
https://developers.slashdot.org/story/13/07/30/2348212/remember-the-computer-science-past-or-be-condemned-to-repeat-it?sbsrc=md
CC-MAIN-2017-43
refinedweb
6,539
71.04
Subject: Re: [OMPI devel] [OMPI svn-full] svn:open-mpi r30860 - in trunk/ompi/mca: btl/usnic rte From: Ralph Castain (rhc_at_[hidden]) Date: 2014-02-27 16:52:00 Just to clarify my point, since the 1.7 branch was mentioned in this thread. I didn't worry about USNIC calling abort because, as Jeff pointed out, we do so in other places. However, I do believe that we shouldn't be doing so (including in orte) because it isn't the role of a library to abort the process. We should report errors upward to the app and let it decide how to respond. That said, I know we initially did it because we hit places where we couldn't propagate an error code (e.g., in a void routine called by the event lib). I've been working on resolving that in orte, but it still isn't complete. Figure we should do the same to the MPI layer, recognizing that it will take time to complete On Feb 27, 2014, at 1:48 PM, Rolf vandeVaart <rvandevaart_at_[hidden]> wrote: > It could. I added that argument 4 years ago to support by my failover work with the BFO. It was a way for a BTL to pass some type of string back to the PML telling the PML who it was for verbose output to understand what was happening. > >> -----Original Message----- >> From: devel [mailto:devel-bounces_at_[hidden]] On Behalf Of Jeff Squyres >> (jsquyres) >> Sent: Thursday, February 27, 2014 4:22 PM >> To: Open MPI Developers >> Subject: Re: [OMPI devel] [OMPI svn-full] svn:open-mpi r30860 - in >> trunk/ompi/mca: btl/usnic rte >> >> Speaking of which, shouldn't the OB1 error handler send the error message >> string that it received as the 4th param to ompi_rte_abort() so that it can be >> printed out? >> >> >> Index: ompi/mca/pml/ob1/pml_ob1.c >> =========================================================== >> ======== >> --- ompi/mca/pml/ob1/pml_ob1.c (revision 30877) >> +++ ompi/mca/pml/ob1/pml_ob1.c (working copy) >> @@ -780,7 +780,7 @@ >> return; >> } >> #endif /* OPAL_CUDA_SUPPORT */ >> - ompi_rte_abort(-1, NULL); >> + ompi_rte_abort(-1, btlinfo); >> } >> >> #if OPAL_ENABLE_FT_CR == 0 >> >> >> >> On Feb 27, 2014, at 1:12 PM, Jeff Squyres (jsquyres) <jsquyres_at_[hidden]> >> wrote: >> >>> >>> >>> >>> -- >>>] >
https://www.open-mpi.org/community/lists/devel/2014/02/14253.php
CC-MAIN-2016-30
refinedweb
359
66.17
I have made simple Submit score option. User inputs name and score, and they are save to the list. List saves only top 10 scores. Than, list is printed to .txt file. But it works only while program is working. When i start it again, there's only default score in .txt file. User scores weren't saved. I'm using pickle module for that. This is piece of my code. It's Python 3.4 and Tkinter. Keep on mind that I'm learning python. # This is inside class # ... # ... self.printto = tk.Button(self, text="Submit", command=self.highscore ) self.printto.pack(side="left") self.high_scores = [ ('Liz', 1800) ] def highscore(self): name = self.name_ent.get() score = int(self.score_ent.get()) self.high_scores.append((name, score)) high_scores = sorted(self.high_scores, key=itemgetter(1), reverse=True)[:10] with open('D:\Desktop/mytext.txt', 'wb') as f: pickle.dump(high_scores, f) You are only saving data to file, but you are not reading it. You must open the file at the beginning of the program and read scores from it. with open('D:\Desktop/mytext.txt', 'rb') as f: high_scores = pickle.load(f)
https://codedump.io/share/5Ka5X69idVnK/1/how-to-keep-list-changes-when-program-ends
CC-MAIN-2017-43
refinedweb
191
64.67
This column is currently focused on modeling, UML, and XML. More specifically, I am exploring the use of UML modeling for XML development and in particular how XSLT stylesheets can help through automatic derivation. As XML has become a common feature in development projects, many developers have grown interested in integrating XML with the rest of their development. While many organizations still rely on ad-hoc tools for XML development, the trend is towards adopting the same methodology for XML -- or at least one common set of tools -- that is already in use for other development needs, such as Java technology, databases, or the Web. As discussed in the previous column, a model is a simplified description of a system that can assist in calculations and predications. In the context of this article, the system is always an XML vocabulary. Figure 1 illustrates the modeling cycle as a continuum of models. The first models are drawn on the whiteboard (or on a sheet of paper) and tend to be informal. At this stage, the goal is to give all participants (users, developers, designers) a chance to express themselves freely. Figure 1. A continuum of models The next step is to draw a UML model (or several models if the vocabulary is complex). The UML model is more refined and formal, but it remains synthetic and readable because it is intended primarily as a communication device between the team members. The last model is the XML schema, which is the most precise of them all. Its goal is to allow the parser to validate XML documents against the vocabulary definition so it can forego readability in favor of precision. The major difference between all these models is their goal: from informal communication to precise, formal validation by the parser. The difference is not in the nature of the models (simplified description of an XML vocabulary), but in the level of assistance each model provides. If you think of a continuum of models, from the least precise to the most formal, it makes sense to look into automatic derivation -- the process of generating one model automatically from an earlier model. Obviously, automatic derivation works well only if the two models are equally descriptive, which sort of conflicts with the idea of some models being more descriptive than others. Addressing the different levels of description in the models will be the topic of the next column; here, I will focus on derivation. XML Metadata Interchange (XMI) You will recall from the previous installment that I implemented automatic derivation through XMI and XSLT. Assuming that you are already familiar with XML schema (if you're not, see Resources), I will introduce XML Metadata Interchange (XMI) in this section. Vocabularies and compatibility XMI is a sophisticated specification (version 1.2 is over 400 pages), so, in this article, I will limit myself to the bare minimum description needed for automatic derivation. XMI does not specify an XML vocabulary, but rather an algorithm that generates vocabularies for metamodels. In other words, XMI does not define Class, Attribute, Association, or other tags as you would expect. Instead, XMI specifies how to create tags for concepts in a metamodel. I know that's a lot of models to work with, but bear with me -- it will become clearer in a moment. Therefore XMI is not so much a vocabulary as a framework. Unfortunately, this means that no two tools interpret this framework in the same way. Differences also exist between different versions of the same tool: Rational Rose originally supported XMI through an add-on developed by Unisys. The latest versions of Rational XDE have built-in support for XMI, but it's a slightly different variant. The differences are not necessarily significant, but they may cause incompatibilities. In practice, it makes sense to target your stylesheets to the one or two tools that are used in your community and not worry about the rest. In this article, rather than adopting one specific version of XMI, I will stick with the examples published by the OMG. Although no tool is directly compatible with the samples, this is good middle ground. Adapting them to your tool of choice will not be difficult. Although it mostly specifies an algorithm, XMI also defines a few tags and attributes. You will need the following: XMIis always the root element. It must have an xmi.versionattribute (valid versions are 1.0, 1.1, 1.2, and 2.0). XMI.headeris a placeholder for information on the model. Its most important children are XMI.documentationand XMI.metamodel. XMI.documentationholds end-user information as these children elements (whose names are self-explanatory): XMI.owner XMI.contact XMI.longDescription XMI.shortDescription XMI.exporter XMI.exporterVersion XMI.exporterID XMI.notice XMI.metamodelrecords the metamodel to which the XMI algorithm has been applied -- in this case, the UML metamodel (XMI works with other metamodels such as Metaobject Facility, MOF, also published by the OMG). XMI.contentcontains the actual model. xmi.idand xmi.idrefare attributes for encoding links: xmi.idis an element identifier that must be unique; xmi.idrefis a reference to an element by its identifier. The UML metamodel is a model that describes the UML language -- specifically, it describes classes, attributes, associations, packages, collaborations, use cases, actors, messages, states, and all the other concepts in the UML language. For coherence, the metamodel is written in UML. The prefix "meta" indicates that the metamodel describes a model of a model. Likewise, XML is a metalanguage because it's a language that describes languages. The UML metamodel is published in the UML specification. More specifically, XMI uses the "UML Model Interchange" described in chapter 5 of the UML specification (see Resources). Be warned that the UML metamodel is rather large and intimidating. I can only give you a flavor for it in this article. Figure 2 is an excerpt from the metamodel that describes the class, one of the central concepts in class diagrams. Figure 2. the metamodel for a class In the metamodel, the class concept is modeled as the metaclass Class which inherits from the abstract metaclass Classifier. Classifier is the parent for Class, Interface, and Datatype (the latter two are not represented in Figure 2). The inheritance chain continues to: GeneralizableElement, which represents all concepts that can be generalized (inherited from); ModelElement, which represents all abstractions in the model (such as namespace, constraints, and class); and finally Element, the topmost metaclass. Each of these metaclasses has attributes from which Class inherits. A composition exists between Classifier and Feature, which is the parent of StructuralFeature. Attribute is derived from StructuralFeature. Confused by the metamodel? Try to forget it's a metamodel, try to forget it's about UML, and look at it as an ordinary model. Figure 2 is simply pointing out the concept of Class, which is a highly specialized element that is related to interface and data type (through its inheritance from Classifier). Class has a name, visibility, and many more attributes. Finally, there is an association between Class and Attribute. So Figure 2 formally expresses that a class has a name, visibility, and other properties, and that it may have attributes. Indeed, Figure 2 is the definition of a UML class. If you find this confusing, it's probably because the definition itself is written in UML! I have intentionally simplified Figure 1 to ignore namespace, constraint, stereotype, inheritance, and many other aspects of what makes a class a class. Trust me, they are included in the complete UML metamodel but they are not useful for this article. Why bother with the metamodel? Because when you feed it to the XMI algorithm, you get an XML vocabulary for UML. As an example, Listing 1 is an XMI representation of Figure 3 (using the variation of XMI illustrated in the specification -- see above): Figure 3. A UML model for an address Listing 1. The address exported to XMI Notice how the XML elements and attributes in Listing 1 match the classes and attributes in Figure 2. You've now come full circle: The XMI document is a direct representation of the UML metamodel because the UML metamodel is a description of UML itself. A portion of the UML metamodel deals with the visual representation of concepts -- where to draw the concepts on screen. I don't process that information in my stylesheets for two reasons: - It is not needed when deriving an XML schema from the UML model. - It is extremely difficult to produce the visual output when deriving the UML model from an XML schema. A more reasonable option is to open the model in a modeling tool and take a few minutes to prepare the visual representation of the model on screen. The hardest work (getting the definitions right) has been done by the stylesheet. Now that you have the key to reading XMI files, it's easy to map XMI tags to their XML schema equivalents. One possible mapping is: UML:Modelbecomes xs:schema; its target namespace is derived from the model name. UML:Classbecomes a global XML element declaration ( xs:element). UML:Attributebecome a local XML element declaration ( xs:element). Listing 2 is an XSLT stylesheet that implements the mapping: Listing 2. XML schema derivation Obviously, the stylesheet in Listing 2 is still very limited (and it does very limited error checking) because it only supports a small subset of the UML metamodel. It ignores packages, interfaces, associations, and more. You can enrich the stylesheet and support those concepts with a simple extension of the process I've shown you so far: Study the appropriate portion of the UML metamodel, define a mapping to XML schema, and implement it. Listing 2 is very handy if you follow the normal modeling workflow: from the least detailed to the most detailed model. Frequently you will find that an XML schema already exists, and that it should serve as the starting point for your work. It would be tedious to recreate the UML model, so a stylesheet that implements the reverse mapping is handy. Listing 3 is an example: Listing 3. Reverse derivation (from XML schema to UML) Towards more comprehensive stylesheets To say that the stylesheets I have introduced in this article are simplistic would be an understatement. They are less than 50 lines long and deal with a small subset of the UML metamodel. Real-world stylesheets recognize many more UML concepts, and typically weigh in at 500 lines or more. My goal in this installment has been to introduce the concepts behind automatic model derivation: - Even the models (UML, XML schema) are represented as a data set; this special data set is called the metamodel. - You can establish a mapping between the UML metamodel and an XML schema. - You can implement the mapping in XSLT stylesheets. - UML and XML schema are just different representations of the same reality; they differ because they serve different goals. In this article, I have had to make simplifications. If you try to extend the stylesheets from Listings 2 and 3, you may encounter two problems: - The UML model may not be specific enough (because it's a high-level view) to enable meaningful derivation of XML schema (low-level, detailed model). - You may find more than one sensible mapping between the UML metamodel and XML schema. Solving these two problems is the topic of my next two column installments. - Participate in the discussion forum. - Read the UML specification, which includes the complete UML metamodel, at the Object Management Group site. - While you're there, check out the XMI specification, which includes samples of UML data. Although no tools follow these samples faithfully, they are a good middle ground from which it is easy to adapt to the specifics of each tool. - Review the previous installment of this column, "UML, XMI, and code generation, Part 1" (developerWorks, March 2004), in which Benoît Marchal discusses the relationship between UML and XML schema. - If you're new to XML schema, the tutorial "XML Schema Infoset Model" (developerWorks, November 2003) will bring you up to speed. - Explore IBM Rational Rose, the leading UML modeling product. You'll also find plenty of Rational and UML resources on the Rational section of developerWorks. - Find hundreds more XML resources on the developerWorks XML zone, including previous installments of Benoît Marchal's Working XML column. - Find out.
http://www.ibm.com/developerworks/xml/library/x-wxxm24/
crawl-002
refinedweb
2,064
53.92
Alex Martelli <aleax at aleax.it> writes: > Oren Tirosh wrote: > ... >>> > Sounds like a good idea to me, if a sensible name is chosen for the >>> > "main module" (I propose 'main':-). >>> >>> My choice would have been __main__ :-) Is it really the correct way to >>> 'import __main__' instead of 'running' it? >> >> You can't import __main__ - you'll get the one already in sys.modules. > > If there's a __main__ in the zip, we could remove (even assuming it's > already there) the yet-empty sys.modules['__main__']. > >> The code for the main script needs to be executed in __main__'s dict. Then we name the boot module __boot__ and import this from the zip. This could then execute the script in the __main__ module's namespace. > So, I reiterate an idea I've already expressed: key on the executable > file's name. If it's at least six characters long and the first six > characters are (case-insensitive) 'p', 'y', 't', 'h', 'o', 'n' in this > order, forget the whole thing and proceed like now; in other words, > use whatever new tricks we insert *if and only if* the executable file's > name does NOT start with (case-insensitive) 'python'. > >> problems on some obscure environments. A possible alternative would be >> to have a configuration area inside the executable that can be modified >> by an external program (e.g. py2exe). The program would search for a >> signature string and modify the section after it. The configuration >> area can be as simple as a string that overrides the command line >> arguments. > > I suspect "obscure environments" may make it hard for py2exe to find > the needed signature and get at the 'configuration area' (depending on > how executable files are stored when seen as stream of bytes). Still, > such an area would also be useful for other purposes, as you mention > (e.g., supplying the -O switch "at compile time", and the like). So, > perhaps, we could simply test the executable's name FIRST, and if the > name starts with "python" just do nothing, otherwise look at the > configuration area (string) and so on. Sounds much like the way py2exe already works now. It locates the appended zip-file by searching the exefile from the end, then finds the beginning of the zipfile, and looks for a magic number there, which is used to verify that the next n bytes before this position is a C structure containing the required flags. I don't like the idea to scan the executable for a magic signature without further hints where this should be. > On any "obscure environment" > where the set of tricks doesn't work, one would simply have to avoid > renaming or copying the python interpreter to weird names, and otherwise > would be just about as well or badly off as today. >From reading the McMillan installer sources some time ago, I have the impression that on some obscure platforms it's not possible to append the structure and the zipfile to the executable, and on other obscure platforms (or maybe runtime environments, maybe a cgi executable started from apache) it may be difficult to the pathname if the exefile. But, all in all, it sounds like a plan. Although I have the impression that it may be difficult to convince the python-dev crowd to include this in 2.3.1. (Is anyone of them reading this thread?) Thomas
https://mail.python.org/pipermail/python-list/2003-August/188595.html
CC-MAIN-2017-17
refinedweb
565
68.2
Following on from Andy’s post on Webcam support, here is how to use your Webcam to stream color video to your PC. The leJOS program is: package mypackage; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.Socket; import lejos.hardware.BrickFinder; import lejos.hardware.Button; import lejos.hardware.ev3.EV3; import lejos.hardware.lcd.LCD; import lejos.hardware.video.Video; public class Stream { private static final int WIDTH = 160; private static final int HEIGHT = 120; private static final String HOST = "192.168.0.2"; private static final int PORT = 55555; public static void main(String[] args) throws IOException { EV3 ev3 = (EV3) BrickFinder.getLocal(); Video video = ev3.getVideo(); video.open(WIDTH, HEIGHT); byte[] frame = video.createFrame(); Socket sock = new Socket(HOST, PORT); BufferedOutputStream bos = new BufferedOutputStream(sock.getOutputStream()); long start = System.currentTimeMillis(); int frames = 0; LCD.drawString("fps:", 0, 2); while(Button.ESCAPE.isUp()) { try { video.grabFrame(frame); LCD.drawString("" + (++frames * 1000f/(System.currentTimeMillis() - start)), 5,2); bos.write(frame); bos.flush(); } catch (IOException e) { break; } } bos.close(); sock.close(); video.close(); } } And the PC program is: package mypackage; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class CameraFrame { private static final int WIDTH = 160; private static final int HEIGHT = 120; private static final int NUM_PIXELS = WIDTH * HEIGHT; private static final int BUFFER_SIZE = NUM_PIXELS * 2; private static final int PORT = 55555; private ServerSocket ss; private Socket sock; private byte[] buffer = new byte[BUFFER_SIZE]; private BufferedInputStream bis; private BufferedImage image; private CameraPanel panel = new CameraPanel(); private JFrame frame; public CameraFrame() { try { ss = new ServerSocket(PORT); sock = ss.accept(); bis = new BufferedInputStream(sock.getInputStream()); } catch (Exception e) { System.err.println("Failed to connect: " + e); System.exit(1); } image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); } public void createAndShowGUI() { frame = new JFrame("EV3 Camera View"); frame.getContentPane().add(panel); frame.setPreferredSize(new Dimension(WIDTH, HEIGHT)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { close(); } }); frame.pack(); frame.setVisible(true); } public void close() { try { if (bis != null) bis.close(); if (sock != null) sock.close(); if (ss != null) ss.close(); } catch (Exception e1) { System.err.println("Exception closing window: " + e1); } } private; } public void run() { while(true) { synchronized (this) { try { int offset = 0; while (offset < BUFFER_SIZE) { offset += bis.read(buffer, offset, BUFFER_SIZE - offset); } for(int i=0;i<BUFFER_SIZE;i+=4) { int y1 = buffer[i] & 0xFF; int y2 = buffer[i+2] & 0xFF; int u = buffer[i+1] & 0xFF; int v = buffer[i+3] & 0xFF; int rgb1 = convertYUVtoARGB(y1,u,v); int rgb2 = convertYUVtoARGB(y2,u,v); image.setRGB((i % (WIDTH * 2)) / 2, i / (WIDTH * 2), rgb1); image.setRGB((i % (WIDTH * 2)) / 2 + 1, i / (WIDTH * 2), rgb2); } } catch (Exception e) { break; } } panel.repaint(1); } } class CameraPanel extends JPanel { private static final long serialVersionUID = 1L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Ensure that we don't paint while the image is being refreshed synchronized(CameraFrame.this) { g.drawImage(image, 0, 0, null); } } } public static void main(String[] args) { final CameraFrame cameraFrame = new CameraFrame(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { cameraFrame.createAndShowGUI(); } }); cameraFrame.run(); } } Advertisements Thanks a lot for this article – the possibilities this enables now are quite staggering. I have a question though: how do you achieve communication over IP by WiFi and camera usage whereas there is only one usb port on the brick? Do you use some kind of usb hub to plug a wifi dongle and the camera? Any specific brand/model? Same for the webcam: do you know what are the models supported? Thanks you again very much for this article that is of great help to me! I’ll continue following your post closely 🙂 Yes, I use a very tiny USB hub –. I think all UVC webcams are supported – see. I use one similar to this –. They seem to be a copy of a Microsoft webcam and are very cheap. Great, many thanks for this comprehensive answer! I’ll try those out, this is much appreciated. No space left on device Error thanks for sharing this very good stuff 🙂 I tried it my self by using usb hub with 4 ports, I used one for netgear adapter, and other for usb camera. when I installed program on EV3, I got the following error: VIDIOC_STREAMON error 28, No space left on device I googled to find a solution, but they are all talking about 2 web camers on the same bus to produce the problem, which is not my case. Would u please help me on that? I am thinking that the usb camera is the problem as it is cheap china one. I am sorry, I can’t really help, as I have never seen that error. It might be either the camera or the hub. You could try without the hub, but you would need to use USB or Bluetooth for streaming. Or you could try a different camera. The lsusb output might give a clue to the problem. Hi I tried to run the code in my lejos 0.9.0 beta. Runned the pc program as a java aplication, and runned the Lejos code as a lejos program. Lejos gives me the “Connection refused” error and some more errors. I tested the SSH, TELNET and Ping, it’s all ok. What i’m a doing wrong? Thanks Did you change HOST to the IP address of your PC? You also need your firewall (e.g. Windows firewall) to let the PC program run as a server on port 55555 – you will normally be prompted for this. You can change the port number if it clashes with anything else. Do i put the external IP of the host PC? I have to do some port forwarding right? For it to be acessible from any network… Its the local IP of the PC you need as long as the PC and the EV3 are on the same network. You don’t need port forwarding. But if i want to make it online, the only thing to do is to change the ip to external ip right? I don’t know what you mean by you want it online. The EV3 program makes an outward call to a Java server on a PC that shows the video stream from the camera. If you used an external IP address and did port forwarding, then you could have the EV3 in one house and connect over the internet to a PC in another house (for example). That is not the normal definition of online. If you wanted the video stream accessed via a web browser, you would need to do http streaming. That is possible – I might have a go at a blog post on http video streaming. With http streaming, the server would be on the EV3, so you would need port forwarding on the network where the EV3 is running, Yes that’s what i want, you’re right. I struggling with another problem now, the video size and the fps. Is it possible to increase the image size and/or the fps? Thanks for your support! The EV3 processor is not very fast. People seem to get fps ranging from 5 to 10 – I got about 5. If you increased the video size you would get less. I think the video size supported may depend on your camera – you will have to experiment to see what works. I’ve written the post on HTTP streaming – Thanks a lot for this article. could you please tell me why I have problem with video library import lejos.hardware.video.Video; it seems not included in eclipse as well refers to this line by red color hi, how can I get a bigger picture? thanks
https://lejosnews.wordpress.com/2014/09/04/webcam-streaming/
CC-MAIN-2017-43
refinedweb
1,324
68.67