Ejemplo n.º 1
0
        static public bool InitSocket(String adapter, uint baudrate)
        {
            FinalizeApp();
            IBalObject bal       = null;
            bool       succeeded = false;
            IVciDevice device    = null;


            try
            {
                device = GetDeviceByString(adapter);
                //
                // Open bus access layer
                //
                bal = device.OpenBusAccessLayer();

                //
                // Open a message channel for the CAN controller
                //
                mCanChn = bal.OpenSocket(0, typeof(ICanChannel)) as ICanChannel;

                /*//
                 * // Open the scheduler of the CAN controller
                 * //
                 * Log("4"); // не проходит переинициализацию, что-то надо сделать
                 * mCanSched = bal.OpenSocket(0, typeof(ICanScheduler)) as ICanScheduler;*/

                // Initialize the message channel
                mCanChn.Initialize(1024, 128, false);

                // Get a message reader object
                mReader = mCanChn.GetMessageReader();

                // Initialize message reader
                mReader.Threshold = 1;

                // Create and assign the event that's set if at least one message
                // was received.
                mRxEvent = new System.Threading.AutoResetEvent(false);
                mReader.AssignEvent(mRxEvent);

                // Get a message wrtier object
                mWriter = mCanChn.GetMessageWriter();

                // Initialize message writer
                mWriter.Threshold = 1;

                mTxEvent = new System.Threading.AutoResetEvent(false);
                mWriter.AssignEvent(mTxEvent);

                // Activate the message channel
                mCanChn.Activate();


                //
                // Open the CAN controller
                //
                mCanCtl = bal.OpenSocket(0, typeof(ICanControl)) as ICanControl;
                CanBitrate _cb = new CanBitrate();
                switch (baudrate)
                {
                case BAUDRATE_125:
                    _cb = CanBitrate.Cia125KBit; break;

                case BAUDRATE_250:
                    _cb = CanBitrate.Cia250KBit; break;

                default:
                    _cb = CanBitrate.Cia125KBit; break;
                }
                // Initialize the CAN controller
                mCanCtl.InitLine(CanOperatingModes.Standard |
                                 CanOperatingModes.Extended |       //extended отключить наверняка стоит
                                 CanOperatingModes.ErrFrame,
                                 _cb);

                //
                // print line status
                //
                Debug.WriteLine(" LineStatus: " + mCanCtl.LineStatus + "\n|");

                // Set the acceptance filter for std identifiers
                mCanCtl.SetAccFilter(CanFilter.Std,
                                     (uint)CanAccCode.All, (uint)CanAccMask.All);

                // Set the acceptance filter for ext identifiers
                mCanCtl.SetAccFilter(CanFilter.Ext,
                                     (uint)CanAccCode.All, (uint)CanAccMask.All);

                // Start the CAN controller
                mCanCtl.StartLine();

                succeeded = true;
            }
            catch (Exception exc)
            {
                Debug.WriteLine("Error: Initializing socket failed : " + exc.Message + "\n|");
                succeeded = false;
            }
            finally
            {
                DisposeVciObject(device);
                DisposeVciObject(bal);
            }

            return(succeeded);
        }
 private static void PutInPushKeyInfoInSharedPrefs()
 {
     ServiceLocator.Current.GetInstance <IDeveloperToolsService>().LastKeyUploadInfo = PushKeysInfo;
     Debug.WriteLine(PushKeysInfo);
 }
Ejemplo n.º 3
0
 void put(params object[] a) => Debug.WriteLine(string.Join(" ", a));
Ejemplo n.º 4
0
 /// <summary>
 ///     Logs the specified error message.
 /// </summary>
 private static void Error(object sender, DebugEventArgs args)
 {
     MSDebug.WriteLine("[ERROR] " + args.Text);
 }
Ejemplo n.º 5
0
 public void OnProviderEnabled(string provider)
 {
     LiddleSay.WriteLine("ProviderEnabled");
 }
