How can I add a countdown in this script, by pressing the left mouse button? Every click counts minus 1. 10,9,8,7,6,5,4,3,2,1,0 example? This currently does not work in this script, and I do not understand the problem.
#pragma strict
var myTrigger : GameObject;
var myObject : GameObject;
var countAmmo : int = 10 ;
private var score : int = 10;
var guiScore : GUIText;
function Start ()
{
guiScore.text = "Score: 10";
}
function Update()
{
if(Input.GetButtonDown("Fire1"))
countAmmo = countAmmo -1;
score = countAmmo -1;
if(countAmmo == 0)
if(score == -1)
{
myObject.SetActive(false);
}
else
{
guiScore.text = "Score: -1";
myObject.SetActive(true);
}
}
I don't know exactly which language this is or in which context you are trying to achieve that, but looking at your code it seems that its only a problem with some brackets in your if-clauses. Try it, no guarantee that it's working.
#pragma strict
var myTrigger : GameObject;
var myObject : GameObject;
var countAmmo : int = 10 ;
private var score : int = 10;
var guiScore : GUIText;
function Start ()
{
guiScore.text = "Score: 10";
}
function Update()
{
if(Input.GetButtonDown("Fire1"))
{
countAmmo = countAmmo -1;
score = countAmmo -1;
guiScore.text = "Score: " + score.ToString();
if(countAmmo <= 0)
{
if(score == -1)
{
myObject.SetActive(false);
} else {
guiScore.text = "Score: -1";
}
myObject.SetActive(true);
}
}
}
This line:
guiScore.text = "Score: -1";
Should be:
guiScore.text = "Score:" + score;
#pragma strict
var myTrigger : GameObject;
var myObject : GameObject;
var countAmmo : int = 10 ;
private var score : int = 10;
var guiScore : GUIText;
function Start ()
{
guiScore.text = "Score: " + score.toString();
}
function Update()
{
if(Input.GetButtonDown("Fire1"))
countAmmo--;
score = countAmmo - 1;
if(countAmmo == 0)
{
if(score == -1)
{
myObject.SetActive(false);
}
else
{
guiScore.text = "Score: " + score.ToString();
myObject.SetActive(true);
}
}
}
Related
I am new to SignalR and in the learning process, I am trying to make Stock ticker. I have over 1000 stocks list and want to show paging and update on real-time changes that's why I am using Groups with SignalR. Problem is that when I open page 1 then everything works fine until I open page 2, then page 1 stop getting signals and page 2 start getting signals. What am I missing here in SignalR groups? Please help me, Thanks.
Hub
[HubName("stockTicker")]
public class StockTickerHub : Hub
{
private StockTicker _stockTicker;
public StockTickerHub()
: this(StockTicker.Instance)
{
}
public StockTickerHub(StockTicker stockTicker)
{
_stockTicker = stockTicker;
}
public void OpenMarket()
{
var page = this.Context.QueryString["page_no"];
int pageno = Convert.ToInt32(page);
_stockTicker.OpenMarket(pageno);
tryAddGroup(page);
}
public Task tryAddGroup(string page)
{
return Groups.Add(Context.ConnectionId, page);
}
}
StockTicker.cs
public class StockTicker
{
MainModel _model = new MainModel();
private static Lazy<StockTicker> _instance = new Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients));
private TimeSpan _updateInterval = TimeSpan.FromMilliseconds(3000);
private Timer _timer;
public volatile int pageno;
private StockTicker(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
}
public static StockTicker Instance
{
get
{
return _instance.Value;
}
}
private IHubConnectionContext<dynamic> Clients
{
get;
set;
}
public void OpenMarket(int page_no)
{
pageno = page_no;
_timer = new Timer(UpdateStockPrices, pageno, _updateInterval, _updateInterval);
}
private void UpdateStockPrices(object state)
{
var latest_stocks = new List<StockViewModel>();
latest_stocks = _model.Get100Stocks(pageno);
foreach (var stock in latest_stocks)
{
BroadcastStockPrice(stock, pageno);
}
}
private void BroadcastStockPrice(StockViewModel stock, int pageno)
{
Clients.Group(pageno.ToString()).updateStockPrice(stock);
//Clients.All.updateStockPrice(stock);
}
}
(Updated Question)
StockTicker.js
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
}
jQuery.fn.flash = function (color, duration) {
var current = this.css('backgroundColor');
this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
.animate({ backgroundColor: current }, duration / 2);
};
$(function () {
var ticker = $.connection.stockTicker;
var $stockTable = $('#stockTable');
var $stockTableBody = $stockTable.find('tbody');
tdPrice = '<td data-rank-price="{currency_query}" data-sort="{currency_price_usd}"><div data-price-spn="{currency_query}">${currency_price_usd}</div></td>';
tdPercentage = '<td data-rank-perc="{currency_query}" data-sort="{currency_change_24h_usd}"><div data-change-spn="{currency_query}"><span class="{DirectionClass}">{currency_change_24h_usd}</span></div></td>';
tdVolume = '<td data-rank-volume="{currency_query}" data-sort="{currency_24h_volume_usd}"><div data-24-volume-spn="{currency_query}>${currency_24h_volume_usd}</div></td>';
tdMarketcap = '<td data-rank-cap="{currency_query}" data-sort="{currency_market_cap_usd}"><div data-mcap-spn="{currency_query}">${currency_market_cap_usd}</div></td>';
function formatStock(stock) {
return $.extend(stock, {
currency_price_usd: formatprices(stock.currency_price_usd),
currency_change_24h_usd: stock.currency_change_24h_usd == null ? '0.00%' : (stock.currency_change_24h_usd).toFixed(2) + '%',
currency_24h_volume_usd: stock.currency_24h_volume_usd == null ? '0' : nFormatter(stock.currency_24h_volume_usd, 2),
currency_market_cap_usd: stock.currency_market_cap_usd == null ? '0' : nFormatter(stock.currency_market_cap_usd, 2),
DirectionClass: stock.currency_change_24h_usd === 0 ? 'nochange' : stock.currency_change_24h_usd >= 0 ? 'green' : 'red'
});
}
function nFormatter(num, digits) {
var si = [
{ value: 1, symbol: "" },
{ value: 1E3, symbol: "K" },
{ value: 1E6, symbol: "M" },
{ value: 1E9, symbol: "B" },
{ value: 1E12, symbol: "T" },
{ value: 1E15, symbol: "P" },
{ value: 1E18, symbol: "E" }
];
var rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
var i;
for (i = si.length - 1; i > 0; i--) {
if (num >= si[i].value) {
break;
}
}
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}
function formatprices(n, curr) {
var sep = sep || ".";
var decimals;
if (n > 0.99999999) {
decimals = decimals || 2;
}
else {
decimals = decimals || 6;
}
return n.toLocaleString().split(sep)[0]
+ sep
+ n.toFixed(decimals).split(sep)[1];
}
$.extend(ticker.client, {
updateStockPrice: function (stock) {
var displayStock = formatStock(stock),
$tdprice = $(tdPrice.supplant(displayStock)),
$tdpercentage = $(tdPercentage.supplant(displayStock)),
$tdvolume = $(tdVolume.supplant(displayStock)),
$tdcap = $(tdMarketcap.supplant(displayStock));
if (stock.LastChange != 0.0) {
bgprice = stock.LastChange < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-price=' + stock.currency_query + ']').replaceWith($tdprice);
$tdpricespn = $stockTableBody.find('div[data-price-spn=' + stock.currency_query + ']');
$tdpricespn.flash(bgprice, 1500);
}
if (stock.LastChangePercentage != 0.0) {
bgper = stock.LastChangePercentage < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-perc=' + stock.currency_query + ']').replaceWith($tdpercentage);
$tdpercentagespn = $stockTableBody.find('div[data-change-spn=' + stock.currency_query + ']');
$tdpercentagespn.flash(bgper, 1500);
}
if (stock.LastChangeVolume != 0.0) {
bgvol = stock.LastChangeVolume < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-volume=' + stock.currency_query + ']').replaceWith($tdvolume);
$tdvolumespn = $stockTableBody.find('div[data-24-volume-spn=' + stock.currency_query + ']');
$tdvolumespn.flash(bgvol, 1500);
}
if (stock.LastChangeCap != 0.0) {
bgcap = stock.LastChangeCap < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-cap=' + stock.currency_query + ']').replaceWith($tdcap);
$tdcapspn = $stockTableBody.find('div[data-mcap-spn=' + stock.currency_query + ']');
$tdcapspn.flash(bgcap, 1500);
}
}
});
$.connection.hub.url = 'http://localhost:13429/signalr';
$.connection.hub.qs = { 'page_no': $("#page").val() };
$.connection.hub.start().done(function () {
console.log("connected");
}).then(function () {
return ticker.server.openMarket();
});
});
Looking at your code, your global variable pageno is always the last page that was requested:
public void OpenMarket(int page_no)
{
pageno = page_no;
_timer = new Timer(UpdateStockPrices, pageno, _updateInterval, _updateInterval);
}
You need another variable that tracks the max page.
public volatile int pageMax;
public void OpenMarket(int page_no)
{
pageno = page_no;
pageMax = pageno > pageMax
: pageno
? pageMax;
_timer = new Timer(UpdateStockPrices, pageno, _updateInterval, _updateInterval);
}
Then make sure to broadcast the correct stocks to the pages.
Is there any alternative to System.Web.Security.Membership.GeneratePassword in AspNetCore (netcoreapp1.0).
The easiest way would be to just use a Guid.NewGuid().ToString("n") which is long enough to be worthy of a password but it's not fully random.
Here's a class/method, based on the source of Membership.GeneratePassword of that works on .NET Core:
public static class Password
{
private static readonly char[] Punctuations = "!##$%^&*()_-+=[{]};:>|./?".ToCharArray();
public static string Generate(int length, int numberOfNonAlphanumericCharacters)
{
if (length < 1 || length > 128)
{
throw new ArgumentException(nameof(length));
}
if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
{
throw new ArgumentException(nameof(numberOfNonAlphanumericCharacters));
}
using (var rng = RandomNumberGenerator.Create())
{
var byteBuffer = new byte[length];
rng.GetBytes(byteBuffer);
var count = 0;
var characterBuffer = new char[length];
for (var iter = 0; iter < length; iter++)
{
var i = byteBuffer[iter] % 87;
if (i < 10)
{
characterBuffer[iter] = (char)('0' + i);
}
else if (i < 36)
{
characterBuffer[iter] = (char)('A' + i - 10);
}
else if (i < 62)
{
characterBuffer[iter] = (char)('a' + i - 36);
}
else
{
characterBuffer[iter] = Punctuations[i - 62];
count++;
}
}
if (count >= numberOfNonAlphanumericCharacters)
{
return new string(characterBuffer);
}
int j;
var rand = new Random();
for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
{
int k;
do
{
k = rand.Next(0, length);
}
while (!char.IsLetterOrDigit(characterBuffer[k]));
characterBuffer[k] = Punctuations[rand.Next(0, Punctuations.Length)];
}
return new string(characterBuffer);
}
}
}
I've omitted the do...while loop over the CrossSiteScriptingValidation.IsDangerousString. You can add that back in yourself if you need it.
You use it like this:
var password = Password.Generate(32, 12);
Also, make sure you reference System.Security.Cryptography.Algorithms.
System.Random doesn't provide enough entropy when used for security reasons.
https://cwe.mitre.org/data/definitions/331.html
Why use the C# class System.Random at all instead of System.Security.Cryptography.RandomNumberGenerator?
Please see the example below for a more secure version of #khellang version
public static class Password
{
private static readonly char[] Punctuations = "!##$%^&*()_-+[{]}:>|/?".ToCharArray();
public static string Generate(int length, int numberOfNonAlphanumericCharacters)
{
if (length < 1 || length > 128)
{
throw new ArgumentException("length");
}
if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
{
throw new ArgumentException("numberOfNonAlphanumericCharacters");
}
using (var rng = RandomNumberGenerator.Create())
{
var byteBuffer = new byte[length];
rng.GetBytes(byteBuffer);
var count = 0;
var characterBuffer = new char[length];
for (var iter = 0; iter < length; iter++)
{
var i = byteBuffer[iter] % 87;
if (i < 10)
{
characterBuffer[iter] = (char)('0' + i);
}
else if (i < 36)
{
characterBuffer[iter] = (char)('A' + i - 10);
}
else if (i < 62)
{
characterBuffer[iter] = (char)('a' + i - 36);
}
else
{
characterBuffer[iter] = Punctuations[GetRandomInt(rng, Punctuations.Length)];
count++;
}
}
if (count >= numberOfNonAlphanumericCharacters)
{
return new string(characterBuffer);
}
int j;
for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
{
int k;
do
{
k = GetRandomInt(rng, length);
}
while (!char.IsLetterOrDigit(characterBuffer[k]));
characterBuffer[k] = Punctuations[GetRandomInt(rng, Punctuations.Length)];
}
return new string(characterBuffer);
}
}
private static int GetRandomInt(RandomNumberGenerator randomGenerator)
{
var buffer = new byte[4];
randomGenerator.GetBytes(buffer);
return BitConverter.ToInt32(buffer);
}
private static int GetRandomInt(RandomNumberGenerator randomGenerator, int maxInput)
{
return Math.Abs(GetRandomInt(randomGenerator) % maxInput);
}
}
In my web application i need to draw shapes in the image using mouse.But i was struck draw and resize polygon..i have dawned polygon..How to resize it?
i can able to draw polygon using the above code.
But i need to resize it..any idea to resize the drowned polygon?
Please refer the below code.
private function onDrawTriangle() : void {
var ui:UIComponent = new UIComponent();
drawPanel = new Sprite();
drawPanel.graphics.clear();
drawPanel.graphics.lineStyle(2, 0xFF0000);
drawPanel.graphics.beginFill(0xDEFACE);
drawPanel.graphics.drawRect(0,0,300,300);
drawPanel.graphics.endFill();
ui.addChild(drawPanel);
addChild(ui);
ui.x = 20;
ui.y = 20;
_lineArr = new Array();
line = new Shape();
drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
}
private function onAddPoint(evt:MouseEvent) : void {
if(numSpot <= 10) {
var point:Sprite = new Sprite();
point.graphics.clear();
point.graphics.lineStyle(0,0x0000FF);
point.graphics.beginFill(0x0000FF);
point.graphics.drawCircle(0,0,5);
point.graphics.endFill();
point.x = evt.localX;
point.y = evt.localY;
_lineArr.push({x:point.x,y:point.y});
drawPanel.addChild(point);
if(numSpot > 0) drawLine();
numSpot++;
}
}
private function drawLine() : void {
line.graphics.clear();
line.graphics.lineStyle(2,0x000000);
if(_lineArr.length > 2) line.graphics.beginFill(0xFF0000,0.5);
line.graphics.moveTo(_lineArr[0].x,_lineArr[0].y);
for(var i:int=1;i<_lineArr.length;i++) {
line.graphics.lineTo(_lineArr[i].x,_lineArr[i].y);
}
line.graphics.lineTo(_lineArr[0].x,_lineArr[0].y);
if(_lineArr.length > 2) line.graphics.endFill();
drawPanel.addChildAt(line,0);
}
Rather pushing points to array you may push the point(sprite variable).
Have a look on the modified codes for the above codes where I added some more events to re size the polygon
Here is the sample code:
private function onDrawTriangle() : void {
var ui:SpriteVisualElement = new SpriteVisualElement();
//ui.x = 20;
//ui.y = 20;
addElement(ui);
drawPanel = new Sprite();
drawPanel.graphics.clear();
drawPanel.graphics.lineStyle(2, 0xFF0000);
drawPanel.graphics.beginFill(0xDEFACE);
drawPanel.graphics.drawRect(0,0,300,300);
drawPanel.graphics.endFill();
ui.addChild(drawPanel);
_lineArr = new Array();
line = new Shape();
drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
}
private function onAddPoint(evt:MouseEvent) : void {
if(numSpot <= 10) {
var point:Sprite = new Sprite();
point.graphics.clear();
point.graphics.lineStyle(0,0x0000FF);
point.graphics.beginFill(0x0000FF);
point.graphics.drawCircle(0,0,5);
point.graphics.endFill();
point.x = mouseX;
point.y = mouseY;
point.addEventListener(MouseEvent.MOUSE_DOWN , onDown);
_lineArr.push(point);
drawPanel.addChild(point);
if(numSpot > 0) drawLine();
numSpot++;
}
}
private function drawLine() : void {
line.graphics.clear();
line.graphics.lineStyle(2,0x000000);
if(_lineArr.length > 2) line.graphics.beginFill(0xFF0000,0.5);
line.graphics.moveTo(_lineArr[0].x,_lineArr[0].y);
for(var i:int=1;i<_lineArr.length;i++) {
line.graphics.lineTo(_lineArr[i].x,_lineArr[i].y);
}
line.graphics.lineTo(_lineArr[0].x,_lineArr[0].y);
if(_lineArr.length > 2) line.graphics.endFill();
drawPanel.addChildAt(line,0);
}
protected function onDown(event:MouseEvent):void
{
var point:Sprite = event.currentTarget as Sprite;
point.addEventListener(Event.ENTER_FRAME , onResize);
point.addEventListener(MouseEvent.MOUSE_UP , onUp);
drawPanel.removeEventListener(MouseEvent.CLICK,onAddPoint);
}
protected function onResize(event:Event):void
{
var point:Sprite = event.currentTarget as Sprite;
point.x = mouseX;
point.y = mouseY;
drawLine();
}
protected function onUp(event:MouseEvent):void
{
var point:Sprite = event.currentTarget as Sprite;
point.removeEventListener(Event.ENTER_FRAME , onResize);
point.removeEventListener(MouseEvent.MOUSE_UP , onUp);
drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
}
I am working on the platform confirmit, which creates online surveys. This is a script node that results in the runtime error "object required", I would be grateful if you could help me fix it.. It is supposed to check whether certain codes hold 1 or 2 in the questions q2b and q3a (questions are referenced with the function f() - f(question id)[code]) - the
'//skip ?' part. Then it recodes a maximum of four of the codes into another question (h_q4) for further use.
var flag1 : boolean = false;
var flag2 : boolean = false;
//null
for(var i: int=0; i <9; i++)
{
var code = i+1;
f("h_q4")[code].set(null);
}
f("h_q4")['95'].set(null);
//skip ?
for(var k: int=1; k <16; k+=2)
{
var code = k;
if(f("q2b")[code].none("1", "2"))
flag1;
else
{
flag1 = 0;
break;
}
}
if(f("q3a")['1'].none("1", "2"))
flag2;
if(flag1 && flag2)
f("h_q4")['95'].set("1");
//recode
else
{
var fromForm = f("q2b");
var toForm = f("h_q4");
const numberOfItems : int = 4;
var available = new Set();
if(!flag1)
{
for( i = 1; i < 16; i+=2)
{
var code = i;
if(f("q2b")[i].any("1", "2"))
available.add(i);
}
}
if(!flag2)
{
available.add("9");
}
var selected = new Set();
if(available.size() <= numberOfItems)
{
selected = available;
}
else
{
while(selected.size() < numberOfItems)
{
var codes = available.members();
var randomNumber : float = Math.random()*codes.length;
var randomIndex : int = Math.floor(randomNumber);
var selectedCode = codes[randomIndex];
available.remove(selectedCode);
selected.add(selectedCode);
}
}
var codes = fromForm.domainValues();
for(var i = 0;i<codes.length;i++)
{
var code = codes[i];
if(selected.inc(code))
{
toForm[code].set("1");
}
else
{
toForm[code].set("0");
}
}
}
the first part of the code (//null) empties the 'recepient' question to ease testing
.set(), .get(), .any(), .none() are all valid
So we have flv file, we play it with mx:vidodisplay for example. how to get on which stream frame we are currently on?
you can check the nearest keyframe to the current time in stream metadata
upd
when creating a stream you need to handle its' onMetaData call:
private var metaInfo: Object;
private function initStream():void{
stream = new NetStream(conn);
stream.bufferTime = 5;
stream.addEventListener(NetStatusEvent.NET_STATUS, onStatus);
stream.client = new Object();
stream.client.onMetaData = onMetaData;/*this is what you need*/
video.attachNetStream(stream);
}
private function onMetaData(info:Object):void {
metaInfo = info;
var tmpstr:String = '';
for(var s:String in info){
var tstr:String = s + ' = ' + info[s] + '\n';
tmpstr += tstr.indexOf('object') == -1 ? tstr : '';
for(var a:String in info[s]){
var ttstr:String = s + ':' + a + ' = ' + info[s][a] + '\n';
tmpstr += ttstr.indexOf('object') == -1 ? ttstr : '';
for(var c:String in info[s][a]){
var tttstr:String = s + ':' + a + ':' + c + ' = ' + info[s][a][c] + '\n';
tmpstr += tttstr.indexOf('object') == -1 ? tttstr : '';
}
}
}
trace(tmpstr);
}
in this trace you'll see if the streams' metadata has items like:
seekpoints:93:offset = 10342550
seekpoints:93:time = 165.799
or maybe:
keyframes:times = 0,0.48,0.96,1.44,1.92,2.4,2.88,3.36,3.84,4.32,4.8,5.28,5.76,6.24
keyframes:filepositions = 1063,95174,136998,176043,209542,239148,271062,302006,331724,363948,395039,427503,456317,483313
it depends on encoder settings, if your metadata has any object of this kind (metadata['keyframes'], metadata['seekpoints'] etc) you can do the following:
for (var i:int = 0; i < metaInfo['keyframes']['times'].length; i++) {
if (stream.time < metaInfo['keyframes']['times'][i]) {
var keyFrameNum: int = (metaInfo['keyframes']['times'][i] - stream.time < stream.time - metaInfo['keyframes']['times'][i - 1]) ? i : i - 1;
}
}
I did a static class to parse netstream metadata object to as3 object. You can use JSON.stringify(parse(info)) to check all attribute in info. This class just draftly implement. May be some bugs inside.
public class NetStreamMetaData
{
public static function parse(object:Object, isArray:Boolean = false):Object{
var ret:Object = {};
if(isArray)
ret = [];
var k:String;
for(k in object){
if(isNaN(Number(k))){
if(object[k] is Array){
ret[k] = parse(object[k], true);
}else{
ret[k] = object[k];
}
}else{
if(object[k] is Array){
ret.push(parse(object[k], false));
}else{
ret.push(object[k]);
}
}
}
return ret;
}
}