Ejemplo n.º 6
0
 /// <summary>
 ///     Print the specified message.
 /// </summary>
 private static void Print(object sender, DebugEventArgs args)
 {
     MSDebug.WriteLine("[DEBUG] " + args.Text);
 }
Ejemplo n.º 7
0
 /// <summary>
 ///     Logs the specified warning message.
 /// </summary>
 private static void Warning(object sender, DebugEventArgs args)
 {
     MSDebug.WriteLine("[WARNING] " + args.Text);
 }
Ejemplo n.º 8
0
        public void AddToDoItem(ToDo todo)
        {
            Connection.Insert(todo);

            Debug.WriteLine($"Write { todo.Name },{ todo.Description }");
        }
Ejemplo n.º 9
0
        public void Solve()
        {
            var       n   = ri;
            const int MAX = 10000005;
            var       a   = new int[MAX];
            var       b   = new int[MAX];

            foreach (var x in sc.Integer(n))
            {
                a[x] = 1;
            }
            for (int i = 0; i < MAX - 1; i++)
            {
                b[i] = a[i + 1] ^ a[i];
            }
            var xs = Enumerate(2, x => new List <int>());

            for (int i = 0; i < MAX; i++)
            {
                if (b[i] == 1)
                {
                    xs[i % 2].Add(i);
                }
            }


            var isprime = MathEx.Sieve(10000005);

            isprime[2] = false;

            var m = xs[0].Count + xs[1].Count;

            Debug.WriteLine(m);
            Debug.WriteLine(xs[0].AsJoinedString());
            Debug.WriteLine(xs[1].AsJoinedString());
            var G = Enumerate(m + 2, x => new List <Edge>());

            for (int i = 0; i < xs[0].Count; i++)
            {
                for (int j = 0; j < xs[1].Count; j++)
                {
                    if (isprime[Math.Abs(xs[0][i] - xs[1][j])])
                    {
                        G.AddDirectedEdge(i, xs[0].Count + j, 1);
                    }
                }
            }
            var f = m;
            var t = m + 1;

            for (int i = 0; i < xs[0].Count; i++)
            {
                G.AddDirectedEdge(f, i, 1);
            }
            for (int i = 0; i < xs[1].Count; i++)
            {
                G.AddDirectedEdge(xs[0].Count + i, t, 1);
            }
            var mf  = Flow.GetMaxFlow(G, f, t);
            var ans = mf;
            var u   = xs[0].Count - mf;
            var v   = xs[1].Count - mf;

            ans += 2 * (u / 2);
            ans += 2 * (v / 2);
            if (u % 2 == 1)
            {
                ans += 3;
            }
            IO.Printer.Out.WriteLine(ans);
        }
 public void OnResults(Bundle bundle)
 {
     Debug.WriteLine("Speech Results");
     this.SendResults(bundle, this.FinalResults);
 }
 public void OnRmsChanged(float rmsdB)
 {
     Debug.WriteLine("RMS Changed: " + rmsdB);
     this.RmsChanged?.Invoke(rmsdB);
 }
 public void OnPartialResults(Bundle bundle)
 {
     Debug.WriteLine("OnPartialResults Remi");
     this.SendResults(bundle, this.PartialResults);
 }
 public void OnReadyForSpeech(Bundle @params)
 {
     Debug.WriteLine("Ready for Speech");
     this.ReadyForSpeech?.Invoke();
 }
 public void OnEndOfSpeech()
 {
     Debug.WriteLine("End of Speech");
     this.EndOfSpeech?.Invoke();
 }
Ejemplo n.º 15
0
        public void Start(BaseEffect effect)
        {
            if (live_preview_enabled)
            {
                throw new InvalidOperationException("LivePreviewManager.Start() called while live preview is already enabled.");
            }

            // Create live preview surface.
            // Start rendering.
            // Listen for changes to effectConfiguration object, and restart render if needed.

            live_preview_enabled     = true;
            apply_live_preview_flag  = false;
            cancel_live_preview_flag = false;

            layer       = PintaCore.Layers.CurrentLayer;
            this.effect = effect;

            //TODO Use the current tool layer instead.
            live_preview_surface = new Cairo.ImageSurface(Cairo.Format.Argb32,
                                                          PintaCore.Workspace.ImageSize.Width,
                                                          PintaCore.Workspace.ImageSize.Height);

            // Handle selection path.
            PintaCore.Tools.Commit();
            var selection = PintaCore.Workspace.ActiveDocument.Selection;

            selection_path = (selection.Visible) ? selection.SelectionPath : null;
            render_bounds  = (selection_path != null) ? selection_path.GetBounds() : live_preview_surface.GetBounds();
            render_bounds  = PintaCore.Workspace.ClampToImageSize(render_bounds);

            history_item = new SimpleHistoryItem(effect.Icon, effect.Name);
            history_item.TakeSnapshotOfLayer(PintaCore.Layers.CurrentLayerIndex);

            // Paint the pre-effect layer surface into into the working surface.
            using (var ctx = new Cairo.Context(live_preview_surface)) {
                layer.Draw(ctx, layer.Surface, 1);
            }

            if (effect.EffectData != null)
            {
                effect.EffectData.PropertyChanged += EffectData_PropertyChanged;
            }

            if (Started != null)
            {
                Started(this, new LivePreviewStartedEventArgs());
            }

            var settings = new AsyncEffectRenderer.Settings()
            {
                ThreadCount    = PintaCore.System.RenderThreads,
                TileWidth      = render_bounds.Width,
                TileHeight     = 1,
                ThreadPriority = ThreadPriority.BelowNormal
            };

            Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss:ffff") + "Start Live preview.");

            renderer = new Renderer(this, settings);
            renderer.Start(effect, layer.Surface, live_preview_surface, render_bounds);

            if (effect.IsConfigurable)
            {
                if (!effect.LaunchConfiguration())
                {
                    PintaCore.Chrome.MainWindowBusy = true;
                    Cancel();
                }
                else
                {
                    PintaCore.Chrome.MainWindowBusy = true;
                    Apply();
                }
            }
            else
            {
                PintaCore.Chrome.MainWindowBusy = true;
                Apply();
            }
        }
 public void OnBufferReceived(byte[] buffer) => Debug.WriteLine("Buffer Received");
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            Debug.WriteLine("newState: " + newState);

            if (downloaderState != newState)
            {
                downloaderState     = newState;
                statusTextView.Text = GetString(Helpers.GetDownloaderStringFromState(newState));
            }

            bool showDashboard   = true;
            bool showCellMessage = false;
            bool paused          = false;
            bool indeterminate   = true;

            switch (newState)
            {
            case DownloaderState.Idle:
            case DownloaderState.Connecting:
            case DownloaderState.FetchingUrl:
                break;

            case DownloaderState.Downloading:
                indeterminate = false;
                break;

            case DownloaderState.Failed:
            case DownloaderState.FailedCanceled:
            case DownloaderState.FailedFetchingUrl:
            case DownloaderState.FailedUnlicensed:
                paused        = true;
                showDashboard = false;
                indeterminate = false;
                break;

            case DownloaderState.PausedNeedCellularPermission:
            case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                showDashboard   = false;
                paused          = true;
                indeterminate   = false;
                showCellMessage = true;
                break;

            case DownloaderState.PausedByRequest:
                paused        = true;
                indeterminate = false;
                break;

            case DownloaderState.PausedRoaming:
            case DownloaderState.PausedSdCardUnavailable:
                paused        = true;
                indeterminate = false;
                break;

            default:
                paused = true;
                break;
            }

            if (newState != DownloaderState.Completed)
            {
                dashboardView.Visibility   = showDashboard ? ViewStates.Visible : ViewStates.Gone;
                useCellDataView.Visibility = showCellMessage ? ViewStates.Visible : ViewStates.Gone;
                progressBar.Indeterminate  = indeterminate;
                UpdatePauseButton(paused);
            }
            else
            {
                ValidateExpansionFiles();
            }
        }
 public void OnError(SpeechRecognizerError error)
 {
     Debug.WriteLine("Error: " + error);
     this.Error?.Invoke(error);
 }
Ejemplo n.º 19
0
 /// <summary>
 ///     Print the specified message.
 /// </summary>
 public static void Print(string message)
 {
     MSDebug.WriteLine("[DEBUG] " + message);
 }
 public void OnEvent(int eventType, Bundle @params) => Debug.WriteLine("OnEvent: " + eventType);
Ejemplo n.º 21
0
 /// <summary>
 ///     Logs the specified warning message.
 /// </summary>
 public static void Warning(string message)
 {
     MSDebug.WriteLine("[WARNING] " + message);
 }
Ejemplo n.º 22
0
 private void Control_SizeChanged(object sender, EventArgs e)
 {
     Debug.WriteLine("Height: ");
 }
Ejemplo n.º 23
0
 /// <summary>
 ///     Logs the specified error message.
 /// </summary>
 public static void Error(string message)
 {
     MSDebug.WriteLine("[ERROR] " + message);
 }
Ejemplo n.º 24
0
        public async Task <AuthUser> LoginAsync(IMobileServiceClient client, string provider, IDictionary <string, string> parameters = null, bool clientFlow = false)
        {
            try
            {
                var authProvider = (MobileServiceAuthenticationProvider)Enum.Parse(typeof(MobileServiceAuthenticationProvider), Settings.AuthProvider);
                var authUser     = new AuthUser();

                if (clientFlow)
                {
                    #region Client Flow

                    JObject jToken = null;

                    if (authProvider == MobileServiceAuthenticationProvider.Facebook)
                    {
                        var loginResult = await LoginFacebookAsync();

                        authUser.UserInfo = await GetFacebookProfileAsync(loginResult.AccessToken.Token);

                        authUser.AccessToken = loginResult.AccessToken.Token;
                        //authUser.RefreshToken = ...

                        jToken = JObject.FromObject(new
                        {
                            access_token = loginResult.AccessToken.Token,
                            //authorization_code = ...,
                            //id_token = ...,
                        });
                    }

                    if (authProvider == MobileServiceAuthenticationProvider.Google)
                    {
                        var account = await LoginGoogleAsync();

                        authUser.UserInfo = new UserInfo
                        {
                            UserId          = account.Id,
                            Email           = account.Email,
                            UserName        = account.DisplayName,
                            ProfileImageUrl = account.PhotoUrl.Path
                        };
                        authUser.AccessToken = account.IdToken;
                        //authUser.RefreshToken = ...

                        jToken = JObject.FromObject(new
                        {
                            access_token       = account.IdToken,
                            authorization_code = account.ServerAuthCode,
                            id_token           = account.IdToken
                        });
                    }

                    authUser.MobileServiceUser = await client.LoginAsync(authProvider, jToken);

                    #endregion
                }
                else
                {
                    #region Server Flow

                    authUser.MobileServiceUser = await client.LoginAsync(Forms.Context, authProvider, new Dictionary <string, string> {
                        { "access_type", "offline" }
                    });
                    await SetIdentityValues(authUser);

                    if (authProvider == MobileServiceAuthenticationProvider.Facebook)
                    {
                        authUser.UserInfo = await GetFacebookProfileAsync(authUser.AccessToken);
                    }
                    if (authProvider == MobileServiceAuthenticationProvider.Google)
                    {
                        authUser.UserInfo = await GetGoogleProfileAsync(authUser.AccessToken);
                    }

                    #endregion
                }

                return(authUser);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return(null);
        }
Ejemplo n.º 25
0
 public void OnStatusChanged(string provider, Availability status, Bundle extras)
 {
     LiddleSay.WriteLine(string.Format("provider:{0}, status:{1}", provider, status));
 }
Ejemplo n.º 26
0
 public override void OnDisconnected(string p0)
 {
     Debug.WriteLine("### OnDisconnected " + p0);
     _platformBluetooth.OnDisconnected();
 }
Ejemplo n.º 27
0
        public void Solve()
        {
            var n   = ri;
            var h   = sc.Integer() + 1;
            var deg = new int[2 * h];
            var set = new DisjointSet(2 * h + 1);

            for (int i = 0; i < n; i++)
            {
                var a = ri; var b = ri; var c = ri; var d = ri;
                if (c == 0 && d == 0)
                {
                    //Console.WriteLine($"{a} {b + h}");
                    deg[a]++; deg[b + h]--; set.Unite(a, b + h);
                }
                else if (c != 0 && d == 0)
                {
                    //Console.WriteLine($"{c + h} {b + h}");
                    deg[c + h]++; deg[b + h]--; set.Unite(c + h, b + h);
                }
                else if (c == 0 && d != 0)
                {
                    //Console.WriteLine($"{a} {d}");
                    deg[a]++; deg[d]--; set.Unite(a, d);
                }
                else if (c != 0 && d != 0)
                {
                    //Console.WriteLine($"{c + h} {d}");
                    deg[c + h]++; deg[d]--; set.Unite(c + h, d);
                }
                else
                {
                    throw new Exception();
                }
            }
            Debug.WriteLine(deg.AsJoinedString());
            var fail = false;

            fail |= deg.All(x => x == 0);
            fail |= deg.Take(h).Min() < 0;
            fail |= deg.Skip(h).Max() > 0;

            for (int i = 0; i < h; i++)
            {
                var k = -deg[i + h];
                if (k == 0)
                {
                    continue;
                }
                for (int j = 0; j < h; j++)
                {
                    var mi = Math.Min(deg[j], k);
                    if (mi == 0)
                    {
                        continue;
                    }
                    deg[j] -= mi;
                    k      -= mi;
                    set.Unite(i + h, 2 * h);
                    set.Unite(j, 2 * h);
                }
                fail      |= k != 0;
                deg[i + h] = k;
            }
            Debug.WriteLine(deg.AsJoinedString());
            fail |= deg.Any(x => x != 0);
            var cnt = 0;

            for (int i = 0; i <= 2 * h; i++)
            {
                if (set[i] == i && set.Size(i) != 1)
                {
                    cnt++;
                }
                //if (set[i] == i) { Console.WriteLine($"{i} {set.Size(i)}"); }
            }

            fail |= cnt > 1;
            if (fail)
            {
                Console.WriteLine("NO");
            }
            else
            {
                Console.WriteLine("YES");
            }
        }
Ejemplo n.º 28
0
 protected override void OnUpdate(double progress, Gdk.Rectangle updatedBounds)
 {
     Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss:ffff") + " LivePreviewManager.OnUpdate() progress: " + progress);
     PintaCore.Chrome.ProgressDialog.Progress = progress;
     manager.FireLivePreviewRenderUpdatedEvent(progress, updatedBounds);
 }
 public void OnBeginningOfSpeech()
 {
     Debug.WriteLine("Beginning of Speech");
     this.StartOfSpeech?.Invoke();
 }
Ejemplo n.º 30
0
        //protected override void OnCreate(Bundle bundle)
        //{
        //	base.OnCreate(savedInstanceState);

        //	// Create your application here
        //}

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.webflow_mywebview);

            #region WebView

            var client = new ContentWebViewClient();

            client.WebViewLocaitonChanged += (object sender, ContentWebViewClient.WebViewLocaitonChangedEventArgs e) =>
            {
                Debug.WriteLine(e.CommandString);
            };

            client.WebViewLoadCompleted += (object sender, ContentWebViewClient.WebViewLoadCompletedEventArgs e) =>
            {
                RunOnUiThread(() =>
                {
                    AndHUD.Shared.Dismiss(this);
                });
            };


            MyWebView = FindViewById <WebView>(Resource.Id.webflow_mywebview);
            // NOTICE : 先換成一般的 WebViewClient
            //MyWebView.SetWebViewClient(client);
            MyWebView.SetWebViewClient(new MyWebClient());

            MyWebView.Settings.JavaScriptEnabled = true;
            MyWebView.Settings.UserAgentString   = @"Android";

            // 負責與頁面溝通 - WebView -> Native
            MyJSInterface myJSInterface = new MyJSInterface(this);

            MyWebView.AddJavascriptInterface(myJSInterface, "TP");
            myJSInterface.CallFromPageReceived += delegate(object sender, MyJSInterface.CallFromPageReceivedEventArgs e)
            {
                Debug.WriteLine(e.Result);
            };

            // 負責與頁面溝通 - Native -> WebView
            JavaScriptResult callResult = new JavaScriptResult();
            callResult.JavaScriptResultReceived += (object sender, JavaScriptResult.JavaScriptResultReceivedEventArgs e) =>
            {
                Debug.WriteLine(e.Result);
            };


            // 載入一般網頁
            //MyWebView.LoadUrl ("http://stackoverflow.com/");
            // 載入以下程式碼進行互動

            MyWebView.LoadDataWithBaseURL(
                null
                , @"<html>
						<head>
							<title>Local String</title>
							<style type='text/css'>p{font-family : Verdana; color : purple }</style>
							<script language='JavaScript'> 
								var lookup = '中文訊息'
								function msg(){ window.location = 'callfrompage://Hi'  }
							</script>
						</head>
						<body><p>Hello World!</p><br />
							<button type='button' onclick='TP.CallFromPage(lookup)' text='Hi From Page'>Hi From Page</button>
						</body>
					</html>"
                , "text/html"
                , "utf-8"
                , null);



            #endregion

            #region EditText

            _InputMethodManager =
                (InputMethodManager)GetSystemService(Context.InputMethodService);

            TxtUrl = FindViewById <EditText>(Resource.Id.webflow_mywebview_txtUrl);

            TxtUrl.TextChanged += (object sender,
                                   Android.Text.TextChangedEventArgs e) =>
            {
                Debug.WriteLine(TxtUrl.Text + ":" + e.Text);
            };

            #endregion


            BtnGo        = FindViewById <Button>(Resource.Id.webflow_mywebview_btnGo);
            BtnGo.Click += (object sender, EventArgs e) =>
            {
                RunOnUiThread(() =>
                {
                    MyWebView.EvaluateJavascript(@"msg();", callResult);

                    /*
                     * var url = TxtUrl.Text.Trim() ;
                     *
                     * AlertDialog.Builder alert = new AlertDialog.Builder (this);
                     * alert.SetTitle (url);
                     * alert.SetNegativeButton( "取消", (senderAlert, args) =>{
                     *
                     *
                     * });
                     * alert.SetPositiveButton( "確認", (senderAlert, args) =>{
                     *
                     *      RunOnUiThread(
                     *              ()=>{
                     *                      AndHUD.Shared.Show(this, "Status Message", -1, MaskType.Clear);
                     *              }
                     *
                     *      );
                     *
                     *      MyWebView.LoadUrl (url);
                     *
                     * });
                     *
                     * RunOnUiThread (() => {
                     *      alert.Show();
                     * } );
                     *
                     * //
                     * _InputMethodManager.HideSoftInputFromWindow(
                     *      TxtUrl.WindowToken,
                     *      HideSoftInputFlags.None );
                     */
                });
            };
        }