text
stringlengths
1
1.04M
language
stringclasses
25 values
Entertainment never stops at Supermoon, as the much-loved platform always ups the engagement quotient for fans with the best and never seen before acts. A few weeks after announcing AP Dhillon’s debut India tour, Supermoon is now back with Kalamkaar India Tour. All the hip-hop fans out there, get ready and polish your rapping skills as Supermoon ft Kalamkaar is coming to a city near you. The extraordinary talent showcase featuring as many as six popular Indian rap and hip-hop stars will embark on its musical journey from Hyderabad on 12th December 2021, moving to Gurugram on 17th December 2021 and ending the tour in Goa on 19th December 2021. Tickets for this eagerly awaited experience will be available on Paytm insider. The upcoming on-ground concert will give hip-hop fans a chance to be closer to their idols as they perform live on their most popular numbers on-stage. The tour will feature Raftaar, the ever-popular Indian rapper, lyricist, dancer, TV personality and music composer headlining the shows along with electrifying performances by the trending hip-hop artists such as Rashmeet, Kr$na, Deep Kalsi, Karma and Yunan. Along with keeping entertainment at its absolute peak, Zee Live shall leave no stone unturned towards ensuring its patrons a safe environment by adhering to the highest standards of safety and hygiene.
english
Tianhui- salah satu pengeluar dan pembekal cip LED UV terkemuka menyediakan perkhidmatan cip LED UV ODM/OEM. Tianhui TO46 340nm UVA LED adalah sumber cahaya yang digunakan untuk ujian perubatan, terutamanya untuk analisis darah dan aspek lain. Sumber cahaya LED ini mempunyai panjang gelombang 340 nanometer dan tergolong dalam jalur ultraviolet A. Cahaya ultraviolet A-band mempunyai panjang gelombang yang lebih panjang dan tenaga yang lebih rendah, menjadikannya sesuai untuk aplikasi perubatan tertentu. Dalam bidang perubatan, analisis darah adalah salah satu kaedah pengesanan yang paling penting. Dengan menganalisis sampel darah, maklumat penting tentang status kesihatan pesakit boleh diperolehi, seperti kiraan sel darah merah, kiraan sel darah putih, kandungan hemoglobin, dsb. Sebagai sumber cahaya, Tianhui TO46 340nm UVA LED boleh memberikan cahaya ultraviolet A yang mencukupi untuk merangsang komponen atau penanda tertentu dalam darah, dengan itu membantu pekerja perubatan dalam analisis darah. Terdapat beberapa kelebihan untuk menggunakan Tianhui TO46 340nm UVA LED untuk analisis darah. Pertama, cahaya ultraungu A boleh menembusi sampel darah dan berinteraksi dengan komponen tertentu di dalamnya. Kedua, Tianhui TO46 340nm UVA LED mempunyai masa tindak balas yang lebih pendek dan jangka hayat yang lebih lama, memberikan sumber cahaya yang stabil dan boleh dipercayai. Selain itu, reka bentuk pembungkusan TO46 menjadikannya lebih padat dan mudah untuk disepadukan ke dalam peranti perubatan. Zhuhai Tianhui Electronic Co., Ltd. Diasaskan pada 2002 . Ini adalah syarikat berorientasikan pengeluaran dan teknologi tinggi bersepadu penyelidikan dan pembangunan, pengeluaran, jualan dan penyelesaian yang menyediakan LED UV, yang khusus dalam melakukan pembungkusan LED UV dan menyediakan penyelesaian UV LED produk siap untuk pelbagai aplikasi LED UV. Tianhui electric telah terlibat dalam pakej UV LED dengan siri pengeluaran penuh dan kualiti dan kebolehpercayaan yang stabil serta harga yang kompetitif. Produk termasuk UVA, UVB, UVC daripada panjang gelombang pendek kepada panjang gelombang panjang dan spesifikasi LED UV lengkap daripada kuasa kecil kepada kuasa tinggi. 1. Untuk mengelakkan pereputan tenaga, pastikan kaca hadapan bersih. 2. Adalah disyorkan untuk tidak mempunyai objek yang menghalang cahaya sebelum modul, yang akan menjejaskan kesan pensterilan. 3. Sila gunakan voltan input yang betul untuk memacu modul ini, jika tidak modul akan rosak. disyorkan bahawa gam lubang keluar modul terus menghubungi air minuman. Pendedahan kepada cahaya ultraungu boleh menyebabkan kerosakan pada mata manusia. Jangan melihat cahaya ultraviolet secara langsung atau tidak langsung.
english
<gh_stars>1-10 /* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.spinnaker.halyard.cli.command.v1.config.providers.aws; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.netflix.spinnaker.halyard.cli.command.v1.config.providers.account.AbstractAddAccountCommand; import com.netflix.spinnaker.halyard.config.model.v1.node.Account; import com.netflix.spinnaker.halyard.config.model.v1.providers.aws.AwsAccount; import com.netflix.spinnaker.halyard.config.model.v1.providers.aws.AwsProvider; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Parameters(separators = "=") public class AwsAddAccountCommand extends AbstractAddAccountCommand { protected String getProviderName() { return "aws"; } @Parameter( names = "--default-key-pair", description = AwsCommandProperties.DEFAULT_KEY_PAIR_DESCRIPTION ) private String defaultKeyPair; @Parameter( names = "--edda", description = AwsCommandProperties.EDDA_DESCRIPTION ) private String edda; @Parameter( names = "--discovery", description = AwsCommandProperties.DISCOVERY_DESCRIPTION ) private String discovery; @Parameter( names = "--account-id", description = AwsCommandProperties.ACCOUNT_ID_DESCRIPTION, required = true ) private String accountId; @Parameter( names = "--regions", variableArity = true, description = AwsCommandProperties.REGIONS_DESCRIPTION ) private List<String> regions = new ArrayList<>(); @Parameter( names = "--assume-role", description = AwsCommandProperties.ASSUME_ROLE_DESCRIPTION, required = true ) private String assumeRole; @Override protected Account buildAccount(String accountName) { AwsAccount account = (AwsAccount) new AwsAccount().setName(accountName); account.setDefaultKeyPair(defaultKeyPair) .setEdda(edda) .setDiscovery(discovery) .setAccountId(accountId) .setRegions(regions .stream() .map(r -> new AwsProvider.AwsRegion().setName(r)) .collect(Collectors.toList()) ) .setAssumeRole(assumeRole); return account; } @Override protected Account emptyAccount() { return new AwsAccount(); } }
java
<reponame>Server1567/LandingPage-of-Multiclase /* Description: © Multiclase, imagina, aprende y crea Version: 1 Author: <NAME>(Server1567) - Front-End Developer Author URL: https://server1567.herokuapp.com */ /* Not allow Scroll at the Screen */ .no_scroll { overflow: hidden; } .card-panel { border-radius: 0 !important; } body { margin: 0; padding: 0; min-height: 100vh; display: flex; flex-direction: column; } div #body { flex: 1 0 auto; } #caption-img { display: flex; flex-direction: column; } .lets_go { display: flex; flex-direction: row; align-items: center; cursor: pointer; width: 17%; color: lightblue; } .lets_go:hover { color: cyan; } .icon-block { padding: 0 15px; } .icon-block .material-icons { font-size: inherit; } .team { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: 0 !important; padding: 100px 0px !important; } .team-card { width: 250px !important; top: 100px !important; } .worker { margin: 0 !important; width: 100%; } .contact { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: 0 !important; padding: 100px 0px; } /* Little Content */ #little-content { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 100px 0px; } .little-content { margin: 10px; } .little-content:hover { color: gray; } .new-add { color: darkgray; } .section-little-content { list-style: none; } .section-little-content-li { display: inline-block; } /* CONTACT */ form { width: 50% !important; margin: auto; } /* FOOTER */ /* Area de Redes Sociales */ .facebook, .twitter, .instagram { display: inline-block; font-style:27px; font-size: 29px; width: 52px; height: 50px; font-line:20px; border-radius: 50%; color: #fff; padding: 5px; } .facebook:hover { color: #2b416f; } .twitter:hover { color: #3f82b1; } .instagram:hover { color: purple; } .facebook { background: #3B5998; margin: 15px 15px 15px 0px; } .twitter { background: #55ACEE; margin: 15px 15px 15px 0px; } .instagram { background: linear-gradient(60deg, #3051F1 10%, #C92BB7 60%); margin: 15px 15px 15px 0px; } /********** MEDIA QUERIES ***********/ /* DESKTOP */ @media screen and (min-width: 992px){ .brand-logo { text-align: left; } form { width: 50% !important; } } /* TABLET */ @media screen and (min-width: 600px) and (max-width: 992px){ .brand-logo { text-align: center; } .lets_go { width: 30%; } form { width: 90% !important; } } /* MOBILE */ @media screen and (max-width: 600px){ .brand-logo { text-align: center; } img .b-logo { width: 40%; padding: 5px; } .lets_go { width: 50%; } form { width: 90% !important; } }
css
“I have decided to make changes to the national executive,” Zuma said in a terse announcement of five senior ministerial changes, which he said was aimed at taking South Africa’s transformation forward. Zuma announced that Sexwale, who defied the president in a recent ANC leadership battle, would be removed as minister for human settlements. The departure of 60-year-old Sexwale – who served prison time on Robben Island with Nelson Mandela and is now one of South Africa’s richest men – consolidates Zuma’s power base and removes a potential rival. He was replaced by ANC member of parliament Connie September. “Twenty years of democracy have changed the face of our country, and the last five years have pushed that change forward,” Zuma said, thanking Sexwale and others for their service. Sexwale, once a commander of the ANC’s armed wing, has long been tipped as a potential leader of the party and of the country. After the 1994 elections he served as the premier of Gauteng province, which incorporates Johannesburg and Pretoria, but relinquished this post in 1999 to become a businessman. In the private sector he picked up a string of directorships and assets spanning the mining, engineering and energy sectors, earning most of his wealth in the diamond sector. Zuma also axed communications minister Dina Pule, who has been embroiled in a corruption probe over favours to her alleged lover. Meanwhile the ministers of energy and transport traded portfolios. But the biggest surprise may have been the ministers who survived. Basic education minister Angie Motshekga survived despite a scandal that left kids in one province without textbooks for a year.
english
{ "date_blocked": null, "citation": { "state_cite_three": null, "federal_cite_one": "358 U.S. 52", "federal_cite_two": null, "specialty_cite_one": null, "federal_cite_three": null, "lexis_cite": null, "document_uris": [ "/api/rest/v2/document/105778/" ], "scotus_early_cite": null, "case_name": "<NAME>", "westlaw_cite": null, "state_cite_one": null, "neutral_cite": null, "state_cite_regional": null, "state_cite_two": null, "docket_number": "266", "id": 90161, "resource_uri": "/api/rest/v2/citation/90161/" }, "id": 105778, "blocked": false, "judges": "<NAME>", "court": "/api/rest/v2/jurisdiction/scotus/", "date_filed": "1958-10-20", "download_url": null, "source": "LR", "local_path": null, "html_lawbox": "<div>\n<center><b>358 U.S. 52 (1958)</b></center>\n<center><h1>KOVRAK<br>\nv.<br>\nGINSBURG ET AL., MEMBERS OF THE COMMITTEE ON UNAUTHORIZED PRACTICE OF THE LAW.</h1></center>\n<center>No. 266.</center>\n<center><p><b>Supreme Court of United States.</b></p></center>\n<center>Decided October 20, 1958.</center>\nAPPEAL FROM THE SUPREME COURT OF PENNSYLVANIA, EASTERN DISTRICT.\n<p><i><NAME></i> and <i><NAME></i> for appellant.</p>\n<p><i><NAME></i> for appellees.</p>\n<p>PER CURIAM.</p>\n<p>The motion to dismiss is granted and the appeal is dismissed for want of a substantial federal question.</p>\n</div>", "time_retrieved": "2010-04-28T09:55:42", "nature_of_suit": "", "plain_text": "", "html_with_citations": "<div>\n<center><b><span class=\"citation no-link\"><span class=\"volume\">358</span> <span class=\"reporter\">U.S.</span> <span class=\"page\">52</span></span> (1958)</b></center>\n<center><h1>KOVRAK<br>\nv.<br>\nGINSBURG ET AL., MEMBERS OF THE COMMITTEE ON UNAUTHORIZED PRACTICE OF THE LAW.</h1></center>\n<center>No. 266.</center>\n<center><p><b>Supreme Court of United States.</b></p></center>\n<center>Decided October 20, 1958.</center>\nAPPEAL FROM THE SUPREME COURT OF PENNSYLVANIA, EASTERN DISTRICT.\n<p><i><NAME></i> and <i><NAME></i> for appellant.</p>\n<p><i><NAME></i> for appellees.</p>\n<p>PER CURIAM.</p>\n<p>The motion to dismiss is granted and the appeal is dismissed for want of a substantial federal question.</p>\n</div>", "sha1": "8b3059118b099407c3731f67fbbd12d7824990fe", "date_modified": "2014-12-21T01:51:07.950080", "precedential_status": "Published", "absolute_url": "/opinion/105778/kovrak-v-ginsburg/", "citation_count": 6, "supreme_court_db_id": null, "extracted_by_ocr": false, "docket": "/api/rest/v2/docket/284900/", "html": "<p class=\"case_cite\">358 U.S. 52</p>\n <p class=\"case_cite\">79 S.Ct. 95</p>\n <p class=\"case_cite\">3 L.Ed.2d 46</p>\n <p class=\"parties\"><NAME>, appellant,<br>v.<br><NAME>, Chairman, <NAME>, <NAME>, III, etc.</p>\n <p class=\"docket\">No. 266.</p>\n <p class=\"court\">Supreme Court of the United States</p>\n <p class=\"date\">October 20, 1958</p>\n <div class=\"prelims\">\n <p class=\"indent\">Messrs. <NAME> and <NAME>, for appellant.</p>\n <p class=\"indent\">Mr. <NAME>, for appellees.</p>\n <p class=\"indent\">PER CURIAM.</p>\n </div>\n <div class=\"num\" id=\"p1\">\n <span class=\"num\">1</span>\n <p class=\"indent\">The motion to dismiss is granted and the appeal is dismissed for want of a substantial federal question.</p>\n </div>\n ", "resource_uri": "/api/rest/v2/document/105778/" }
json
<reponame>arjinmc/SmartCam<filename>core/src/main/java/com/arjinmc/smartcam/core/camera1/Camera1Preview.java package com.arjinmc.smartcam.core.camera1; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.Camera; import android.os.Handler; import android.os.Looper; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.arjinmc.smartcam.core.SmartCamConfig; import com.arjinmc.smartcam.core.SmartCamLog; import com.arjinmc.smartcam.core.SmartCamPreview; import com.arjinmc.smartcam.core.SmartCamUtils; import com.arjinmc.smartcam.core.callback.SmartCamOrientationEventListener; import com.arjinmc.smartcam.core.file.ImageSaver; import com.arjinmc.smartcam.core.model.CameraSize; import com.arjinmc.smartcam.core.model.CameraVersion; import com.arjinmc.smartcam.core.model.SmartCamCaptureError; import com.arjinmc.smartcam.core.model.SmartCamCaptureResult; import com.arjinmc.smartcam.core.model.SmartCamError; import com.arjinmc.smartcam.core.wrapper.AbsCameraWrapper; import com.arjinmc.smartcam.core.wrapper.ICameraPreviewWrapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Preview for camera v1 * Created by <NAME> on 2019-10-14. * email: <EMAIL> */ public class Camera1Preview extends SurfaceView implements SurfaceHolder.Callback, ICameraPreviewWrapper { private final String TAG = "Camera1Preview"; private SurfaceHolder mHolder; private Camera1Wrapper mCameraWrapper; private Camera mCamera; private AbsCameraWrapper.OnClickCaptureListener mOnClickCaptureListener; private SmartCamOrientationEventListener mOrientationEventListener; private SmartCamPreview.OnManualFocusListener mOnManualFocusListener; private SmartCamPreview.OnCaptureAnimationLister mOnCaptureAnimationListener; private SmartCamPreview.OnGestureToZoomListener mOnGestureToZoomListener; private int mCameraDegree; private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private Handler mHandler = new Handler(Looper.getMainLooper()); private CameraSize mPreviewSize; private float mLastGesturePointDistance; private boolean mIsTwoPointsMoving; public Camera1Preview(Context context, Camera1Wrapper camera1Wrapper) { super(context); mCameraWrapper = camera1Wrapper; if (SmartCamConfig.getInstance().isUseGestureToZoom()) { setClickable(true); } init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mOrientationEventListener = new SmartCamOrientationEventListener(getContext(), this); mOrientationEventListener.enable(); mOnClickCaptureListener = new AbsCameraWrapper.OnClickCaptureListener() { @Override public void onCapture() { if (mCamera == null) { return; } try { if (mOnCaptureAnimationListener != null) { mOnCaptureAnimationListener.onPlay(); } mCamera.takePicture(new Camera.ShutterCallback() { @Override public void onShutter() { } }, null, new Camera.PictureCallback() { @Override public void onPictureTaken(final byte[] data, Camera camera) { if (mCameraWrapper.getCaptureCallback() != null) { new ImageSaver(new SmartCamCaptureResult(data, CameraVersion.VERSION_1 //no need to return orientation because it has auto fix the right orientation , 0 , SmartCamUtils.isShouldReverse(mCameraWrapper.getCurrentCameraType()) , mPreviewSize.getHeight() , mPreviewSize.getWidth() , mCameraWrapper.getPreviewRatio()), mCameraWrapper.getCaptureCallback()).start(); } if (SmartCamConfig.getInstance().isAutoReset()) { doPreview(); } } }); } catch (Exception e) { e.printStackTrace(); if (mOnCaptureAnimationListener != null) { mOnCaptureAnimationListener.onStop(); } dispatchError(new SmartCamCaptureError()); } } }; mCameraWrapper.setOnClickCaptureListener(mOnClickCaptureListener); } @Override public void surfaceCreated(SurfaceHolder holder) { SmartCamLog.i(TAG, "surfaceCreated"); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { SmartCamLog.i(TAG, "surfaceChanged:" + width + "/" + height); doPreview(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { SmartCamLog.i(TAG, "surfaceDestroyed"); if (mHolder.getSurface() == null) { return; } try { if (mCamera != null) { mCameraWrapper.closeFlashMode(); mCamera.stopPreview(); getHolder().removeCallback(this); } } catch (Exception e) { // e.printStackTrace(); } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP && event.getPointerCount() == 1 && mOnManualFocusListener != null && SmartCamConfig.getInstance().isUseManualFocus() && !mIsTwoPointsMoving) { mOnManualFocusListener.requestFocus(event.getX(), event.getY()); Camera.Area cameraArea = new Camera.Area(mOnManualFocusListener.getFocusRegion(), 1000); List<Camera.Area> meteringAreas = new ArrayList<>(); List<Camera.Area> focusAreas = new ArrayList<>(); Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getMaxNumMeteringAreas() > 0) { meteringAreas.add(cameraArea); focusAreas.add(cameraArea); try { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); parameters.setFocusAreas(focusAreas); parameters.setMeteringAreas(meteringAreas); mCamera.cancelAutoFocus(); mCamera.setParameters(parameters); mCamera.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean b, Camera camera) { } }); } catch (Exception e) { // e.printStackTrace(); mOnManualFocusListener.cancelFocus(); } } } else if (event.getAction() == MotionEvent.ACTION_MOVE && event.getPointerCount() == 2 && SmartCamConfig.getInstance().isUseGestureToZoom()) { mIsTwoPointsMoving = true; float gesturePointDistance = SmartCamUtils.getPointsDistance(event.getX(0), event.getY(0) , event.getX(1), event.getY(1)); if (mLastGesturePointDistance != 0) { float changeDistance = mLastGesturePointDistance - gesturePointDistance; if (Math.abs(changeDistance) > SmartCamConfig.getInstance().getGestureMovingFactor()) { if (changeDistance > 0) { // zoom smaller dispatchGestureToZoomEvent(true, changeDistance); } else if (changeDistance < 0) { //zoom bigger dispatchGestureToZoomEvent(false, Math.abs(changeDistance)); } } } mLastGesturePointDistance = gesturePointDistance; if (mOnManualFocusListener != null) { mOnManualFocusListener.cancelFocus(); } } else if (event.getAction() == MotionEvent.ACTION_UP) { mIsTwoPointsMoving = false; } return super.onTouchEvent(event); } private void doPreview() { try { mCameraWrapper.resumeOpen(); mCamera = mCameraWrapper.getCamera(); if (mCamera != null) { mOrientation = SmartCamUtils.getWindowDisplayRotation(getContext()); SmartCamLog.i(TAG, "startPreview orientation:" + mOrientation); mCamera.setDisplayOrientation(SmartCamUtils.getShouldRotateDegree(getContext() , mCameraWrapper.getCurrentCameraType() , mCameraWrapper.getCurrentCameraId() , mOrientation)); if (mCameraWrapper.getPreviewRatio() == null) { mPreviewSize = mCameraWrapper.getCompatPreviewSize( getMeasuredHeight(), getMeasuredWidth()); } else { mPreviewSize = mCameraWrapper.getCompatPreviewSizeByRatio( mCameraWrapper.getPreviewRatio() , getMeasuredHeight(), getMeasuredWidth()); } if (mPreviewSize != null) { SmartCamLog.e(TAG, "final preview size:" + mPreviewSize.getWidth() + "/" + mPreviewSize.getHeight()); getHolder().setFixedSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } mCamera.setPreviewDisplay(getHolder()); Camera.Parameters parameters = mCamera.getParameters(); if (SmartCamUtils.hasAutoFocus(getContext())) { parameters = setAutoFocusMode(parameters, true); } parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); CameraSize outputSize = mCameraWrapper.getMaxOutputSize(); parameters.setPictureSize(outputSize.getWidth(), outputSize.getHeight()); parameters.setJpegQuality(SmartCamConfig.getInstance().getCaptureQuality()); parameters.setPictureFormat(ImageFormat.JPEG); parameters.setRotation(SmartCamUtils.getShouldRotateOrientationForCamera1(mCameraDegree, mCameraWrapper.getCurrentCameraType())); parameters = mCameraWrapper.resumeFlashMode(parameters); parameters = mCameraWrapper.resumeZoom(parameters); mCamera.setParameters(parameters); mCamera.startPreview(); } } catch (IOException e) { e.printStackTrace(); } } @Override public void onOrientationChange(int degree) { if (Math.abs(degree - mCameraDegree) > SmartCamConfig.getInstance().getDismissManualFocusDegreeOffset()) { if (mOnManualFocusListener != null) { mOnManualFocusListener.cancelFocus(); } } int oldCameraDegree = mCameraDegree; mCameraDegree = degree; if (mCamera == null) { return; } //if should rotate degree is the same,no need to change preview orientation if (SmartCamUtils.getShouldRotateOrientationForCamera1(oldCameraDegree, mCameraWrapper.getCurrentCameraType()) == SmartCamUtils.getShouldRotateOrientationForCamera1(mCameraDegree, mCameraWrapper.getCurrentCameraType())) { return; } //update capture orientation try { Camera.Parameters parameters = mCamera.getParameters(); parameters.setRotation(SmartCamUtils.getShouldRotateOrientationForCamera1( mCameraDegree, mCameraWrapper.getCurrentCameraType())); mCamera.setParameters(parameters); } catch (Exception e) { // e.printStackTrace(); } } @Override public void startPreview() { if (mCamera == null) { return; } doPreview(); } @Override public void stopPreview() { if (mCamera == null) { return; } mCamera.stopPreview(); } @Override public void destroy() { mOrientationEventListener.disable(); try { surfaceDestroyed(mHolder); } catch (Exception e) { e.printStackTrace(); } if (mOnGestureToZoomListener != null) { mOnGestureToZoomListener = null; } } @Override public void resumeAutoFocus() { if (mCamera == null) { return; } if (!SmartCamUtils.hasAutoFocus(getContext())) { return; } try { Camera.Parameters parameters = mCamera.getParameters(); parameters = setAutoFocusMode(parameters, true); mCamera.setParameters(parameters); } catch (Exception e) { } } /** * set focus mode * * @param parameter * @param autoFocus * @return */ private Camera.Parameters setAutoFocusMode(Camera.Parameters parameter, boolean autoFocus) { final List<String> modes = parameter.getSupportedFocusModes(); if (autoFocus && modes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameter.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } else if (modes.contains(Camera.Parameters.FOCUS_MODE_FIXED)) { parameter.setFocusMode(Camera.Parameters.FOCUS_MODE_FIXED); } else if (modes.contains(Camera.Parameters.FOCUS_MODE_INFINITY)) { parameter.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY); } else { parameter.setFocusMode(modes.get(0)); } return parameter; } @Override public void setOnManualFocusListener(SmartCamPreview.OnManualFocusListener onManualFocusListener) { mOnManualFocusListener = onManualFocusListener; } @Override public void setOnCaptureAnimationListener(SmartCamPreview.OnCaptureAnimationLister onCaptureAnimationListener) { mOnCaptureAnimationListener = onCaptureAnimationListener; } @Override public void setOnGestureToZoomListener(SmartCamPreview.OnGestureToZoomListener onGestureToZoomListener) { mOnGestureToZoomListener = onGestureToZoomListener; } private void dispatchError(SmartCamError smartCamError) { if (mCameraWrapper == null || mCameraWrapper.getCaptureCallback() == null) { return; } mCameraWrapper.getCaptureCallback().onError(smartCamError); } /** * dispatch to ui * * @param isSmaller * @param changeDistance */ private void dispatchGestureToZoomEvent(boolean isSmaller, float changeDistance) { if (mOnGestureToZoomListener != null) { if (isSmaller) { mOnGestureToZoomListener.onZoomToSmaller(changeDistance); } else { mOnGestureToZoomListener.onZoomToBigger(changeDistance); } } } }
java
ULAANBAATAR: Tokyo Olympian Deepak Punia settled for a silver medal in the men's freestyle 86 kg while Viky bagged a bronze in the 92 kg category on the last day of the 2022 Asian Wrestling Championships, here on Sunday. With the two medals on the final day of the meet, India finished with a total tally of 17 medals -- one gold, five silver and 11 bronze at Ulaanbaatar. Tokyo medallist Ravi Kumar Dahiya won the solitary gold in the men's 57kg weight class. Though the count surpassed last year's haul of 14, India did win more gold medals, five, at the 2021 edition held at Almaty. Deepak Punia, a former world championships silver medallist, began his campaign with a 6-0 win over Iranian grappler Mohsen Miryousef Mostafavi Alanjagh before ousting South Korean Olympian Kim Gwanuk, a bronze medallist at the Asian Games 2014, 5-0 in the semi-finals. Up against Kazakhstan's Azamat Dauletbekov in the gold medal match though, the Indian grappler came out on the wrong end of a 6-1 scoreline and had to settle for a silver medal at the Asian meet for the second consecutive year. In the 92kg competition, India's Viky edged Mirlan Chynybekov of Kyrgyzstan 4-3 in the quarter-finals but was defeated by Mongolia's Orgilokh Dagvadorj by technical superiority in the semis. A 5-3 win over Uzbek grappler Ajiniyaz Saparniyazov in the bronze medal match handed Viky a podium finish. Another Indian wrestler Mangal Kadyan also managed to make it to the bronze medal match of the 61kg event through repechage but was denied a spot on the podium by 2020 champion Ulukbek Zholdoshbekov of Kyrgyzstan, who won the medal bout 6-4.
english
<gh_stars>1-10 #!/usr/bin/env node const { spawn } = require("child_process"); const inquirer = require("inquirer"); const ProgressBar = require("progress"); const chalk = require("chalk"); const { log } = console; const { calcWithTotal, calcWithTemp } = require("../lib/util/time"); let resultFileName = ""; const questions = [ { type: "input", name: "sourceUrl", message: "请输入要处理视频的地址:", validate: function(input) { if (!input) { return "处理视频的地址不能为空"; } return true; } }, { type: "confirm", name: "isNeedCut", message: "是否需要截取视频?" }, { type: "input", name: "startTime", message: "开始时间:", when: function(answers) { return answers.isNeedCut; }, default: "00:00:00", validate: function(input) { if (!input) { return "开始时间不能为空"; } if (!/\d{2}:\d{2}:\d{2}/.test(input)) { return "请输入正确格式 !例如 00:00:00"; } return true; } }, { type: "input", name: "endTime", message: "结束时间:", when: function(answers) { return answers.isNeedCut; }, validate: function(input) { if (!input) { return "结束时间不能为空"; } if (!/\d{2}:\d{2}:\d{2}/.test(input)) { return "请输入正确格式 !例如 00:00:00"; } return true; } }, { type: "input", name: "resultName", message: "输出结果视频的名称:", default: function() { const now = new Date().getTime(); resultFileName = `${now}.mp4`; return resultFileName; } } ]; (async function() { const { sourceUrl, isNeedCut, startTime, endTime, resultName } = await inquirer.prompt(questions); let args = ["-i", sourceUrl]; if (isNeedCut) { startTime && args.push("-ss", startTime); endTime && args.push("-to", endTime); } args.push(resultName); ffmpegSpawn(args, [startTime, endTime]); })(); /** * 获取最新answer的结果 * @param {string} k question 的key */ const getAnswer = function(k) { return function(answers) { return answers[k]; }; }; /** * ffmpeg 执行命令的封装 * @param {Array} args ffmpeg 要执行的参数 * @param {Array} param1 [视频开始时间,视频截取时间] */ const ffmpegSpawn = function(args, [startTime, endTime]) { if (args.length == 0) throw new Error("ffmpegSpawn 缺少参数"); log(chalk`commond run: {rgb(255,131,0) ffmpeg ${args.join(" ")}}`); const bar = new ProgressBar(":bar :percent", { total: 50, complete: chalk.green("█"), incomplete: " " }); let total = endTime; //等于视频时间长度 let current = ""; const ls = spawn("ffmpeg", args, { cwd: process.cwd() // stdio: "inherit" }); ls.stderr.on("data", data => { const d = data.toString(); if (!endTime && /Duration: (\d{2}:\d{2}:\d{2})/.test(d)) { total = d.match(/Duration: (\d{2}:\d{2}:\d{2})/)[1]; } if (/time=(\d{2}:\d{2}:\d{2})/.test(d)) { current = d.match(/time=(\d{2}:\d{2}:\d{2})/)[1]; !endTime ? bar.update(calcWithTotal(current, total) / 100) : bar.update(calcWithTemp(current, total, startTime) / 100); } }); ls.on("close", code => { if (!bar.complete) { //如果结束进度条未完成直接结束 bar.update(1); } log(chalk.green(`🎉 ${resultFileName}转换结束 !!`)); }); return; };
javascript
There are some New York Fashion Week trends that I would need help from the glam gods themselves to re-create (hello, "angel eyes" makeup). However, others are so easy, even I can do them with simple products I have at home. When I saw beauty creator Cat Quinn's video about the "siren skin" trend, I knew I needed to try it immediately. The look was spotted at The Blonds's spring/summer 2024 show, and it was created using two products from MAC Cosmetics: MAC Glitter ($17, originally $23) in the shade Reflects Transparent Pink and MAC Strobe Cream ($36) in Peachlite. When I saw the extraterrestrial-like glimmer on Quinn's body, I couldn't get my hands on the products fast enough. I didn't have the exact shades on hand, but I already owned the Strobe Cream in Goldlite and the Glitter in Iridescent Sage. I figured the combination would give me a mermaidcore-themed look, which I was all about. The process was very simple: combine the Strobe Cream and Glitter before adding the mixture wherever you want. I did just that and ended up with a gorgeous, green-tinted lotion. On first application, I was a little surprised by how gritty the texture was, which made me immediately wonder if it was my embarrassingly old bottle of Strobe Cream that was the culprit. However, after adjusting the glitter-to-cream ratio - you'll want about a squeeze and a half of the cream to about half a makeup-spatula tip of glitter- I was good to go. The result was a gorgeous, glittery sheen on my chest that I immediately knew would be perfect for concerts, festivals, or even just a good old selfie on Instagram. I did notice that some of the glitter transferred onto my clothes, which I didn't mind personally, but it's worth noting if this is a trend you want to try - especially for special occasions like weddings or graduations. All in all, this is a really fun and wearable Fashion Week trend that can add a bit of glamour to your daily getting-ready routine. I likely will only be doing it again when I get a fresh bottle of Strobe Cream (mine really is so old that I'm embarrassed to be talking about it in public), but you can likely mix your glitter into any body lotion for a similar effect.
english
#include "stdafx.h" #include "ItemRenderingSystem.h" #include "GameObject.h" ItemRenderingSystem::ItemRenderingSystem( GameObject& parent, std::string spritePath, std::unique_ptr<IEffect> deadEffect, std::unique_ptr<IEffect> hitEffect) : parent{ parent } { this->spritePath = spritePath; this->deadEffect = std::move(deadEffect); this->hitEffect = std::move(hitEffect); } ItemRenderingSystem::ItemRenderingSystem( GameObject& parent, TextureRegion textureRegion, std::unique_ptr<IEffect> deadEffect, std::unique_ptr<IEffect> hitEffect) : parent{ parent } { this->sprite = std::make_unique<Sprite>(textureRegion); this->deadEffect = std::move(deadEffect); this->hitEffect = std::move(hitEffect); } Sprite& ItemRenderingSystem::GetSprite() { return *sprite; } GameObject& ItemRenderingSystem::GetParent() { return parent; } void ItemRenderingSystem::LoadContent(ContentManager& content) { RenderingSystem::LoadContent(content); if (sprite != nullptr) return; auto texture = content.Load<Texture>(spritePath); sprite = std::make_unique<Sprite>(texture); } void ItemRenderingSystem::Update(GameTime gameTime) { if (GetParent().GetState() == ObjectState::DYING) { deadEffect->Update(gameTime); if (deadEffect->IsFinished()) GetParent().Destroy(); } if (hitEffect != nullptr) hitEffect->Update(gameTime); } void ItemRenderingSystem::Draw(SpriteExtensions& spriteBatch) { switch (GetParent().GetState()) { case ObjectState::NORMAL: spriteBatch.Draw(*sprite, GetParent().GetPosition()); RenderingSystem::Draw(spriteBatch); break; case ObjectState::DYING: deadEffect->Draw(spriteBatch); break; } if (hitEffect != nullptr) hitEffect->Draw(spriteBatch); } void ItemRenderingSystem::OnStateChanged() { if (GetParent().GetState() == ObjectState::DYING) { if (deadEffect != nullptr) deadEffect->Show(GetParent().GetOriginPosition()); else GetParent().Destroy(); } } void ItemRenderingSystem::OnTakingDamage() { if (hitEffect != nullptr) hitEffect->Show(GetParent().GetOriginPosition()); }
cpp
{ "title": "Exploring The Universe With IUE 1978-1996", "credit": "<NAME> and <NAME> (GSFC), NASA", "explanation": "", "date": "1996-09-30", "hdurl": "https://apod.nasa.gov/apod/image/iue_allsky.gif", "service_version": "v1", "media_type": "image", "url": "https://apod.nasa.gov/apod/image/iue_allsky.gif" }
json
<reponame>zbigos/multi_project_tools<gh_stars>0 #!/usr/bin/env python3 import logging, sys, argparse from collect import Collection if __name__ == '__main__': parser = argparse.ArgumentParser(description="test a project repo") parser.add_argument('--force-delete', help='instead of aborting on existing files, delete them', action='store_const', const=True) subparsers = parser.add_subparsers(help='help for subcommand', dest="command") parser.add_argument('--config', help="the config file listing all project directories", default='projects.yaml') parser.add_argument('--local-config', help="the local environment config file", default='local.yaml') parser.add_argument('--project', help="just run for a single project, supply project ID", type=int) parser.add_argument('--test-module', help="run the module's test", action='store_const', const=True) parser.add_argument('--prove-wrapper', help="check the wrapper proof", action='store_const', const=True) parser.add_argument('--test-caravel', help="check the caravel test", action='store_const', const=True) parser.add_argument('--test-gds', help="check the gds", action='store_const', const=True) parser.add_argument('--test-lvs', help="check the gds against powered verilog", action='store_const', const=True) parser.add_argument('--test-tristate-z', help="check outputs are z when not active", action='store_const', const=True) parser.add_argument('--test-ports', help="check ports defined in yaml match the verilog", action='store_const', const=True) parser.add_argument('--test-git', help="check gitsha on disk matches the config", action='store_const', const=True) parser.add_argument('--test-all', help="run all the checks for each project", action='store_const', const=True) parser.add_argument('--test-from', help="run all the checks for all projects with id equal or more than the given id", type=int) parser.add_argument('--openram', help="use OpenRAM - instantiate the bridge, wrapper and do the wiring", action='store_const', const=True) parser.add_argument('--clone-shared-repos', help="clone shared repos defined in projects.yaml", action='store_const', const=True) parser.add_argument('--clone-repos', help="git clone the repo", action='store_const', const=True) parser.add_argument('--create-openlane-config', help="create the OpenLane & caravel_user_project config", action='store_const', const=True) parser.add_argument('--gate-level', help="create the caravel includes file with gate level includes", action='store_const', const=True) parser.add_argument('--copy-project', help="copy project's RTL and tests to correct locations in caravel_user_project", action='store_const', const=True) parser.add_argument('--copy-gds', help="copy the projects GDS and LEF files", action='store_const', const=True) parser.add_argument('--generate-doc', help="generate a index.md file with information about each project", action='store_const', const=True) parser.add_argument('--dump-hash', help="print current commit hash of each project along with author and title", action='store_const', const=True) parser.add_argument('--fill', help="for testing, repeat the given projects this number of times", type=int) parser.add_argument('--annotate-image', help="annotate the multi_macro.png image generated by klayout", action='store_const', const=True) parser.add_argument('--dump-macro-position', help="use the macro.cfg + gds to create a list of positions and sizes", action='store_const', const=True) parser.add_argument('--layout-tool', help="run the manual layout tool on current designs", action='store_const', const=True) parser.add_argument('--layout-tool-downscale', help="scale factor for layout tool", type=int) args = parser.parse_args() # setup log log_format = logging.Formatter('%(asctime)s - %(module)-15s - %(levelname)-8s - %(message)s') # configure the client logging log = logging.getLogger('') # has to be set to debug as is the root logger log.setLevel(logging.INFO) # create console handler and set level to info ch = logging.StreamHandler(sys.stdout) # create formatter for console ch.setFormatter(log_format) log.addHandler(ch) collection = Collection(args) # run any tests specified by arguments collection.run_tests() if args.layout_tool: collection.launch_layout_tool(args.layout_tool_downscale) # create all the OpenLane config for the user collection wrapper if args.create_openlane_config: collection.create_openlane_config() # copy gds to correct place if args.copy_gds: collection.copy_all_gds() if args.copy_project: collection.copy_all_project_files_to_caravel() # generate doc if args.generate_doc: collection.generate_docs() # image if args.annotate_image: collection.annotate_image() # dump macro pos - wip for assisted macro placement if args.dump_macro_position: collection.get_macro_pos()
python
Welcome to the Cricket World weekly trivia, in which we feature 10 cricket related questions to test your knowledge against the rest of the world. Linking in with our Daily Quiz on @Cricket_World, we will be giving you a bit longer to answer the trivia questions below, and weekly winners will be chosen to win a £10 Amazon voucher. So leave your details below, answer the 10 questions to the best of your ability and check back in daily on our Twitter account, and here everyday Friday for a new quiz and winners announced. This weeks competition will close on 23rd October, at which time a new one will open up. Best of luck!
english
<gh_stars>10-100 package com.taotao.cloud.member.biz.service.impl; import cn.hutool.core.util.PageUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.taotao.cloud.member.api.dto.EvaluationQueryParams; import com.taotao.cloud.member.api.dto.MemberEvaluationDTO; import com.taotao.cloud.member.api.enums.EvaluationGradeEnum; import com.taotao.cloud.member.api.vo.EvaluationNumberVO; import com.taotao.cloud.member.api.vo.MemberEvaluationListVO; import com.taotao.cloud.member.api.vo.MemberEvaluationVO; import com.taotao.cloud.member.biz.entity.Member; import com.taotao.cloud.member.biz.entity.MemberEvaluation; import com.taotao.cloud.member.biz.mapper.MemberEvaluationMapper; import com.taotao.cloud.member.biz.service.MemberEvaluationService; import com.taotao.cloud.member.biz.service.MemberService; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * 会员商品评价业务层实现 * * * @since 2020-02-25 14:10:16 */ @Service @Transactional(rollbackFor = Exception.class) public class MemberEvaluationServiceImpl extends ServiceImpl<MemberEvaluationMapper, MemberEvaluation> implements MemberEvaluationService { /** * 会员评价数据层 */ @Resource private MemberEvaluationMapper memberEvaluationMapper; /** * 订单 */ @Autowired private OrderService orderService; /** * 子订单 */ @Autowired private OrderItemService orderItemService; /** * 会员 */ @Autowired private MemberService memberService; /** * 商品 */ @Autowired private GoodsSkuService goodsSkuService; /** * rocketMq */ @Autowired private RocketMQTemplate rocketMQTemplate; /** * rocketMq配置 */ @Autowired private RocketmqCustomProperties rocketmqCustomProperties; @Override public IPage<MemberEvaluation> managerQuery(EvaluationQueryParams queryParams) { //获取评价分页 return this.page(PageUtil.initPage(queryParams), queryParams.queryWrapper()); } @Override public IPage<MemberEvaluationListVO> queryPage(EvaluationQueryParams evaluationQueryParams) { return memberEvaluationMapper.getMemberEvaluationList(PageUtil.initPage(evaluationQueryParams), evaluationQueryParams.queryWrapper()); } @Override public MemberEvaluationDTO addMemberEvaluation(MemberEvaluationDTO memberEvaluationDTO) { //获取子订单信息 OrderItem orderItem = orderItemService.getBySn(memberEvaluationDTO.getOrderItemSn()); //获取订单信息 Order order = orderService.getBySn(orderItem.getOrderSn()); //检测是否可以添加会员评价 checkMemberEvaluation(orderItem, order); //获取用户信息 Member member = memberService.getUserInfo(); //获取商品信息 GoodsSku goodsSku = goodsSkuService.getGoodsSkuByIdFromCache(memberEvaluationDTO.getSkuId()); //新增用户评价 MemberEvaluation memberEvaluation = new MemberEvaluation(memberEvaluationDTO, goodsSku, member, order); //过滤商品咨询敏感词 memberEvaluation.setContent(SensitiveWordsFilter.filter(memberEvaluation.getContent())); //添加评价 this.save(memberEvaluation); //修改订单货物评价状态为已评价 orderItemService.updateCommentStatus(orderItem.getSn(), CommentStatusEnum.FINISHED); //发送商品评价消息 String destination = rocketmqCustomProperties.getGoodsTopic() + ":" + GoodsTagsEnum.GOODS_COMMENT_COMPLETE.name(); rocketMQTemplate.asyncSend(destination, JSONUtil.toJsonStr(memberEvaluation), RocketmqSendCallbackBuilder.commonCallback()); return memberEvaluationDTO; } @Override public MemberEvaluationVO queryById(String id) { return new MemberEvaluationVO(this.getById(id)); } @Override public boolean updateStatus(String id, String status) { UpdateWrapper updateWrapper = Wrappers.update(); updateWrapper.eq("id", id); updateWrapper.set("status", status.equals(SwitchEnum.OPEN.name()) ? SwitchEnum.OPEN.name() : SwitchEnum.CLOSE.name()); return this.update(updateWrapper); } @Override public boolean delete(String id) { LambdaUpdateWrapper<MemberEvaluation> updateWrapper = Wrappers.lambdaUpdate(); updateWrapper.set(MemberEvaluation::getDeleteFlag, true); updateWrapper.eq(MemberEvaluation::getId, id); return this.update(updateWrapper); } @Override public boolean reply(String id, String reply, String replyImage) { UpdateWrapper<MemberEvaluation> updateWrapper = Wrappers.update(); updateWrapper.set("reply_status", true); updateWrapper.set("reply", reply); if (StringUtils.isNotEmpty(replyImage)) { updateWrapper.set("have_reply_image", true); updateWrapper.set("reply_image", replyImage); } updateWrapper.eq("id", id); return this.update(updateWrapper); } @Override public EvaluationNumberVO getEvaluationNumber(String goodsId) { EvaluationNumberVO evaluationNumberVO = new EvaluationNumberVO(); List<Map<String, Object>> list = this.baseMapper.getEvaluationNumber(goodsId); Integer good = 0; Integer moderate = 0; Integer worse = 0; for (Map<String, Object> map : list) { if (map.get("grade").equals(EvaluationGradeEnum.GOOD.name())) { good = Integer.valueOf(map.get("num").toString()); } else if (map.get("grade").equals(EvaluationGradeEnum.MODERATE.name())) { moderate = Integer.valueOf(map.get("num").toString()); } else if (map.get("grade").equals(EvaluationGradeEnum.WORSE.name())) { worse = Integer.valueOf(map.get("num").toString()); } } evaluationNumberVO.setAll(good + moderate + worse); evaluationNumberVO.setGood(good); evaluationNumberVO.setModerate(moderate); evaluationNumberVO.setWorse(worse); evaluationNumberVO.setHaveImage(this.count(new QueryWrapper<MemberEvaluation>() .eq("have_image", 1) .eq("goods_id", goodsId))); return evaluationNumberVO; } /** * 检测会员评价 * * @param orderItem 子订单 * @param order 订单 */ public void checkMemberEvaluation(OrderItem orderItem, Order order) { //根据子订单编号判断是否评价过 if (orderItem.getCommentStatus().equals(CommentStatusEnum.FINISHED.name())) { throw new ServiceException(ResultCode.EVALUATION_DOUBLE_ERROR); } //判断是否是当前会员的订单 if (!order.getMemberId().equals(UserContext.getCurrentUser().getId())) { throw new ServiceException(ResultCode.ORDER_NOT_USER); } } }
java
/* My own edits on top of the Hyde style sheets. */ html { font-family: utopia-std, "Times New Roman", serif; font-weight: 400; font-style: normal; font-variant-ligatures: common-ligatures; } .sidebar-about h1 { font-family: utopia-std-headline, serif; font-weight: 400; font-style: normal; } body { font-size: 0.8rem; counter-reset: htwo hthree hfour hfive hsix; } /* Legal notice */ footer { font-size: 0.5rem; } /* Chrome displays address in italic */ address { font-style: normal; } /* Bibliography display */ .bibliography { padding-left: 0em; font-size: 0.8rem; padding: 0em; margin: 0em; } /* Hiding a bug from Jekyll * Jekyll is processing {%include%}ed files as if they contain Markdown * inbetween their HTML tags. This results in <p> elements on undesired * positions. This will remove their effects :) */ .bibliography p { display: inline; } .bibliography pre { display: none; } .bibliography pre:target { padding-top: 0rem; padding-bottom: 0rem; display: block; } .bibliography li { padding-left: 0em; list-style-type: none; text-indent: 1em; } .bibliography li:target { color: #717171; background-color: #eeeeee; } .post { margin: 0; padding: 0; } /* In-article styles */ /*article.post > p:first-of-type,*/ article { counter-reset: figures; } figure { counter-increment: figures; } figure figcaption:before { font-style: normal; font-weight: bold; content: 'Figure ' counter(figures) '.'; } figure, #intro { color: #717171; background-color: #eeeeee; font-style: italic; padding: 0.5rem; } #intro { margin-bottom: 1rem; } figure figcaption, figure figcaption small { font-size: 0.8rem; } figure img { display: block; margin-left: auto; margin-right: auto; max-width: 100%; } .post-snippet header { display: block; float:left; font-size: 0.8rem; color: #717171; margin-right: 1rem; } .post header { display: block; font-size: 0.8rem; color: #717171; text-align: right; } .post-snippet header > .post-title { display: inline-block; margin: 0; font-size: medium; } header > .metadata { font-size: smaller; font-style: italic; } ul.categories { /*font-size: 0.8rem;*/ padding: 0rem; display: inline; } time.published + ul.categories:before { content: " · "; } ul.categories li { display: inline; } ul.categories li:after { content: ", "; } ul.categories li:last-of-type:after { content: ""; } hr { margin: 0; padding: 0; } code { color: #717171; } .MathJax, .MathJax * { color: #717171; } ul#markdown-toc, ul#markdown-toc ul { counter-reset: toc_counter; list-style-type: none; padding-bottom: 0px; margin-bottom: 0px; } ul#markdown-toc li:before, ul#markdown-toc ul li:before { counter-increment: toc_counter; content: counters(toc_counter,".") ". "; } .post h2 { counter-reset: hthree hfour hfive hsix; } .post h3 { counter-reset: hfour hfive hsix; } .post h4 { counter-reset: hfive hsix; } .post h5 { counter-reset: hsix; } .post h2:before { counter-increment: htwo; content: counter(htwo) ". "; } .post h3:before { counter-increment: hthree; content: counter(htwo) "." counter(hthree) ". "; } .post h4:before { counter-increment: hfour; content: counter(htwo) "." counter(hthree) "." counter(hfour) ". "; } .post h5:before { counter-increment: hfive; content: counter(htwo) "." counter(hthree) "." counter(hfour) "." counter(hfive) ". "; } .post h6:before { counter-increment: hsix; content: counter(htwo) "." counter(hthree) "." counter(hfour) "." counter(hfive) "." counter(hsix) ". "; } .post .no_toc:before { counter-increment: none; content: ""; } section.category > span { display: none; } section.category:target > span { display: block; } /** Themes **/ /* UvA color scheme */ .theme-uva .sidebar { background-color: #BC0031; } .theme-uva .content a, .theme-uva .related-posts li a:hover { color: #BC0031; } /* UvA-FNWI color scheme */ .theme-uva-fnwi .sidebar { background-color: #751b68; } .theme-uva-fnwi .content a, .theme-uva-fnwi .related-posts li a:hover { color: #751b68; }
css
<filename>src/main/java/com/mo9/risk/util/MsfClient.java package com.mo9.risk.util; /** * Project Name : msf * File Name : MsfClient.java * Package Name : com.mo9.msf.core.client * Create Date : 2015-6-8下午12:10:22 * * Copyright ©2011 moKredit Inc. All Rights Reserved */ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.gamaxpay.commonutil.msf.BaseResponse; import com.gamaxpay.commonutil.msf.JacksonConvertor; import com.gamaxpay.commonutil.web.PostRequest; import com.thinkgem.jeesite.modules.sys.utils.DictUtils; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Map; /** * <p>Msf客户端程序</p> * * <p>DESC</p> * ******************************************************** * Date Author Changes * 2015-6-8 <NAME> 创建 ******************************************************** */ public class MsfClient { /**MSF默认客户端访问账户名.*/ private static final String DEFAULT_ACCT="S_soaDefClient"; /**MSF默认客户端访问密码.*/ private static final String DEFAULT_PASSWD="<PASSWORD>"; public static final String SOA_PATH_CONFIG="soa.path"; public static final String VALID_TYPE_SECRET="secret"; /**本类唯一实体*/ private static final MsfClient INSTANCE=new MsfClient(); /**是否已经初始化*/ private static boolean inited; /**当前主机地址,含协议及端口号:例如"http://localhost/"*/ private static String currHost ; private Logger logger = Logger.getLogger(MsfClient.class); /** * 获取本类唯一实例对象. * * @return */ public static MsfClient instance() { if(!inited) { inited=true; // currHost = Mo9DataSourceProperty.getProperty(SOA_PATH_CONFIG); // currHost = "https://www.mo9.com"; currHost=DictUtils.getDictValue("短信链接", "sms_url", "https://new.mo9.com"); //currHost = "http://127.0.0.1"; // currHost = "https://new.mo9.com"; } return INSTANCE; } /** * * 客户端发送HTTP请求. * * @param url 请求的业务URI * @param params 请求参数 * @param responseType 应答对象类型. * @return */ public <T extends BaseResponse> T request(String url ,Map<String,String> params, Class<? extends BaseResponse> responseType) { //Step2:通过HTTP协议,发送消息请求. String respText = ""; try { System.out.println("MsfClient post url :"+url); respText = PostRequest.postRequest(url, params); System.out.println(respText); } catch (IOException e) { logger.warn("网络交互失败",e); return (T) BaseResponse.buildErrorResponse("网络交互失败.", e); } //Step3,解析对象并返回. return (T)(new JacksonConvertor().parse(respText, responseType)); } public BaseResponse requestForBodyType(String url ,Map<String,String> params, Class<? extends Object> bodyType) { //Step2:通过HTTP协议,发送消息请求. String respText = ""; try { respText = PostRequest.postRequest(url, params); // System.out.println(respText); } catch (IOException e) { logger.warn("网络交互失败",e); return BaseResponse.buildErrorResponse("网络交互失败.", e); } //Step3,解析对象并返回. JSONObject jsonObj = JSON.parseObject(respText); JSONObject headerJsonObject = jsonObj.getJSONObject("header"); JSONObject bodyJsonObject = jsonObj.getJSONObject("body"); BaseResponse.Header header = JSON.toJavaObject(headerJsonObject, BaseResponse.Header.class); Object body = JSON.toJavaObject(bodyJsonObject, bodyType); return BaseResponse.buildResponse(header,body); } /** * 使用默认服务器账号发送支付请求. * 该方法将自动为用户填充请求的client_id,valid_type,valid_token三个参数. * @param url * @param params * @param responseType * @return */ public <T extends BaseResponse> T requestByDefAcct(String url ,Map<String,String> params, Class<? extends BaseResponse> responseType) { params.put("client_id", DEFAULT_ACCT); params.put("valid_type", VALID_TYPE_SECRET); params.put("valid_token", <PASSWORD>); return request(url,params,responseType); } /** * 使用默认服务器账号发送支付请求. * 该方法将自动为用户填充请求的client_id,valid_type,valid_token三个参数. * @param url * @param params * @param responseType * @return */ public <T extends BaseResponse> T requestFromServer(String path ,Map<String,String> params, Class<? extends BaseResponse> responseType) { params.put("client_id", DEFAULT_ACCT); params.put("valid_type", VALID_TYPE_SECRET); params.put("valid_token", <PASSWORD>); return request(currHost+path,params,responseType); } public BaseResponse requestFromServerForBodyType(String path ,Map<String,String> params, Class<? extends Object> bodyType) { params.put("client_id", DEFAULT_ACCT); params.put("valid_type", VALID_TYPE_SECRET); params.put("valid_token", <PASSWORD>); return requestForBodyType(currHost+path,params,bodyType); } }
java
Former WWE Superstar Kelly Kelly has opened up about what she misses about pro wrestling. Real name Barbie Blank made her televised debut as part of the ECW brand in 2006. She has shared the ring with many notable female wrestlers during her career, including Mickie James, Beth Phoenix, and Maryse. In September 2012, Blank was released from her WWE contract. She returned to the company in 2017 and made her WWE in-ring return in the 2018 Women's Royal Rumble match. Speaking on the Grown Ass Women podcast, Kelly stated that she misses performing for the fans and spending time with her friends when asked what she misses about wrestling. “What do I miss? All the girls, the friendships, traveling with your friends and renting the cars, doing the travel... I loved the comraderie, the family aspect, and I got to see the world at 19 years old, like how many people can say that? ...I love performing for the fans and I loved going out there every night and putting on a show. It’s just the best feeling in the world. People [ask me] to describe it and I can’t. When you walk through that curtain, it’s literally unlike anything you will ever feel in your life,” Kelly Kelly said. (H/T WrestleZone) The WWE veteran is a former Divas Champion, and she has also held the retired 24/7 Championship. She made history by becoming the first woman to hold the 24/7 Title. When asked what she doesn't miss about the wrestling business, Kelly Kelly stated that she doesn't miss taking bumps. The 36-year-old star competed in her last match last year as an entrant in the 2022 Women's Royal Rumble match, which Ronda Rousey won. Would you like to see Kelly Kelly have another match in WWE? Sound off in the comments below!
english
Shares of Titan Company hit a record high of Rs 2,718. 65, on rallying 5 per cent on the BSE in Thursday’s intra-day trade on expectations of strong earnings growth. The stock of the Tata Group Company engaged in jewellery and watch business has surpassed its previous high of Rs 2,687. 30 touched on January 7, 2022. Titan Company is among the top players in ace investor Rakesh Jhunjhunwala & his family’s portfolio with holding value of over Rs 12,000 crore. As on December 31, 2021, Rakesh Jhunjhunwala (4. 02 per cent) and his wife Rekha Rakesh Jhunjhunwala (1. 07 per cent) collectively held 5. 09 per cent stake in Titan Company, the shareholding pattern data shows. On the basis of current market capitalisation of Rs 2. 39 trillion, Rakesh Jhunjhunwala and his family hold shares worth Rs 12,187 crore in the company. TO READ THE FULL STORY, SUBSCRIBE NOW NOW AT JUST RS 249 A MONTH. What you get on Business Standard Premium? - Unlock 30+ premium stories daily hand-picked by our editors, across devices on browser and app. - Pick your 5 favourite companies, get a daily email with all news updates on them. - Full access to our intuitive epaper - clip, save, share articles from any device; newspaper archives from 2006. - Preferential invites to Business Standard events. - Curated newsletters on markets, personal finance, policy & politics, start-ups, technology, and more.
english
from .cifar import Cifar10DataProvider, Cifar100DataProvider, \ Cifar10AugmentedDataProvider, Cifar100AugmentedDataProvider from .svhn import SVHNDataProvider def get_data_provider_by_name(name, train_params): """Return required data provider class""" if name == 'C10': return Cifar10DataProvider(**train_params) if name == 'C10+': return Cifar10AugmentedDataProvider(**train_params) if name == 'C100': return Cifar100DataProvider(**train_params) if name == 'C100+': return Cifar100AugmentedDataProvider(**train_params) if name == 'SVHN': return SVHNDataProvider(**train_params) else: print("Sorry, data provider for `%s` dataset " "was not implemented yet" % name) exit()
python
<reponame>elanthia-online/cartograph<filename>maps/gsiv/rooms/27634.json<gh_stars>1-10 { "id": 27634, "title": [ "[Annex, Silvergate Inn Lobby]" ], "description": [ "Simple, but elegant, the teakwood flooring of this room is polished to a lustrous sheen. A silver velvet pennant edged with green hangs near a heavy, white muslin curtain." ], "paths": [ "Obvious exits: none" ], "location": "Mist Harbor", "wayto": { "25998": "go curtain", "12296": { "file": "string_procs/wayto/27634_12296.rb" } }, "timeto": { "25998": 0.2, "12296": 0.2 } }
json
Coal imports in India increased by 11.7% to 20.95 Million Tonnes (MT) in November compared to the same period last year, according to data from B2B e-commerce company mjunction services. However, overall coal imports for the April-November period of the current financial year decreased to 169.08 MT from 173.47 MT in the previous year. The reduction in coal imports can be attributed to sufficient domestic supply and a slowdown in demand after the festive season in October, explained Vinaya Varma, MD and CEO of mjunction. Congress leader Vijay Bhike filed a police complaint at Mapusa on Friday night against the organisers of Sunburn, meanwhile, AAP Goa chief Amit Palekar said the state government should take action against them for hurting "Sanatan Dharma". Sunburn EDM, a popular electronic dance music festival, started on December 28 at Vagator in North Goa and will wind up on Saturday, December 30. Retail sales in October and November 2023 grew by only 7% compared to the same period in 2022, despite the festive season, according to a survey by the Retailers Association of India (RAI). Many retailers faced muted footfalls, and sales were similar to the previous year. The growth varied across regions, with East India signaling an 11% growth, South India 7%, North India 6%, and West India 5%. The annual growth rate in wholesale despatches from factories to dealerships moderated to 3.7% compared with 15.9% growth in October, in absolute numbers, it hit a new high for November at 334,130 units, according to Society of Indian Automobile Manufacturers (Siam). Total consumption in November, a proxy for oil demand, fell by 2.8% to 18.72 million tonnes from 19.26 million tonnes in October, the data from the Indian oil ministry's Petroleum Planning and Analysis Cell (PPAC) showed. It was down about 2% compared with the same period a year earlier. "Consumption increased in October due to agricultural demand and as people traveled during the festive season. November is seeing a dip as people reverted to normal activity," said Prashant Vasisht, vice president and co-head, corporate ratings at ICRA. According to industry estimates, about 335,354 cars, sedans and utility vehicles were dispatched from factories to dealerships last month, an increase of 3.9% over 322,600 units sold in the same period last year. Industry numbers were supported by market leaders Maruti Suzuki and Hyundai Motor India which reported a growth of 1.3% (134,158 units) and 3.1% (49,451 units), respectively last month. "Contrary to expectations, Diwali witnessed subdued enthusiasm for the FMCG sector. Post-Diwali sales have historically been low. Particularly hard-hit segments are chocolates, confectionery and biscuits, followed by beauty, and cosmetics," said Dhairyashil Patil, national president of All India Consumer Products Distributors Federation (AICPDF). Fueled by robust demand, India's automotive retail sales hit a record during the festive season, with overall sales surging 19% YoY. Passenger vehicle retail sales increased by 10%. Inventory levels for passenger vehicles remain a concern. Two-wheeler registrations rose 21% while three-wheeler registrations saw a 41% increase. Tractor sales experienced a slight decline. Cement prices in India have corrected by an average of 2% in November due to slowed demand amid the festive season and elections in some states. The average cement price in India is about ₹382 for a 50 kg bag, almost unchanged from November last year but down marginally from ₹386 a bag in the current quarter. The season also saw a shift in fortunes for general trade, which boosted its market share to 35-40% from about 32% the year before, while online channels remained flat. That said, analysts continue to predict a 1-2% on-year annual decline in shipments in 2023 despite the notable surge in sales during the festive season. Operators say a bevy of factors are driving the boom in purpose-built student accommodations (PBSAs): India’s young population, increasing enrolment in higher education, surge in students migrating to cities with a greater concentration of educational institutions, growing investor and developer interest, and students’ preference for quality, organised accommodation. Indian automakers celebrated their most successful festive season to date, marking a remarkable 41% year-on-year surge in passenger vehicle (PV) sales during the three months spanning the festivals of Onam to Bhai Dooj. Automakers expect to close the year with sales of 4.10-4.17 million cars, utility vehicles and vans - 8-10% more than 2022 compared to the earlier estimate of about 0-6% growth - despite the high base of last year when sales had grown by 23% to 3.79 million units, several senior executives told ET. Better-than-expected demand for sports utility vehicles (SUVs) at the more premium end of the market is driving the sales, they said. The spirits market in India expanded 10% during the first half of the calendar year, the only discretionary category to retain strong growth momentum as consumers cut back on other lifestyle segments such as apparel and electronics. The December quarter is generally a peak period for spirits due to weddings, festivals and winter months. Originally a 24-hour online shopping event held on Nov. 11 each year in China, the 'Singles Day' festival - a nod to the digits in the date - has expanded into weeks of promotions across the country's major e-commerce platforms and in brick-and-mortar stores. A total of 389,714 cars and utility vehicles were sold last month, a 15.9% increase from 336,330 vehicles sold a year earlier, showed data from industry body Society of Indian Automobile Manufacturers (SIAM). Automakers in the country mostly report wholesale despatches from factories and not retail sales to customers. Amazon said that it received the highest single-day of Prime sign-ups, which is paid memberships, in the first 48 hours of sale. More than 65 per cent of Prime members who shopped during the festive season were from tier 2 and 3 cities and towns. Six months ago, a 1-carat LGD ring at the retail level was priced at ₹2 lakh. But now it costs ₹80,000-₹1 lakh. Similarly, a 1-carat natural diamond ring was priced ₹8 lakh six months ago but now it has dropped to ₹5 lakh, a fall of 37.5% . Diamond solitaire rings are flying off the shelves, as well-heeled customers take advantage of this trend. E-way bill generation in India reached a record high of over 10 crore in October, driven by robust festive demand and increased compliance. Both intra-state and inter-state bill generation recorded growth during the month, with inter-state trade growing at a faster pace. As per industry reports, residential sales in India are projected to achieve a record high in 2023, as developers anticipate selling more than 500,000 housing units by the year's end. According to data analytics firm PropEquity Data, in 2022, developers in the top seven cities sold 464,849 units. In the first nine months of this year, they have already sold 372,961 units. Economists say most indicators remain elevated but there are signs of growth slowing. "India's manufacturing sector generated substantial growth in October, despite a challenging global economic environment," said Pollyanna De Lima, economics associate director at S&P Global Market Intelligence. Gold demand in India surged 10% YoY in Q3, reaching 210 tonnes, driven by lower prices and robust rural demand. Despite concerns about El Nino and a patchy monsoon, the World Gold Council (WGC) estimates India's annual consumption to be 700-750 tonnes for 2023. The WGC's Q3 Gold Demand Trends report also highlighted strong global demand, with central bank purchases contributing to a 1,147-tonne demand, 8% above the five-year average. Meanwhile, the government has revised downwards wheat production estimate by 2.19 mt to a record 110.55 mt for the 2022-23 crop year ended June, as per the agriculture ministry data. The country's actual wheat production stood at 107.74 mt in the 2021-22 crop year (July-June). Indian wheat prices have reached an eight-month high due to strong demand for festivals, limited supplies, and import duties making overseas buying unfeasible for domestic flour mills. The government may release more stocks and eliminate import duties to control prices. Rising wheat prices could contribute to food inflation. Passenger vehicle sales in India surpassed two million units in the first half of the year for the first time, driven by strong demand for utility vehicles. Sales of cars, sedans, and utility vehicles reached a record 361,717 units in September, a 1.9% increase compared to the same month last year. The utility vehicle segment accounted for 59.5% of overall passenger vehicle sales in the September quarter.
english
{ "name": "@canrau/gatsby-plugin-react-head", "description": "Gatsby plugin to setup up react-head and make it SSR ready", "version": "0.2.2", "license": "MIT", "author": "<NAME> <<EMAIL>> (https://www.canrau.com)", "main": "index.js", "repository": "https://github.com/canrau/gatsby-plugin-react-head", "bugs": { "url": "https://github.com/canrau/gatsby-plugin-react-head/issues" }, "keywords": [ "gatsby", "gatsby-plugin", "react", "head", "SEO", "helmet", "title", "meta" ], "peerDependencies": { "react-head": "^3.1.1" } }
json
<filename>pkg/lnd/channel_events.go package lnd import ( "context" "database/sql" "encoding/json" "fmt" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/cockroachdb/errors" "github.com/jmoiron/sqlx" "github.com/lightningnetwork/lnd/lnrpc" "github.com/lncapital/torq/internal/channels" "google.golang.org/grpc" "gopkg.in/guregu/null.v4" "io" "time" ) func getChanPoint(cb []byte, oi uint32) (string, error) { ch, err := chainhash.NewHash(cb) if err != nil { return "", err } return fmt.Sprintf("%s:%d", ch.String(), oi), nil } // storeChannelEvent extracts the timestamp, channel ID and PubKey from the // ChannelEvent and converts the original struct to json. // Then it's stored in the database in the channel_event table. func storeChannelEvent(db *sqlx.DB, ce *lnrpc.ChannelEventUpdate, pubKeyChan chan string, chanPointChan chan string) error { jb, err := json.Marshal(ce) if err != nil { return fmt.Errorf("storeChannelEvent -> json.Marshal(%v): %v", ce, err) } timestampMs := time.Now().UTC() var ChanID uint64 var ChannelPoint string var PubKey string switch ce.Type { case lnrpc.ChannelEventUpdate_OPEN_CHANNEL: c := ce.GetOpenChannel() ChanID = c.ChanId ChannelPoint = c.ChannelPoint PubKey = c.RemotePubkey // Add the remote public key to the list to listen to for graph updates. pubKeyChan <- c.RemotePubkey // Add the channel point to the chanPointList, this allows the // channel graph to listen for routing policy updates chanPointChan <- c.ChannelPoint channel := channels.Channel{ ShortChannelID: channels.ConvertLNDShortChannelID(ChanID), ChannelPoint: null.StringFrom(ChannelPoint), DestinationPubKey: null.StringFrom(PubKey), } err = channels.AddChannelRecordIfDoesntExist(db, channel) if err != nil { return err } case lnrpc.ChannelEventUpdate_CLOSED_CHANNEL: c := ce.GetClosedChannel() ChanID = c.ChanId ChannelPoint = c.ChannelPoint PubKey = c.RemotePubkey // Updates the channel point list by removing the channel point from the chanPointList. chanPointChan <- c.ChannelPoint channel := channels.Channel{ ShortChannelID: channels.ConvertLNDShortChannelID(ChanID), ChannelPoint: null.StringFrom(ChannelPoint), DestinationPubKey: null.StringFrom(PubKey), } err = channels.AddChannelRecordIfDoesntExist(db, channel) if err != nil { return err } case lnrpc.ChannelEventUpdate_FULLY_RESOLVED_CHANNEL: c := ce.GetFullyResolvedChannel() ChannelPoint, err = getChanPoint(c.GetFundingTxidBytes(), c.GetOutputIndex()) if err != nil { return err } case lnrpc.ChannelEventUpdate_ACTIVE_CHANNEL: c := ce.GetActiveChannel() ChannelPoint, err = getChanPoint(c.GetFundingTxidBytes(), c.GetOutputIndex()) if err != nil { return err } case lnrpc.ChannelEventUpdate_INACTIVE_CHANNEL: c := ce.GetInactiveChannel() ChannelPoint, err = getChanPoint(c.GetFundingTxidBytes(), c.GetOutputIndex()) if err != nil { return err } case lnrpc.ChannelEventUpdate_PENDING_OPEN_CHANNEL: c := ce.GetPendingOpenChannel() ChannelPoint, err = getChanPoint(c.GetTxid(), c.GetOutputIndex()) if err != nil { return err } default: // TODO: Need to improve error handling and logging in the case of unknown event. // Simply storing the event without any link to a channel. } err = insertChannelEvent(db, timestampMs, ce.Type, false, ChanID, ChannelPoint, PubKey, jb) if err != nil { return errors.Wrapf(err, `storeChannelEvent -> insertChannelEventExec(%v, %s, %s, %t, %d, %s, %s, %v)`, db, timestampMs, ce.Type, false, ChanID, ChannelPoint, PubKey, jb) } return nil } type lndClientSubscribeChannelEvent interface { SubscribeChannelEvents(ctx context.Context, in *lnrpc.ChannelEventSubscription, opts ...grpc.CallOption) (lnrpc.Lightning_SubscribeChannelEventsClient, error) } // SubscribeAndStoreChannelEvents Subscribes to channel events from LND and stores them in the // database as a time series func SubscribeAndStoreChannelEvents(ctx context.Context, client lndClientSubscribeChannelEvent, db *sqlx.DB, pubKeyChan chan string, chanPoinChan chan string) error { cesr := lnrpc.ChannelEventSubscription{} stream, err := client.SubscribeChannelEvents(ctx, &cesr) if err != nil { return errors.Wrapf(err, "SubscribeAndStoreChannelEvents -> client.SubscribeChannelEvents(%v, %v)", ctx, cesr) } for { select { case <-ctx.Done(): return ctx.Err() default: } chanEvent, err := stream.Recv() if err == io.EOF { break } if err != nil { return errors.Wrap(err, "SubscribeChannelEvents -> stream.Recv()") } err = storeChannelEvent(db, chanEvent, pubKeyChan, chanPoinChan) if err != nil { return errors.Wrapf(err, "storeChannelEvent(%v, %v)", db, client) } } return nil } func ImportChannelList(t lnrpc.ChannelEventUpdate_UpdateType, db *sqlx.DB, client lnrpc.LightningClient) error { ctx := context.Background() switch t { case lnrpc.ChannelEventUpdate_OPEN_CHANNEL: req := lnrpc.ListChannelsRequest{} r, err := client.ListChannels(ctx, &req) if err != nil { return errors.Wrapf(err, "ImportChannelList -> client.ListChannels(%v, %v)", ctx, req) } err = storeImportedOpenChannels(db, r.Channels) if err != nil { return errors.Wrapf(err, "ImportChannelList -> storeImportedOpenChannels(%v, %v)", db, r.Channels) } case lnrpc.ChannelEventUpdate_CLOSED_CHANNEL: req := lnrpc.ClosedChannelsRequest{} r, err := client.ClosedChannels(ctx, &req) if err != nil { return errors.Wrapf(err, "ImportChannelList -> client.ClosedChannels(%v, %v)", ctx, req) } err = storeImportedClosedChannels(db, r.Channels) if err != nil { return errors.Wrapf(err, "ImportChannelList -> storeImportedClosedChannels(%v, %v)", db, r.Channels) } } return nil } func getExistingChannelEvents(t lnrpc.ChannelEventUpdate_UpdateType, db *sqlx.DB, cp []string) ([]string, error) { // Prepare the query with an array of channel points q := "select chan_point from channel_event where (chan_point in (?)) and (event_type = ?);" qs, args, err := sqlx.In(q, cp, t) if err != nil { return []string{}, errors.Wrapf(err, "sqlx.In(%s, %v, %d)", q, cp, t) } // Query and create the list of existing channel points (ecp) var ecp []string qsr := db.Rebind(qs) rows, err := db.Query(qsr, args...) if err != nil { return []string{}, errors.Wrapf(err, "getExistingChannelEvents -> db.Query(qsr, args...)") } for rows.Next() { var cp sql.NullString err = rows.Scan(&cp) if err != nil { return nil, err } if cp.Valid { ecp = append(ecp, cp.String) } } return ecp, nil } func enrichAndInsertChannelEvent(db *sqlx.DB, eventType lnrpc.ChannelEventUpdate_UpdateType, imported bool, chanId uint64, chanPoint string, pubKey string, jb []byte) error { // Use current time for imported channel events (open/close). // The time used to open/close events is the timestamp of the opening transaction. timestampMs := time.Now().UTC() err := insertChannelEvent(db, timestampMs, eventType, imported, chanId, chanPoint, pubKey, jb) if err != nil { return errors.Wrapf(err, "storeChannelOpenList -> "+ "insertChannelEventExec(%v, %s, %s, %t, %d, %s, %s, %v)", db, timestampMs, eventType, imported, chanId, chanPoint, pubKey, jb) } return nil } func storeImportedOpenChannels(db *sqlx.DB, c []*lnrpc.Channel) error { // Creates a list of channel points in the request result. var cp []string for _, channel := range c { cp = append(cp, channel.ChannelPoint) } ecp, err := getExistingChannelEvents(lnrpc.ChannelEventUpdate_OPEN_CHANNEL, db, cp) if err != nil { return err } icoLoop: for _, channel := range c { for _, e := range ecp { if channel.ChannelPoint == e { continue icoLoop } } jb, err := json.Marshal(channel) if err != nil { return errors.Wrapf(err, "storeChannelList -> json.Marshal(%v)", channel) } // check if we have seen this channel before and if not store in the channel table channelRecord := channels.Channel{ ShortChannelID: channels.ConvertLNDShortChannelID(channel.ChanId), ChannelPoint: null.StringFrom(channel.ChannelPoint), DestinationPubKey: null.StringFrom(channel.RemotePubkey), } err = channels.AddChannelRecordIfDoesntExist(db, channelRecord) if err != nil { return err } err = enrichAndInsertChannelEvent(db, lnrpc.ChannelEventUpdate_OPEN_CHANNEL, true, channel.ChanId, channel.ChannelPoint, channel.RemotePubkey, jb) if err != nil { return errors.Wrapf(err, "storeChannelOpenList -> "+ "enrichAndInsertChannelEvent(%v, %d, %t, %d, %s, %s, %v)", db, lnrpc.ChannelEventUpdate_OPEN_CHANNEL, true, channel.ChanId, channel.ChannelPoint, channel.RemotePubkey, jb) } } return nil } func storeImportedClosedChannels(db *sqlx.DB, c []*lnrpc.ChannelCloseSummary) error { // Creates a list of channel points in the request result. var cp []string for _, channel := range c { cp = append(cp, channel.ChannelPoint) } ecp, err := getExistingChannelEvents(lnrpc.ChannelEventUpdate_CLOSED_CHANNEL, db, cp) if err != nil { return err } icoLoop: for _, channel := range c { for _, e := range ecp { if channel.ChannelPoint == e { continue icoLoop } } jb, err := json.Marshal(channel) if err != nil { return errors.Wrapf(err, "storeChannelList -> json.Marshal(%v)", channel) } // check if we have seen this channel before and if not store in the channel table channelRecord := channels.Channel{ ShortChannelID: channels.ConvertLNDShortChannelID(channel.ChanId), ChannelPoint: null.StringFrom(channel.ChannelPoint), DestinationPubKey: null.StringFrom(channel.RemotePubkey), } err = channels.AddChannelRecordIfDoesntExist(db, channelRecord) if err != nil { return err } err = enrichAndInsertChannelEvent(db, lnrpc.ChannelEventUpdate_CLOSED_CHANNEL, true, channel.ChanId, channel.ChannelPoint, channel.RemotePubkey, jb) if err != nil { return errors.Wrapf(err, "storeImportedClosedChannels -> "+ "enrichAndInsertChannelEvent(%v, %s, %t, %d, %s, %s, %v)", db, lnrpc.ChannelEventUpdate_CLOSED_CHANNEL, true, channel.ChanId, channel.ChannelPoint, channel.RemotePubkey, jb) } } return nil } var sqlStm = `INSERT INTO channel_event (time, event_type, imported, chan_id, chan_point, pub_key, event) VALUES($1, $2, $3, $4, $5, $6, $7);` func insertChannelEvent(db *sqlx.DB, ts time.Time, eventType lnrpc.ChannelEventUpdate_UpdateType, imported bool, chanId uint64, chanPoint string, pubKey string, jb []byte) error { _, err := db.Exec(sqlStm, ts, eventType, imported, chanId, chanPoint, pubKey, jb) if err != nil { return errors.Wrapf(err, `insertChannelEvent -> db.Exec(%s, %s, %d, %t, %d, %s, %s, %v)`, sqlStm, ts, eventType, imported, chanId, chanPoint, pubKey, jb) } return nil }
go
As Hurricane Dorian, the first major storm of the 2019 Atlantic hurricane season, strengthens to Category 4, much of the Caribbean is breathing a sigh of relief that the storm was not as powerful when it travelled through the U. S. Virgin Islands and skimmed Puerto Rico on August 28. Meteorologists have predicted that the storm could ramp up to Category 5 as it heads for Florida: This is about as perfect as a hurricane gets in the Atlantic Ocean. Hurricane #Dorian is a strong Category 4, and possibly will become a Category 5 later today. Since its journey through the region, Dorian has grown in both strength and intensity. The Bahamas has hunkered down and is bracing for rough weather, as the storm's path is expected to continue along the northwest of the archipelago. Hurricane-force winds are estimated to extend outward up to 30 miles (45 km) from the storm's centre, bringing 10 to 15 inches of rain to the northwest Bahamas and 2 to 4 inches in the central Bahamas—conditions which have the potential to cause flash flooding and loss of life. Holly Bynoe, curator at the National Art Gallery of The Bahamas, posted on Facebook: The Bahamas is not ready for any storm–much less a significant cat 3/4 hurricane–we are not even ready for a few inches of rain. The northern islands and its people cannot go through this trauma, again. At this point, it seems unending and relentless. She went on to detail the storms the archipelago has suffered, the billions of dollars worth of damage as a result, and deferred attempts to invest in green energy and hardier infrastructure, concluding: However, we must be asking ourselves other questions now, more in-depth inquiries about our futures, the countries we want to occupy, the spaces that we want to build, the peace we want to inhabit and the WHOLE citizens we aspire to be. If we do not, we fall into the trap of being generationally traumatised peoples moving into a future of rising sea levels, mounting temperatures and being re-colonised by systems of embedded failure. Meanwhile, Bahamian Prime Minister Hubert Minnis has put an evacuation order in place for parts of Grand Bahama and the Abaco Islands, saying that this was not a storm to be trifled with. Bynoe responded to this news by saying: I am on my goat knees praying for the safe passage through the tempest for the people of the Abacos and Grand Bahama. I just watched the evacuation notice and my heart and mind can not fathom what the next 48 hours will look like for them. Gut wrenching terror as they prepare for landfall. Nassau will not be in the direct path of Dorian but we are in the cone and will experience tropical storm conditions. To say this is fortunate feels unfair in the face of what’s to come. The might of the storm has not deterred American hurricane chaser Josh Morgerman, though, who was determined to get to The Bahamas before access was shut down: Dorian appears to be turning farther north even with The Bahamas in its sights. But the fact that it is a lumberingly slow-moving storm has some suggesting that it could be the most violent system to hit the east coast of the United States in 30 years.
english
<filename>README.md<gh_stars>1-10 # datasette-haversine [![PyPI](https://img.shields.io/pypi/v/datasette-haversine.svg)](https://pypi.org/project/datasette-haversine/) [![Changelog](https://img.shields.io/github/v/release/simonw/datasette-haversine?include_prereleases&label=changelog)](https://github.com/simonw/datasette-haversine/releases) [![Tests](https://github.com/simonw/datasette-haversine/workflows/Test/badge.svg)](https://github.com/simonw/datasette-haversine/actions?query=workflow%3ATest) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/datasette-haversine/blob/main/LICENSE) Datasette plugin that adds a custom SQL function for haversine distances Install this plugin in the same environment as Datasette to enable the `haversine()` SQL function. $ pip install datasette-haversine The plugin is built on top of the [haversine](https://github.com/mapado/haversine) library. ## haversine() to calculate distances ```sql select haversine(lat1, lon1, lat2, lon2); ``` This will return the distance in kilometers between the point defined by `(lat1, lon1)` and the point defined by `(lat2, lon2)`. ## Custom units By default `haversine()` returns results in km. You can pass an optional third argument to get results in a different unit: - `ft` for feet - `m` for meters - `in` for inches - `mi` for miles - `nmi` for nautical miles - `km` for kilometers (the default) ```sql select haversine(lat1, lon1, lat2, lon2, 'mi'); ```
markdown
Take no prisoners, allow no rhyme: haven't the inclination, Won't spare the time. is not my preference, so it goes; something like that. Never mind. It's a point of reference. Why is my mind not crystal clear, cunningly astute, sharp as a knife; and overworked similes? Why indeed? Surely must be a reason: over which I have no control. If not, the fault's in me; a flaw in my identity, my sense or perception of worth. Did I acquire it, was it there at birth? Really! Call it intoxication: I can buy that; captures the moment, craving to be fed. The id rampant, takes no prisoners; consumes everything in its path, rhyme, reason, time, treason. I want what I want. Give it to me, I am quite happy to take it regardless. doesn't matter if it's true or false, as long as it had dramatic tension; as long as I don't have to waltz. I need something to believe in; a touch of magic, in which I am special, not ordinary. Ordinary, I disdain; boredom is for the dull. I am not. I proclaim. I exclaim. Vanity, Vanity is my name.
english
<gh_stars>1-10 export default function(text: string) { return text .replace(/</g, "&lt;") .replace(/>/g, "&gt;") };
typescript
Golden Globes 2019: Allison Janney, Saoirse Ronan, Gary Oldman and many other previous year’s winners and nominees will be presenters at this year’s ceremony. Actors Jessica Chastain and Sam Rockwell have been announced as the presenters for 2019 Golden Globe Awards. The announcement was made by The Hollywood Foreign Press Association, the organiser of the award ceremony, on Twitter. Rockwell, who is nominated for a Golden Globe this year for his role as George W Bush in Vice, had won the Best Supporting Actor in a Motion Picture trophy for his role in Three Billboard Outside Ebbing, Missouri in 2018. Chastain won the Golden Globe for Best Actress in a Motion Picture - Drama in 2013 for her performance in Zero Dark Thirty. “The HFPA is proud to announce that Sam Rockwell and @jes_chastain will be presenters at the 76th Golden Globe Awards! ” read a tweet by the official Twitter handle of Golden Globes. Previous year winners like Allison Janney, Saoirse Ronan, Gary Oldman and Sterling K Brown are on the list of award presenters. They will be joined by Lupita Nyong’o, Octavia Spencer, Chadwick Boseman, Taraji P Henson and William H Macy. HFPA, however, has not revealed the awards that all the actors will be presenting. Golden Globes award ceremony, which will be hosted by Sandra Oh and Andy Samberg, will take place on January 6, 2019.
english
Reigning French Open champion Stan Wawrinka was sent packing by big serving Kevin Anderson 7-6(4), 7-6(11) on Wednesday. The match saw no breaks of serve indicating how well both players served. Wawrinka’s forehand, which was a weapon in the French Open let him down in both tie-breaks. Wawrinka made two errors in the first tie-break which enabled Anderson to build up a 5-1 lead. The World No. 4 had a set point serving at 11-10 in the second breaker. He squandered it by making two uncharacteristic forehand errors. Anderson finished the match with a booming ace down the middle. The South African served 22 aces in the match. It is Anderson’s fourth straight win over Wawrinka. Co-incidentally, both of Wawrinka’s first defeats after winning a Grand Slam have come against Anderson. World No. 17 Anderson was pumped up after his win. “I definitely tried to come in quite a bit, especially off my serves, trying to take away his block return a bit,” Anderson said. In other results, Milos Raonic, who missed the French Open due to an injury beat Richard Gasquet 6-4, 6-7 (5), 6-1. Frenchman Gilles Simon was too good for young Australian Thanasi Kokkinakis in his 6-4, 6-2 win. Anderson will take on Guillermo Garcia-Lopez in the quarterfinal. The Spaniard took out Rafael Nadal’s conqueror Alexandr Dolgoplov 6-3, 7-6 (4). Andy Murray will be in action on Thursday as he takes on Fernando Verdasco in the Round of 16.
english
# (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Unit tests for Cisco FC zone driver.""" from unittest import mock from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import importutils from cinder import exception from cinder import test from cinder.volume import configuration as conf from cinder.zonemanager.drivers.cisco import cisco_fc_zone_driver as driver _active_cfg_before_add = {} _active_cfg_before_delete = { 'zones': { 'openstack10008c7cff523b0120240002ac000a50': ( ['fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', 'fc00:db20:35b:7399::5'])}, 'active_zone_config': 'cfg1'} _active_cfg_default = { 'zones': { 'openstack10008c7cff523b0120240002ac000b90': ( ['fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', 'fc00:db20:35b:7399::5'])}, 'active_zone_config': 'cfg1'} _activate = True _zone_name = 'openstack10008c7cff523b0120240002ac000a50' _target_ns_map = {'100000051e55a100': ['20240002ac000a50']} _zoning_status = {'mode': 'basis', 'session': 'none'} _initiator_ns_map = {'100000051e55a100': ['10008c7cff523b01']} _zone_map_to_add = {'openstack10008c7cff523b0120240002ac000a50': ( ['fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b', 'fc00:db20:35b:7399::5'])} _initiator_target_map = {'10008c7cff523b01': ['20240002ac000a50']} _device_map_to_verify = { '304': { 'initiator_port_wwn_list': [ '10008c7cff523b01'], 'target_port_wwn_list': ['20240002ac000a50']}} _fabric_wwn = '304' class CiscoFcZoneDriverBaseTest(object): def setup_config(self, is_normal, mode): fc_test_opts = [ cfg.StrOpt('fc_fabric_address_CISCO_FAB_1', default='10.24.48.213', help='FC Fabric names'), ] configuration = conf.Configuration(fc_test_opts) # fill up config configuration.zoning_mode = 'fabric' configuration.zone_driver = ('cinder.tests.unit.zonemanager.' 'test_cisco_fc_zone_driver.' 'FakeCiscoFCZoneDriver') configuration.cisco_sb_connector = ('cinder.tests.unit.zonemanager.' 'test_cisco_fc_zone_driver' '.FakeCiscoFCZoneClientCLI') configuration.zoning_policy = 'initiator-target' configuration.zone_activate = True configuration.zone_name_prefix = 'openstack' configuration.fc_san_lookup_service = ('cinder.tests.unit.zonemanager.' 'test_cisco_fc_zone_driver.' 'FakeCiscoFCSanLookupService') configuration.fc_fabric_names = 'CISCO_FAB_1' configuration.fc_fabric_address_CISCO_FAB_1 = '172.21.60.220' if (is_normal): configuration.fc_fabric_user_CISCO_FAB_1 = 'admin' else: configuration.fc_fabric_user_CISCO_FAB_1 = 'invaliduser' configuration.fc_fabric_password_CISCO_FAB_1 = '<PASSWORD>' if (mode == 1): configuration.zoning_policy_CISCO_FAB_1 = 'initiator-target' elif (mode == 2): configuration.zoning_policy_CISCO_FAB_1 = 'initiator' else: configuration.zoning_policy_CISCO_FAB_1 = 'initiator-target' configuration.zone_activate_CISCO_FAB_1 = True configuration.zone_name_prefix_CISCO_FAB_1 = 'openstack' configuration.zoning_vsan_CISCO_FAB_1 = '304' return configuration class TestCiscoFcZoneDriver(CiscoFcZoneDriverBaseTest, test.TestCase): def setUp(self): super(TestCiscoFcZoneDriver, self).setUp() # setup config for normal flow self.setup_driver(self.setup_config(True, 1)) GlobalVars._zone_state = [] def setup_driver(self, config): self.driver = importutils.import_object( 'cinder.zonemanager.drivers.cisco.cisco_fc_zone_driver' '.CiscoFCZoneDriver', configuration=config) def fake_get_active_zone_set(self, fabric_ip, fabric_user, fabric_pwd, zoning_vsan): return GlobalVars._active_cfg def fake_get_san_context(self, target_wwn_list): fabric_map = {} return fabric_map def test_delete_connection(self): GlobalVars._is_normal_test = True GlobalVars._active_cfg = _active_cfg_before_delete self.driver.delete_connection( 'CISCO_FAB_1', _initiator_target_map) self.assertNotIn(_zone_name, GlobalVars._zone_state) def test_delete_connection_for_initiator_mode(self): GlobalVars._is_normal_test = True GlobalVars._active_cfg = _active_cfg_before_delete self.setup_driver(self.setup_config(True, 2)) self.driver.delete_connection( 'CISCO_FAB_1', _initiator_target_map) self.assertNotIn(_zone_name, GlobalVars._zone_state) @mock.patch.object(driver.CiscoFCZoneDriver, 'get_zoning_status') @mock.patch.object(driver.CiscoFCZoneDriver, 'get_active_zone_set') def test_add_connection(self, get_active_zone_set_mock, get_zoning_status_mock): """Test normal flows.""" GlobalVars._is_normal_test = True GlobalVars._zone_state = [] self.setup_driver(self.setup_config(True, 1)) get_zoning_status_mock.return_value = {'mode': 'basis', 'session': 'none'} get_active_zone_set_mock.return_value = _active_cfg_default self.driver.add_connection('CISCO_FAB_1', _initiator_target_map) self.assertTrue(_zone_name in GlobalVars._zone_state) @mock.patch.object(driver.CiscoFCZoneDriver, 'get_zoning_status') @mock.patch.object(driver.CiscoFCZoneDriver, 'get_active_zone_set') def test_add_connection_with_no_cfg(self, get_active_zone_set_mock, get_zoning_status_mock): """Test normal flows.""" GlobalVars._is_normal_test = True GlobalVars._zone_state = [] self.setup_driver(self.setup_config(True, 1)) get_zoning_status_mock.return_value = {'mode': 'basis', 'session': 'none'} get_active_zone_set_mock.return_value = {} self.driver.add_connection('CISCO_FAB_1', _initiator_target_map) self.assertTrue(_zone_name in GlobalVars._zone_state) def test_add_connection_for_invalid_fabric(self): """Test abnormal flows.""" GlobalVars._is_normal_test = True GlobalVars._active_cfg = _active_cfg_before_add GlobalVars._is_normal_test = False self.setup_driver(self.setup_config(False, 1)) self.assertRaises(exception.FCZoneDriverException, self.driver.add_connection, 'CISCO_FAB_1', _initiator_target_map) def test_delete_connection_for_invalid_fabric(self): GlobalVars._active_cfg = _active_cfg_before_delete GlobalVars._is_normal_test = False self.setup_driver(self.setup_config(False, 1)) self.assertRaises(exception.FCZoneDriverException, self.driver.delete_connection, 'CISCO_FAB_1', _initiator_target_map) class FakeCiscoFCZoneClientCLI(object): def __init__(self, ipaddress, username, password, port, vsan): if not GlobalVars._is_normal_test: raise processutils.ProcessExecutionError( "Unable to connect to fabric") def get_active_zone_set(self): return GlobalVars._active_cfg def add_zones(self, zones, activate, fabric_vsan, active_zone_set, zone_status): GlobalVars._zone_state.extend(zones.keys()) def delete_zones(self, zone_names, isActivate): zone_list = zone_names.split(';') GlobalVars._zone_state = [ x for x in GlobalVars._zone_state if x not in zone_list] def get_nameserver_info(self): return _target_ns_map def get_zoning_status(self): return _zoning_status def close_connection(self): pass def cleanup(self): pass class FakeCiscoFCSanLookupService(object): def get_device_mapping_from_network(self, initiator_wwn_list, target_wwn_list): device_map = {} initiators = [] targets = [] for i in initiator_wwn_list: if (i in _initiator_ns_map[_fabric_wwn]): initiators.append(i) for t in target_wwn_list: if (t in _target_ns_map[_fabric_wwn]): targets.append(t) device_map[_fabric_wwn] = { 'initiator_port_wwn_list': initiators, 'target_port_wwn_list': targets} return device_map class GlobalVars(object): global _active_cfg _active_cfg = {} global _zone_state _zone_state = list() global _is_normal_test _is_normal_test = True global _zoning_status _zoning_status = {}
python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import collections import os import torch import math from fairseq import bleu, data, options, utils from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar import progress_bar from fairseq.sequence_generator import SequenceGenerator def main(): parser = options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum number of tokens in a batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch size for test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch size for validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset to use for training (train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list ofdata subsets ' ' to use for validation (train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated list ofdata subset ' 'to use for testing (train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to external validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval = args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens to infinity(same as setting to None) if args.max_tokens == 0: args.max_tokens = None # Load dataset dataset = data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang is None or args.target_lang is None: # record inferred languages in args, so that it's saved in checkpoints args.source_lang, args.target_lang = dataset.src, dataset.dst print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for split in dataset.splits: print('| {} {} {} examples'.format(args.data, split, len(dataset.splits[split]))) if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not supported') num_gpus = torch.cuda.device_count() print('| using {} GPUs (with max tokens per GPU = {})'.format(num_gpus, args.max_tokens)) # Build model print('| model {}'.format(args.arch)) model = utils.build_model(args, dataset) criterion = utils.build_criterion(args, dataset) # Start multiprocessing trainer = MultiprocessingTrainer(args, model) # Load the latest checkpoint if one is available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until the learning rate gets too small val_loss = None max_epoch = args.max_epoch or math.inf lr = trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch <= max_epoch: # train for one epoch train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus) # evaluate on validate set for k, subset in enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch, trainer, criterion, dataset, subset, num_gpus) if k == 0: if not args.no_save: # save checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script) # only use first validation loss to update the learning schedule lr = trainer.lr_step(val_loss, epoch) epoch += 1 batch_offset = 0 train_meter.stop() print('| done training in {:.1f} seconds'.format(train_meter.sum)) # Generate on test set and compute BLEU score for beam in [1, 5, 10, 20]: for subset in args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0 if num_gpus > 0 else None)) print('| Test on {} with beam={}: {}'.format(subset, beam, scorer.result_string())) # Stop multiprocessing trainer.stop() def train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus): """Train the model for one epoch.""" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter = AverageMeter() # sentences per batch wpb_meter = AverageMeter() # words per batch wps_meter = TimeMeter() # words per second clip_meter = AverageMeter() # % of updates clipped gnorm_meter = AverageMeter() # gradient norm desc = '| epoch {:03d}'.format(epoch) lr = trainer.get_lr() with progress_bar(itr, desc, leave=False) as t: for i, sample in data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm = trainer.train_step(sample, criterion) ntokens = sum(s['ntokens'] for s in sample) src_size = sum(s['src_tokens'].size(0) for s in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm > args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i == 0: # ignore the first mini-batch in words-per-second calculation wps_meter.reset() if args.save_interval > 0 and (i + 1) % args.save_interval == 0: trainer.save_checkpoint(args, epoch, i + 1) fmt = desc + ' | train loss {:2.2f} | train ppl {:3.2f}' fmt += ' | s/checkpoint {:7d} | words/s {:6d} | words/batch {:6d}' fmt += ' | bsz {:5d} | lr {:0.6f} | clip {:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg * 100, gnorm_meter.avg)) def validate(args, epoch, trainer, criterion, dataset, subset, ngpus): """Evaluate the model on the validation set and return the average loss.""" itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter() desc = '| epoch {:03d} | valid on \'{}\' subset'.format(epoch, subset) with progress_bar(itr, desc, leave=False) as t: for _, sample in data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens'] for s in sample) loss = trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc + ' | valid loss {:2.2f} | valid ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss))) # update and return the learning rate return val_loss def score_test(args, model, dataset, subset, beam, cuda_device): """Evaluate the model on the test set and return the BLEU scorer.""" translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _, _, ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer if __name__ == '__main__': main()
python
"use strict"; // Copyright (C) 2016 <NAME> // MIT License. See LICENSE file for details. Object.defineProperty(exports, "__esModule", { value: true }); var chacha20poly1305_1 = require("./chacha20poly1305"); var benchmark_1 = require("@stablelib/benchmark"); var buf8192 = benchmark_1.byteSeq(8192); var buf1111 = benchmark_1.byteSeq(1111); var buf0 = new Uint8Array(0); var key = benchmark_1.byteSeq(32); var nonce = benchmark_1.byteSeq(12); var aead = new chacha20poly1305_1.ChaCha20Poly1305(key); benchmark_1.report("ChaCha20Poly1305 seal 8K", benchmark_1.benchmark(function () { return aead.seal(nonce, buf8192); }, buf8192.length)); benchmark_1.report("ChaCha20Poly1305 seal 1111", benchmark_1.benchmark(function () { return aead.seal(nonce, buf1111); }, buf1111.length)); benchmark_1.report("ChaCha20Poly1305 seal 8K + AD", benchmark_1.benchmark(function () { return aead.seal(nonce, buf8192, buf8192); }, buf8192.length * 2)); benchmark_1.report("ChaCha20Poly1305 seal 1111 + AD", benchmark_1.benchmark(function () { return aead.seal(nonce, buf1111, buf1111); }, buf1111.length * 2)); benchmark_1.report("ChaCha20Poly1305 seal 0 + AD 8K", benchmark_1.benchmark(function () { return aead.seal(nonce, buf0, buf8192); }, buf8192.length)); var sealed8192 = aead.seal(nonce, buf8192); var sealed1111 = aead.seal(nonce, buf1111); var sealed8192ad = aead.seal(nonce, buf8192, buf8192); var sealed1111ad = aead.seal(nonce, buf1111, buf1111); benchmark_1.report("ChaCha20Poly1305 open 8K", benchmark_1.benchmark(function () { return aead.open(nonce, sealed8192); }, buf8192.length)); benchmark_1.report("ChaCha20Poly1305 open 1111", benchmark_1.benchmark(function () { return aead.open(nonce, sealed1111); }, buf1111.length)); benchmark_1.report("ChaCha20Poly1305 open 8K + AD", benchmark_1.benchmark(function () { return aead.open(nonce, sealed8192ad, buf8192); }, buf8192.length * 2)); benchmark_1.report("ChaCha20Poly1305 open 1111 + AD", benchmark_1.benchmark(function () { return aead.seal(nonce, sealed1111ad, buf1111); }, buf1111.length * 2)); sealed8192[0] ^= sealed8192[0]; benchmark_1.report("ChaCha20Poly1305 open (bad)", benchmark_1.benchmark(function () { return aead.open(nonce, sealed8192); }, buf8192.length)); //# sourceMappingURL=chacha20poly1305.bench.js.map
javascript
The day Rajinikanth's millions of fans have been waiting for is finally here. The Tamil superstar's mega-budget movie Kochadaiiyaan (also spelled as Kochadaiyaan) has arrived near your theatres in multiple languages. This time, Rajini will be seen in never-before avatars as the film is a historical fiction directed by his daughter Soundarya Ashwin. Kochadaiiyaan has Bollywood's big names like Deepika Padukone and Jackie Shroff in the cast with Oscar Award winner AR Rahman and some of the world-class technicains working behind the screens. These names alone add huge value to the project. Soundarya Ashwin's debut film is made on motion capture technology, which was earlier used in Hollywood films like Tin Tin and Avatar. But only a part of the budget has been spent on this Tamil flick. The story of the film is about a son (Rana)'s fight to regain the lost glory of his father (Kochadaiiyaan) both played by the superstar, who will also be seen as Sena (Third role). AR Rahman's voice tells us about the battle of two kingdoms Kalingpuram and Kottaipattanam. The film begins with a kid running away from his sibling. Why he escapes? We'll come to know it later. In the next phase, we meet valiant warrior Rana impressing the king of Kalingpuram. He becomes a trusted aide of the ruler and on his advise, the king declares a war against Kottaipattanam. But the king is in shock in the battlefield as he sees Rajinikanth supporting his opposition. The makers of the film have put their best efforts on Kochadaiiyaan and have almost made it a fine product. In the beginning, there is a small documentary on motion-capture technology. Frankly speaking, the standards used in the Tamil flick may not be upto the mark but considering that it is a fresh attempt not in only Kollywood but in India, we have to encourage the Soundarya Ashwin's team. The first credit for the success will go to KS Ravikumar for coming out with a remarkable story. Though, it is predictable at parts, the tale manages to surprise you at regular intervals. It is simple, yet entertaining. No matter what Rajinikanth does, he continues to steal the show. His expressions are good to watch. But Deepika Padukone's character disappoints you big time. Jackie Shroff, Sarathkumar, Nassar, Shobana and others have done justice to their roles. Full marks for yesteryear actor Nagesh's character. AR Rahman has not disappointed again for Rajinikanth. The Oscar Award winner has come up with a couple of good songs in Kochadaiiyaan. Audience have given thumbs up for 'Engae pogudho', 'Medhuvaagathaan', 'Maattram Ondrudhaan', 'Manappenin sathiyam', 'Idhayam' and 'Karma veeran' songs. His background score is nothing short of extraordinary. Other technical departments like cinematography and editing are good. Verdict: Verdict: Ignore the technical flaws, watch it for the brave attempt made by Soundarya and her team. Mind you, Kochadaiiyaan is a worth-watching film.
english
<reponame>scutee3/codeview import axios from "axios"; import { Handler } from "./global"; export function getInterviews() { return new Handler(axios.get("/interviews")); } export function getInterview(data: any) { return axios.get("/interviews", { params: data, }); } export function createInterview(data: any) { return new Handler(axios.post("/interviews", data)); } export function modifyInterview(data: any) { return new Handler(axios.patch("/interviews", data)); }
typescript
<reponame>JoeyKinch/OpenNavbar * { -webkit-box-sizing: border-box; box-sizing: border-box; font-family: sans-serif; } html, body { margin: 0; padding: 0; width: 100%; min-height: 100%; background: #ececec; } .open-nav--wrap { padding: 0 2rem; height: 55px; background: #ffffff; position: relative; } .open-nav--wrap .contained { max-width: 1100px; margin: auto; } .open-nav--wrap .open-nav { height: 100%; display: -ms-grid; display: grid; -ms-grid-columns: auto 1fr 200px; grid-template-columns: auto 1fr 200px; } @media (max-width: 800px) { .open-nav--wrap .open-nav { -ms-grid-columns: auto 1fr 30px; grid-template-columns: auto 1fr 30px; } } .open-nav--wrap .open-nav .open-nav--brand { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; font-weight: bold; font-size: 1.1rem; } .open-nav--wrap .open-nav .open-nav--menu { list-style: none; margin: 0; padding: 0; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-grid-column: 3; -ms-grid-column-span: 1; grid-column: 3/4; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; } @media (max-width: 800px) { .open-nav--wrap .open-nav .open-nav--menu { display: none; } } .open-nav--wrap .open-nav .open-nav--menu .open-nav--item a { color: #000000; text-decoration: none; -webkit-transition: ease .12s; transition: ease .12s; } .open-nav--wrap .open-nav .open-nav--menu .open-nav--item a:hover { color: #363636; } .open-nav--wrap .open-nav .open-nav--mobilemenu { position: absolute; top: 55px; left: 0; width: 100%; list-style: none; margin: 0; padding: 0 2rem; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; overflow: hidden; pointer-events: none; background: #ffffff; max-height: 0px; -webkit-transition: max-height .3s ease; transition: max-height .3s ease; } @media (min-width: 800px) { .open-nav--wrap .open-nav .open-nav--mobilemenu { display: none; } } .open-nav--wrap .open-nav .open-nav--mobilemenu .open-nav--item { margin-bottom: 15px; } .open-nav--wrap .open-nav .open-nav--mobilemenu .open-nav--item a { color: #000000; text-decoration: none; -webkit-transition: ease .12s; transition: ease .12s; } .open-nav--wrap .open-nav .open-nav--mobilemenu .open-nav--item a:hover { color: #363636; } .open-nav--wrap .open-nav .open-nav--mobilemenu .open-nav--item:first-child { margin-top: 15px; } .open-nav--wrap .open-nav .open-nav--mobilemenu .open-nav--item:last-child { margin-bottom: 25px; } .open-nav--wrap .open-nav .nav-open { max-height: 130px; pointer-events: all; } .open-nav--wrap .open-nav .nav-toggler { -ms-grid-column: 3; -ms-grid-column-span: 1; grid-column: 3/4; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-item-align: center; align-self: center; height: 30px; cursor: pointer; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: space-evenly; -ms-flex-pack: space-evenly; justify-content: space-evenly; } .open-nav--wrap .open-nav .nav-toggler .nav-toggler-line { width: 100%; height: 2px; background: #bdbdbd; } @media (min-width: 800px) { .open-nav--wrap .open-nav .nav-toggler { display: none; } } .nav-fixed { position: fixed; top: 0; width: 100%; }
css
package storer type QueueSetter interface { QueueSetFileRecord(path string, data *FileRecord) <-chan error } func QueueSetFileRecord(s Storer, path string, data *FileRecord) <-chan error { if queueSetter, ok := s.(QueueSetter); ok { return queueSetter.QueueSetFileRecord(path, data) } err := make(chan error, 1) err <- s.SetFileRecord(path, data) close(err) return err }
go
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.uima.ducc.rm.persistence.access; import java.util.Map; import org.apache.uima.ducc.common.head.IDuccHead; import org.apache.uima.ducc.common.persistence.rm.IDbJob; import org.apache.uima.ducc.common.persistence.rm.IDbShare; import org.apache.uima.ducc.common.persistence.rm.IRmPersistence; import org.apache.uima.ducc.common.persistence.rm.IRmPersistence.RmNodes; import org.apache.uima.ducc.common.persistence.rm.RmPersistenceFactory; import org.apache.uima.ducc.common.utils.DuccLogger; import org.apache.uima.ducc.common.utils.id.DuccId; import org.apache.uima.ducc.rm.DuccHead; import org.apache.uima.ducc.rm.scheduler.SchedConstants; public class PersistenceAccess implements IPersistenceAccess { private static String COMPONENT_NAME = SchedConstants.COMPONENT_NAME; private static DuccId jobid = null; private static DuccLogger logger = DuccLogger.getLogger(PersistenceAccess.class, COMPONENT_NAME); private static IPersistenceAccess persistenceAccess = new PersistenceAccess(); private static String bypass = "bypass"; private IDuccHead dh = DuccHead.getInstance(); private IRmPersistence rm_persistence = null; public static IPersistenceAccess getInstance() { return persistenceAccess; } private PersistenceAccess() { rm_persistence = RmPersistenceFactory.getInstance(this.getClass().getName(), COMPONENT_NAME); } private boolean is_master() { String location = "is_master"; boolean retVal = dh.is_ducc_head_virtual_master(); logger.debug(location, jobid, retVal); return retVal; } @Override public void setNodeProperty(String id, RmNodes key, Object value) throws Exception { String location = "setNodeProperty"; if(is_master()) { rm_persistence.setNodeProperty(id, key, value); } else { logger.debug(location, jobid, bypass, id, key, value); } } @Override public void setNodeProperties(String id, Object... properties) throws Exception { String location = "setNodeProperties"; if(is_master()) { rm_persistence.setNodeProperties(id, properties); } else { logger.debug(location, jobid, bypass, id); } } @Override public void addAssignment(String id, DuccId jobid, IDbShare share, int quantum, String jobtype) throws Exception { String location = "addAssignment"; if(is_master()) { rm_persistence.addAssignment(id, jobid, share, quantum, jobtype); } else { logger.debug(location, jobid, bypass, id, jobid, share, quantum, jobtype); } } @Override public void removeAssignment(String id, DuccId jobid, IDbShare share) throws Exception { String location = "removedAssignment"; if(is_master()) { rm_persistence.removeAssignment(id, jobid, share); } else { logger.debug(location, jobid, bypass, id, jobid, share); } } @Override public void createMachine(String id, Map<RmNodes, Object> props) throws Exception { String location = "createMachine"; if(is_master()) { rm_persistence.createMachine(id, props); } else { logger.debug(location, jobid, bypass, id); } } @Override public void clear() throws Exception { String location = "clear"; if(is_master()) { rm_persistence.clear(); } else { logger.debug(location, jobid, bypass); } } @Override public void close() { String location = "close"; if(is_master()) { rm_persistence.close(); } else { logger.debug(location, jobid, bypass); } } @Override public void addJob(IDbJob j) throws Exception { String location = "addJob"; if(is_master()) { rm_persistence.addJob(j); } else { logger.debug(location, jobid, bypass, j); } } @Override public void deleteJob(IDbJob j) throws Exception { String location = "deleteJob"; if(is_master()) { rm_persistence.deleteJob(j); } else { logger.debug(location, jobid, bypass, j); } } @Override public void updateDemand(IDbJob j) throws Exception { String location = "updateDemand"; if(is_master()) { rm_persistence.updateDemand(j); } else { logger.debug(location, jobid, bypass, j); } } @Override public void updateShare(String node, DuccId shareid, DuccId jobid, long investment, String state, long init_time, long pid) throws Exception { String location = "updateShare"; if(is_master()) { rm_persistence.updateShare(node, shareid, jobid, investment, state, init_time, pid); } else { logger.debug(location, jobid, bypass, node, shareid, jobid, investment, state, init_time, pid); } } @Override public void setFixed(String node, DuccId shareId, DuccId jobId, boolean val) throws Exception { String location = "setFixed"; if(is_master()) { rm_persistence.setFixed(node, shareId, jobId, val); } else { logger.debug(location, jobId, bypass, node, shareId, jobId, val); } } @Override public void setPurged(String node, DuccId shareId, DuccId jobId, boolean val) throws Exception { String location = "setPurged"; if(is_master()) { rm_persistence.setPurged(node, shareId, jobId, val); } else { logger.debug(location, jobId, bypass, node, shareId, jobId, val ); } } @Override public void setEvicted(String node, DuccId shareId, DuccId jobId, boolean val) throws Exception { String location = "setEvicted"; if(is_master()) { rm_persistence.setEvicted(node, shareId, jobId, val); } else { logger.debug(location, jobId, bypass, node, shareId, jobId, val ); } } }
java
Progressive multifocal leukoencephalopathy (PML) is a disease that attacks part of your brain. It happens if your body can't fight off disease the way it should. It damages your brain's white matter -- cells that make a substance called myelin. This protects your nerves, and losing it can make it harder for you to move, think, and feel sensations. PML is a very serious illness that can be fatal. It's caused by a virus called the JC virus. Most adults carry it, and it usually doesn't cause any health problems. But it can if you have a weak immune system -- if your body's natural defenses against illness aren't working right. The first signs of PML can be different from person to person, depending on the nerves that are damaged first. But they often include: Sometimes, PML can also cause seizures. About 1 person out of every 200,000 will get PML. That works out to a total of about 4,000 people a year in the United States and Europe combined. It happens most often to people who have AIDS, which attacks the immune system. But people who have some types of cancer or take drugs that keep their body from rejecting a transplanted organ also have a higher risk. People who take medication for multiple sclerosis, which attacks the central nervous system, or other immune system problems, like rheumatoid arthritis or lupus, may be at risk too. U.S. safety officials have said that PML may be a possible side effect of some drugs used to treat multiple sclerosis after a small number of people who used them got it. If your doctor thinks you might have PML, they'll scan your brain with a magnetic resonance imaging machine (MRI). This uses powerful magnets and radio waves to make a detailed picture. They'll look for lesions -- spots of damaged tissue -- that show the disease is there. If an MRI doesn't give a clear picture, they might do a brain biopsy. They'll take a small sample of tissue from your brain to look at under a microscope for signs of the disease. Your doctor might also order a lumbar puncture (spinal tap) to take a sample of the fluid around your brain and spinal cord for testing. The best way to treat PML is to fight whatever has made your immune system weak. You might take drugs that attack the virus that causes AIDS (HIV) or avoid drugs that affect your immune system. You also might need to avoid treatments like chemotherapy, which can put you at higher risk of infections. Researchers are trying to find other drugs to fight the JC virus, but none has been approved for widespread use. White matter killed by the virus doesn't grow back, so your symptoms may be permanent. Many people who have had PML live with the effects of nerve damage. These can be similar to the issues caused by a stroke and can include paralysis and memory loss.
english
// @flow import type { PluginOptions } from 'webpack-bump-plugin' const constants = require('./constants') const fs = require('fs') const logger = require('./logger') module.exports = function process(options: PluginOptions) { if (options.enabled) { // Parse the target const packageRaw = fs.readFileSync(options.target, 'utf8').toString() const packageContent = JSON.parse(packageRaw) const version = packageContent.version const versionparts = version.split(constants.metadataToken) const log = logger(options) // Update the metadata const metadata = (new Date().getTime()).toString() versionparts[1] = metadata // Update the version and write the file const newVersion = versionparts.join(constants.metadataToken) // Write away the package log(`Bumped version: ${version} -> \x1b[34m${newVersion}\x1b[0m`) fs.writeFileSync( options.target, packageRaw.replace(`"version": "${version}"`, `"version": "${newVersion}"`), 'utf8') log(`Bumping ${options.target}`) } }
javascript
{ "anthos_dashboard_restart_host_title": "Ihren Host neu starten", "anthos_dashboard_restart_host_description": "Bitte beachten Sie, dass der Neustart einige Minuten dauern kann. Stellen Sie sich auf die Evakuierung Ihrer Pods ein, um die Verfügbarkeit Ihrer Anwendungen möglichst nicht zu beeinträchtigen.", "anthos_dashboard_restart_host_submit": "Bestätigen", "anthos_dashboard_restart_host_cancel": "Abbrechen", "anthos_dashboard_restart_host_error": "Beim Neustart Ihres Hosts ist ein Fehler aufgetreten: {{message}}" }
json
<filename>package.json { "name": "portfolio", "version": "1.0.0", "description": "personal portfolio site", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/soundwanders/portfolio.git" }, "keywords": [ "jekyll", "bootstrap", "ruby", "gems", "html", "css", "javascript", "personal", "portfolio", "site", "front-end", "developer" ], "author": "soundwanders", "license": "MIT", "bugs": { "url": "https://github.com/soundwanders/portfolio/issues" }, "homepage": "https://github.com/soundwanders/portfolio#readme" }
json
{"h":[{"d":[{"e":["`Mapamatang~ `koni~ `a~ `tokos~.這座山要被開荒了。"],"f":"被開墾,被開荒。"}]}],"stem":"matang","t":"mapamatang"}
json
<gh_stars>0 {"questions": [{"player_1": {"name": "<NAME>", "player_stat": 0.0}, "player_2": {"name": "<NAME>", "player_stat": 4.0}, "stat": "zeroes", "skill": "BAT", "question_text": "Who has more ducks?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 18.4}, "player_2": {"name": "<NAME>", "player_stat": 14.9}, "stat": "strike_rate", "skill": "BOWL", "question_text": "Who has the better bowling strike rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 20.3}, "player_2": {"name": "<NAME>", "player_stat": 22.5}, "stat": "strike_rate", "skill": "BOWL", "question_text": "Who has the better bowling strike rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 758.0}, "player_2": {"name": "<NAME>", "player_stat": 1058.0}, "stat": "runs_given", "skill": "BOWL", "question_text": "Who has given away less runs?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 151.02}, "player_2": {"name": "<NAME>", "player_stat": 168.79}, "stat": "strike_rate", "skill": "BAT", "question_text": "Who has the better batting strike rate?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 1282.0}, "player_2": {"name": "<NAME>", "player_stat": 443.0}, "stat": "runs_given", "skill": "BOWL", "question_text": "Who has given away less runs?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 15.5}, "player_2": {"name": "<NAME>", "player_stat": 16.2}, "stat": "strike_rate", "skill": "BOWL", "question_text": "Who has the better bowling strike rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 26.0}, "player_2": {"name": "<NAME>", "player_stat": 6.0}, "stat": "sixes", "skill": "BAT", "question_text": "Who has hit more sixes?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 6.91}, "player_2": {"name": "<NAME>", "player_stat": 8.65}, "stat": "economy", "skill": "BOWL", "question_text": "Who has the better economy rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 30.08}, "player_2": {"name": "<NAME>", "player_stat": 44.68}, "stat": "average", "skill": "BAT", "question_text": "Who has the better batting average?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 7.35}, "player_2": {"name": "<NAME>", "player_stat": 6.57}, "stat": "economy", "skill": "BOWL", "question_text": "Who has the better economy rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 33.0}, "player_2": {"name": "<NAME>", "player_stat": 96.0}, "stat": "highest", "skill": "BAT", "question_text": "Who has the greater highest score?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 23.0}, "player_2": {"name": "<NAME>", "player_stat": 19.7}, "stat": "strike_rate", "skill": "BOWL", "question_text": "Who has the better bowling strike rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 114.0}, "player_2": {"name": "<NAME>", "player_stat": 108.0}, "stat": "highest", "skill": "BAT", "question_text": "Who has the greater highest score?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 100.0}, "player_2": {"name": "<NAME>", "player_stat": 96.0}, "stat": "highest", "skill": "BAT", "question_text": "Who has the greater highest score?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 7.77}, "player_2": {"name": "<NAME>", "player_stat": 7.4}, "stat": "economy", "skill": "BOWL", "question_text": "Who has the better economy rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 8.39}, "player_2": {"name": "<NAME>", "player_stat": 6.57}, "stat": "economy", "skill": "BOWL", "question_text": "Who has the better economy rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 7.66}, "player_2": {"name": "<NAME>", "player_stat": 8.21}, "stat": "economy", "skill": "BOWL", "question_text": "Who has the better economy rate?", "greater": false}, {"player_1": {"name": "<NAME>", "player_stat": 29.5}, "player_2": {"name": "<NAME>", "player_stat": 33.73}, "stat": "average", "skill": "BAT", "question_text": "Who has the better batting average?", "greater": true}, {"player_1": {"name": "<NAME>", "player_stat": 27.95}, "player_2": {"name": "<NAME>", "player_stat": 29.81}, "stat": "average", "skill": "BOWL", "question_text": "Who has the better bowling average?", "greater": false}]}
json
expected_output = { 'pvst': { 'a': { 'pvst_id': 'a', 'vlans': { 2: { 'vlan_id': 2, 'designated_root_priority': 32768, 'designated_root_address': '0021.1bff.d973', 'designated_root_max_age': 20, 'designated_root_forward_delay': 15, 'bridge_priority': 32768, 'sys_id_ext': 0, 'bridge_address': '8cb6.4fff.6588', 'bridge_max_age': 20, 'bridge_forward_delay': 15, 'bridge_transmit_hold_count': 6, 'interface': { 'GigabitEthernet0/7/0/0': { 'name': 'GigabitEthernet0/7/0/0', 'cost': 20000, 'role': 'DSGN', 'port_priority': 128, 'port_num': 1, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '8cb6.4fff.6588', 'designated_port_priority': 128, 'designated_port_num': 1, }, 'GigabitEthernet0/7/0/1': { 'name': 'GigabitEthernet0/7/0/1', 'cost': 20000, 'role': 'DSGN', 'port_priority': 128, 'port_num': 2, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '8cb6.4fff.6588', 'designated_port_priority': 128, 'designated_port_num': 2, }, 'GigabitEthernet0/7/0/10': { 'name': 'GigabitEthernet0/7/0/10', 'cost': 20000, 'role': 'ROOT', 'port_priority': 128, 'port_num': 3, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '0021.1bff.d973', 'designated_port_priority': 128, 'designated_port_num': 3, }, 'GigabitEthernet0/7/0/11': { 'name': 'GigabitEthernet0/7/0/11', 'cost': 20000, 'role': 'ALT', 'port_priority': 128, 'port_num': 4, 'port_state': 'BLK', 'designated_bridge_priority': 32768, 'designated_bridge_address': '0021.1bff.d973', 'designated_port_priority': 128, 'designated_port_num': 4, }, }, }, 3: { 'vlan_id': 3, 'designated_root_priority': 32768, 'designated_root_address': '0021.1bff.d973', 'designated_root_max_age': 20, 'designated_root_forward_delay': 15, 'bridge_priority': 32768, 'sys_id_ext': 0, 'bridge_address': '8cb6.4fff.6588', 'bridge_max_age': 20, 'bridge_forward_delay': 15, 'bridge_transmit_hold_count': 6, 'interface': { 'GigabitEthernet0/7/0/0': { 'name': 'GigabitEthernet0/7/0/0', 'cost': 20000, 'role': 'DSGN', 'port_priority': 128, 'port_num': 1, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '8cb6.4fff.6588', 'designated_port_priority': 128, 'designated_port_num': 1, }, 'GigabitEthernet0/7/0/1': { 'name': 'GigabitEthernet0/7/0/1', 'cost': 20000, 'role': 'DSGN', 'port_priority': 128, 'port_num': 2, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '8cb6.4fff.6588', 'designated_port_priority': 128, 'designated_port_num': 2, }, 'GigabitEthernet0/7/0/10': { 'name': 'GigabitEthernet0/7/0/10', 'cost': 20000, 'role': 'ROOT', 'port_priority': 128, 'port_num': 3, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '0021.1bff.d973', 'designated_port_priority': 128, 'designated_port_num': 3, }, 'GigabitEthernet0/7/0/11': { 'name': 'GigabitEthernet0/7/0/11', 'cost': 20000, 'role': 'ALT', 'port_priority': 128, 'port_num': 4, 'port_state': 'BLK', 'designated_bridge_priority': 32768, 'designated_bridge_address': '0021.1bff.d973', 'designated_port_priority': 128, 'designated_port_num': 4, }, }, }, 4: { 'vlan_id': 4, 'designated_root_priority': 32768, 'designated_root_address': '0021.1bff.d973', 'designated_root_max_age': 20, 'designated_root_forward_delay': 15, 'bridge_priority': 32768, 'sys_id_ext': 0, 'bridge_address': '8cb6.4fff.6588', 'bridge_max_age': 20, 'bridge_forward_delay': 15, 'bridge_transmit_hold_count': 6, 'interface': { 'GigabitEthernet0/7/0/0': { 'name': 'GigabitEthernet0/7/0/0', 'cost': 20000, 'role': 'DSGN', 'port_priority': 128, 'port_num': 1, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '8cb6.4fff.6588', 'designated_port_priority': 128, 'designated_port_num': 1, }, 'GigabitEthernet0/7/0/1': { 'name': 'GigabitEthernet0/7/0/1', 'cost': 20000, 'role': 'DSGN', 'port_priority': 128, 'port_num': 2, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '8cb6.4fff.6588', 'designated_port_priority': 128, 'designated_port_num': 2, }, 'GigabitEthernet0/7/0/10': { 'name': 'GigabitEthernet0/7/0/10', 'cost': 20000, 'role': 'ROOT', 'port_priority': 128, 'port_num': 3, 'port_state': 'FWD', 'designated_bridge_priority': 32768, 'designated_bridge_address': '0021.1bff.d973', 'designated_port_priority': 128, 'designated_port_num': 3, }, 'GigabitEthernet0/7/0/11': { 'name': 'GigabitEthernet0/7/0/11', 'cost': 20000, 'role': 'ALT', 'port_priority': 128, 'port_num': 4, 'port_state': 'BLK', 'designated_bridge_priority': 32768, 'designated_bridge_address': '0021.1bff.d973', 'designated_port_priority': 128, 'designated_port_num': 4, }, }, }, }, }, }, }
python
<reponame>AsureNetwork/asure-pension-core<gh_stars>1-10 use crate::contributor::Contributor; use crate::pensioner::Pensioner; use crate::doneuser::DoneUser; pub enum User { Contributor(Contributor), Pensioner(Pensioner), Done(DoneUser), } impl User { pub fn new() -> Self { User::Contributor(Contributor::new()) } pub fn to_contributor(&self) -> Option<&Contributor> { match self { User::Contributor(contributor) => Some(contributor), _ => None } } pub fn to_contributor_mut(&mut self) -> Option<&mut Contributor> { match self { User::Contributor(contributor) => Some(contributor), _ => None } } pub fn to_pensioner(&self) -> Option<&Pensioner> { match self { User::Pensioner(pensioner) => Some(pensioner), _ => None } } pub fn to_pensioner_mut(&mut self) -> Option<&mut Pensioner> { match self { User::Pensioner(pensioner) => Some(pensioner), _ => None } } pub fn to_done_user(&self) -> Option<&DoneUser> { match self { User::Done(done_user) => Some(done_user), _ => None } } }
rust
<reponame>mainpage/mainpage.github.io<gh_stars>0 --- layout: keynote title: "移动端单页框架简单调研" subtitle: "" show: "true" iframe: "/2016/08/23/h5-spa-framwork-slide/" date: 2015-08-23 author: "sch" header-img: "" catalog: true tags: - 前端开发 - 移动端 --- 当前移动互联网应用的开发模式主要有三种:Native、Webapp和Hybrid,关于它们的区别和优劣,相信大家已经比较熟悉了。对于web前端来说,与我们相关的是webapp和hybrid app这两种应用形态,其中又以hybrid应用更为广泛。随着近年来前端技术的发展,基于web技术的移动端应用的体验逐步向原生靠近,涌现出一批优秀的移动端web开发框架。本文结合自己在mini项目中的调研和实践,对移动端web开发的一些代表性框架做一个简单的介绍。 #移动端开发模式 Native、Webapp和Hybrid ![](/img/in-post/post-h5-spa-framwork/webapp.png) ## 单页应用(SPA) 对于移动端web应用来说,为了达到媲美原生应用的效果,单页架构几乎是不可或缺的。传统的多页面的应用在页面跳转时需要从服务器加载html并重新渲染,会出现明显的“白屏”现象,对于一个移动端“应用”来说这是不可忍受的。因此,大部分移动端框架选择或支持了单页的开发方式。那么,单页应用都有哪些优点呢? ## 单页应用的优势 * 页面无刷新切换 * 页面切换速度快,体验流畅 * 动画转场效果 * 前后端分离 ## 单页应用必须具备的功能 * 能够管理页面状态的路由系统 * 子页面调度模块 * 数据管理模块 * 页面切换的转场效果 ## 具有代表性的移动端单页框架 * Angular.js * React Native * Vue.js * MobileBone.js ## Angular.js * 大而全的MVC框架 * $routeProvider提供前端路由支持 * controller实现模块调度 * ng-view进行局部渲染 * ngAnimate创建动画效果 ## demo `html` ``` <body ng-app="myApp"> <div class="header">header</div> <div ng-view></div> <div class="footer">footer</span> </body> ``` `js` ``` angular.module('myApp', ['ngRoute']) .config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/detail/:id', { templateUrl: 'views/detail.html', controller: 'DayCtrl' }) .otherwise({ redirectTo: '/' }); }) ``` ## 优缺点 优点: * 功能完善,提供了一整套解决方案 * 数据绑定、依赖注入、单页路由、自定义指令 * MVC架构,分层清晰 缺点: * 框架过重,对移动端而言体积过大 * “脏检查”效率低下 * 没有明确的组件化概念 * 动画转场效果实现较为困难 ## React Native * 基于React.js的组件化机制 * js编写的React组件渲染为原生组件 * Navigator组件实现页面导航和路由 * 路由模块通过实例化不同组件实现模块调度 * Flux架构的数据和状态管理 * 基于原生UI的动画效果 ## demo ``` // 主模块 class MainView extends Component { // ... render() { return ( <Navigator //样式 style={{flex:1}} //初始化路由 initialRoute={{component: FirstPage}} //配置场景动画 configureScene={this.configureScene} //根据路由渲染组件 renderScene={this.renderScene} /> ); } } //renderScene方法 renderScene(route, navigator) { if (route.name == 'Home') { return <Home navigator={navigator} {...route.passProps}/> } else if (route.name == 'Detail') { return <Detail navigator={navigator} {...route.passProps}/> } ... } ``` ## 优缺点 优点 * 完善的组件化机制 * 基于Virtual Dom的数据绑定效率很高 * javascript组件最终渲染为原生组件 * 可以达到接近原生应用的体验 * learn once,write anywhere 缺点: * 依赖原生组件暴露出来的组件和方法 * 一定程度上牺牲了web的灵活性和扩展性 ## Vue.js * 新兴的轻量级MVVM框架 * vue-router提供路由支持 * 路由模块通过实例化不同组件实现模块调度 * Flux架构的数据和状态管理 * 基于transition特性的CSS/动画过渡系统 ## demo `demo.vue` ``` //模板 <template> <nav> <li><a v-link="/home">首页</a></li> <li><a v-link="/detail">详情</a></li> </nav> <div class="container"> <router-view></router-view> </div> </div> </template> <script> ... //路由 const router = new VueRouter() router.map({ '/home': { component: Home }, '/detail': { component: Detail } }) router.redirect({ '*': '/home' }) </script> ``` ## 优缺点 优点: * 完善的组件化机制 * 轻量,~24kb min+gzip * 高效,基于defineProperty的数据绑定 * 快速,异步批量DOM更新 缺点: * 新兴框架,资料较少 * 社区规模较小,影响力有限 * 框架不够成熟 ## MobileBone.js * 轻量webapp单页切换骨架 * 基于hash、H5 history API 和锚点定位的路由 * 通过子页面的id匹配对应路由 * 通过子页面进入和离开时的回调来调度模块 * 可定制的动画转场效果 ## demo 作者提供的demos: [http://rawgit.com/zhangxinxu/mobilebone/master/test/index.html](http://rawgit.com/zhangxinxu/mobilebone/master/test/index.html) ## 优点和缺点: 优点: * 轻量级,插件级别的框架 * 可智能识别页面切换方向 * 动画效果可自定义 缺点 * 页面切换不支持传参 * 仅提供了切换骨架,应用的管理完全需要手动 * 代码组织不够优雅
markdown
<reponame>naineshmehta/sfg.2017 /* SET COLUMNS */ .threeColRightPane { width: 220px; margin-left:10px; float: right; } .threeColLeftPane { width: 120px; float: left; } .contentPane { margin-left:130px; margin-right: 230px; } /* ACCOMODATE EMPTY PANES */ .DNNEmptyPane{width:0; margin:0;} .paneGroup .threeColLeftPane.DNNEmptyPane + .contentPane{ margin-left:0; } .paneGroup .threeColRightPane.DNNEmptyPane + .threeColLeftPane + .contentPane{ margin-right: 0; } .paneGroup .threeColRightPane.DNNEmptyPane + .threeColLeftPane.DNNEmptyPane + .contentPane{ margin-left:0; margin-right: 0; } .console .console-none { background-color: #666; } .console .console-none h3{ color: #fff; font-family: arial; } .console .active.console-none { background-color: #222; }
css
{"Department":"Прокуратура Черкаської області","Region":"Черкаська область","Position":"Прокурор відділу нагляду за додержанням законів територіальними органами поліції при провадженні досудового розслідування та підтриманням державного державного обвинувачення Прокуратури Черкаської області","Name":"<NAME>","Декларації 2013":"","Декларації 2014":"","Декларації 2015":"https://public.nazk.gov.ua/declaration/46924eab-4cb5-4dda-ae49-b3ba4ca8d169","Декларації 2016":"https://public.nazk.gov.ua/declaration/4a97898c-0617-42dc-b6ad-b28f5365d6fb","Фото":"","Як живе":"","Декларації доброчесності":"http://www.gp.gov.ua/integrity_profile/files/c3c5489adc1a636c204be3bc6f6b385a.pdf","type":"prosecutor","key":"onishchenko_igor_stanislavovich","analytics":[{"y":2015,"i":86736,"k":17.56,"ka":1,"fi":51943,"fc":2,"ff":15.43,"ffa":1},{"y":2016,"i":131995,"k":17.56,"ka":1,"fi":116103,"fc":2,"ff":15.43,"ffa":1},{"y":2017,"i":268018,"k":17.56,"ka":1,"fc":2},{"y":2018}],"declarationsLinks":[{"id":"nacp_75393221-9ebd-4f3e-811c-5fedad6f8d97","year":2015,"provider":"declarations.com.ua.opendata"},{"id":"nacp_4a97898c-0617-42dc-b6ad-b28f5365d6fb","year":2016,"provider":"declarations.com.ua.opendata"},{"id":"nacp_70cac24e-c680-4891-8888-23883a01950d","year":2017,"provider":"declarations.com.ua.opendata"},{"id":"nacp_13756627-c6b4-42e8-bfde-b8f310e3cfba","year":2018,"provider":"declarations.com.ua.opendata"}]}
json
use std::path::Path; use indicatif::ProgressStyle; use crate::cli; use crate::cli::color::Color; pub struct ProgressBar { pb: indicatif::ProgressBar, end_message: String, } impl ProgressBar { pub fn new(message: String, end_message: String) -> Self { let pb = indicatif::ProgressBar::new_spinner(); pb.set_style( ProgressStyle::default_spinner() .tick_strings(cli::spinner::TICKS) .template("{spinner:.blue} {msg} {percent}% ({eta})"), ); pb.set_message(message); Self { pb, end_message } } pub fn start(&self) { self.pb.enable_steady_tick(cli::spinner::TICK_DURATION); } pub fn stop(&self) { self.pb.finish_and_clear(); println!("{}", &self.end_message); } pub fn set_max_progress(&self, progress: u64) { self.pb.set_length(progress); } pub fn update_progress(&self, progress: u64) { self.pb.set_position(progress); } pub fn download(download_asset: &str, output_path: &Path) -> ProgressBar { ProgressBar::new( format!("Downloading {}", Color::new(download_asset).bold()), format!( "Saved to: {}", Color::new(&format!("{}", output_path.display())).bold() ), ) } }
rust
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #include "Luau/Module.h" #include "Luau/Common.h" #include "Luau/RecursionCounter.h" #include "Luau/Scope.h" #include "Luau/TypeInfer.h" #include "Luau/TypePack.h" #include "Luau/TypeVar.h" #include "Luau/VisitTypeVar.h" #include <algorithm> LUAU_FASTFLAGVARIABLE(DebugLuauFreezeArena, false) LUAU_FASTFLAGVARIABLE(DebugLuauTrackOwningArena, false) LUAU_FASTINTVARIABLE(LuauTypeCloneRecursionLimit, 300) LUAU_FASTFLAG(LuauTypeAliasDefaults) LUAU_FASTFLAGVARIABLE(LuauPrepopulateUnionOptionsBeforeAllocation, false) namespace Luau { static bool contains(Position pos, Comment comment) { if (comment.location.contains(pos)) return true; else if (comment.type == Lexeme::BrokenComment && comment.location.begin <= pos) // Broken comments are broken specifically because they don't have an end return true; else if (comment.type == Lexeme::Comment && comment.location.end == pos) return true; else return false; } bool isWithinComment(const SourceModule& sourceModule, Position pos) { auto iter = std::lower_bound(sourceModule.commentLocations.begin(), sourceModule.commentLocations.end(), Comment{Lexeme::Comment, Location{pos, pos}}, [](const Comment& a, const Comment& b) { return a.location.end < b.location.end; }); if (iter == sourceModule.commentLocations.end()) return false; if (contains(pos, *iter)) return true; // Due to the nature of std::lower_bound, it is possible that iter points at a comment that ends // at pos. We'll try the next comment, if it exists. ++iter; if (iter == sourceModule.commentLocations.end()) return false; return contains(pos, *iter); } void TypeArena::clear() { typeVars.clear(); typePacks.clear(); } TypeId TypeArena::addTV(TypeVar&& tv) { TypeId allocated = typeVars.allocate(std::move(tv)); if (FFlag::DebugLuauTrackOwningArena) asMutable(allocated)->owningArena = this; return allocated; } TypeId TypeArena::freshType(TypeLevel level) { TypeId allocated = typeVars.allocate(FreeTypeVar{level}); if (FFlag::DebugLuauTrackOwningArena) asMutable(allocated)->owningArena = this; return allocated; } TypePackId TypeArena::addTypePack(std::initializer_list<TypeId> types) { TypePackId allocated = typePacks.allocate(TypePack{std::move(types)}); if (FFlag::DebugLuauTrackOwningArena) asMutable(allocated)->owningArena = this; return allocated; } TypePackId TypeArena::addTypePack(std::vector<TypeId> types) { TypePackId allocated = typePacks.allocate(TypePack{std::move(types)}); if (FFlag::DebugLuauTrackOwningArena) asMutable(allocated)->owningArena = this; return allocated; } TypePackId TypeArena::addTypePack(TypePack tp) { TypePackId allocated = typePacks.allocate(std::move(tp)); if (FFlag::DebugLuauTrackOwningArena) asMutable(allocated)->owningArena = this; return allocated; } TypePackId TypeArena::addTypePack(TypePackVar tp) { TypePackId allocated = typePacks.allocate(std::move(tp)); if (FFlag::DebugLuauTrackOwningArena) asMutable(allocated)->owningArena = this; return allocated; } namespace { struct TypePackCloner; /* * Both TypeCloner and TypePackCloner work by depositing the requested type variable into the appropriate 'seen' set. * They do not return anything because their sole consumer (the deepClone function) already has a pointer into this storage. */ struct TypeCloner { TypeCloner(TypeArena& dest, TypeId typeId, SeenTypes& seenTypes, SeenTypePacks& seenTypePacks, CloneState& cloneState) : dest(dest) , typeId(typeId) , seenTypes(seenTypes) , seenTypePacks(seenTypePacks) , cloneState(cloneState) { } TypeArena& dest; TypeId typeId; SeenTypes& seenTypes; SeenTypePacks& seenTypePacks; CloneState& cloneState; template<typename T> void defaultClone(const T& t); void operator()(const Unifiable::Free& t); void operator()(const Unifiable::Generic& t); void operator()(const Unifiable::Bound<TypeId>& t); void operator()(const Unifiable::Error& t); void operator()(const PrimitiveTypeVar& t); void operator()(const SingletonTypeVar& t); void operator()(const FunctionTypeVar& t); void operator()(const TableTypeVar& t); void operator()(const MetatableTypeVar& t); void operator()(const ClassTypeVar& t); void operator()(const AnyTypeVar& t); void operator()(const UnionTypeVar& t); void operator()(const IntersectionTypeVar& t); void operator()(const LazyTypeVar& t); }; struct TypePackCloner { TypeArena& dest; TypePackId typePackId; SeenTypes& seenTypes; SeenTypePacks& seenTypePacks; CloneState& cloneState; TypePackCloner(TypeArena& dest, TypePackId typePackId, SeenTypes& seenTypes, SeenTypePacks& seenTypePacks, CloneState& cloneState) : dest(dest) , typePackId(typePackId) , seenTypes(seenTypes) , seenTypePacks(seenTypePacks) , cloneState(cloneState) { } template<typename T> void defaultClone(const T& t) { TypePackId cloned = dest.addTypePack(TypePackVar{t}); seenTypePacks[typePackId] = cloned; } void operator()(const Unifiable::Free& t) { cloneState.encounteredFreeType = true; TypePackId err = getSingletonTypes().errorRecoveryTypePack(getSingletonTypes().anyTypePack); TypePackId cloned = dest.addTypePack(*err); seenTypePacks[typePackId] = cloned; } void operator()(const Unifiable::Generic& t) { defaultClone(t); } void operator()(const Unifiable::Error& t) { defaultClone(t); } // While we are a-cloning, we can flatten out bound TypeVars and make things a bit tighter. // We just need to be sure that we rewrite pointers both to the binder and the bindee to the same pointer. void operator()(const Unifiable::Bound<TypePackId>& t) { TypePackId cloned = clone(t.boundTo, dest, seenTypes, seenTypePacks, cloneState); seenTypePacks[typePackId] = cloned; } void operator()(const VariadicTypePack& t) { TypePackId cloned = dest.addTypePack(TypePackVar{VariadicTypePack{clone(t.ty, dest, seenTypes, seenTypePacks, cloneState)}}); seenTypePacks[typePackId] = cloned; } void operator()(const TypePack& t) { TypePackId cloned = dest.addTypePack(TypePack{}); TypePack* destTp = getMutable<TypePack>(cloned); LUAU_ASSERT(destTp != nullptr); seenTypePacks[typePackId] = cloned; for (TypeId ty : t.head) destTp->head.push_back(clone(ty, dest, seenTypes, seenTypePacks, cloneState)); if (t.tail) destTp->tail = clone(*t.tail, dest, seenTypes, seenTypePacks, cloneState); } }; template<typename T> void TypeCloner::defaultClone(const T& t) { TypeId cloned = dest.addType(t); seenTypes[typeId] = cloned; } void TypeCloner::operator()(const Unifiable::Free& t) { cloneState.encounteredFreeType = true; TypeId err = getSingletonTypes().errorRecoveryType(getSingletonTypes().anyType); TypeId cloned = dest.addType(*err); seenTypes[typeId] = cloned; } void TypeCloner::operator()(const Unifiable::Generic& t) { defaultClone(t); } void TypeCloner::operator()(const Unifiable::Bound<TypeId>& t) { TypeId boundTo = clone(t.boundTo, dest, seenTypes, seenTypePacks, cloneState); seenTypes[typeId] = boundTo; } void TypeCloner::operator()(const Unifiable::Error& t) { defaultClone(t); } void TypeCloner::operator()(const PrimitiveTypeVar& t) { defaultClone(t); } void TypeCloner::operator()(const SingletonTypeVar& t) { defaultClone(t); } void TypeCloner::operator()(const FunctionTypeVar& t) { TypeId result = dest.addType(FunctionTypeVar{TypeLevel{0, 0}, {}, {}, nullptr, nullptr, t.definition, t.hasSelf}); FunctionTypeVar* ftv = getMutable<FunctionTypeVar>(result); LUAU_ASSERT(ftv != nullptr); seenTypes[typeId] = result; for (TypeId generic : t.generics) ftv->generics.push_back(clone(generic, dest, seenTypes, seenTypePacks, cloneState)); for (TypePackId genericPack : t.genericPacks) ftv->genericPacks.push_back(clone(genericPack, dest, seenTypes, seenTypePacks, cloneState)); ftv->tags = t.tags; ftv->argTypes = clone(t.argTypes, dest, seenTypes, seenTypePacks, cloneState); ftv->argNames = t.argNames; ftv->retType = clone(t.retType, dest, seenTypes, seenTypePacks, cloneState); } void TypeCloner::operator()(const TableTypeVar& t) { // If table is now bound to another one, we ignore the content of the original if (t.boundTo) { TypeId boundTo = clone(*t.boundTo, dest, seenTypes, seenTypePacks, cloneState); seenTypes[typeId] = boundTo; return; } TypeId result = dest.addType(TableTypeVar{}); TableTypeVar* ttv = getMutable<TableTypeVar>(result); LUAU_ASSERT(ttv != nullptr); *ttv = t; seenTypes[typeId] = result; ttv->level = TypeLevel{0, 0}; for (const auto& [name, prop] : t.props) ttv->props[name] = {clone(prop.type, dest, seenTypes, seenTypePacks, cloneState), prop.deprecated, {}, prop.location, prop.tags}; if (t.indexer) ttv->indexer = TableIndexer{clone(t.indexer->indexType, dest, seenTypes, seenTypePacks, cloneState), clone(t.indexer->indexResultType, dest, seenTypes, seenTypePacks, cloneState)}; for (TypeId& arg : ttv->instantiatedTypeParams) arg = clone(arg, dest, seenTypes, seenTypePacks, cloneState); for (TypePackId& arg : ttv->instantiatedTypePackParams) arg = clone(arg, dest, seenTypes, seenTypePacks, cloneState); if (ttv->state == TableState::Free) { cloneState.encounteredFreeType = true; ttv->state = TableState::Sealed; } ttv->definitionModuleName = t.definitionModuleName; ttv->methodDefinitionLocations = t.methodDefinitionLocations; ttv->tags = t.tags; } void TypeCloner::operator()(const MetatableTypeVar& t) { TypeId result = dest.addType(MetatableTypeVar{}); MetatableTypeVar* mtv = getMutable<MetatableTypeVar>(result); seenTypes[typeId] = result; mtv->table = clone(t.table, dest, seenTypes, seenTypePacks, cloneState); mtv->metatable = clone(t.metatable, dest, seenTypes, seenTypePacks, cloneState); } void TypeCloner::operator()(const ClassTypeVar& t) { TypeId result = dest.addType(ClassTypeVar{t.name, {}, std::nullopt, std::nullopt, t.tags, t.userData}); ClassTypeVar* ctv = getMutable<ClassTypeVar>(result); seenTypes[typeId] = result; for (const auto& [name, prop] : t.props) ctv->props[name] = {clone(prop.type, dest, seenTypes, seenTypePacks, cloneState), prop.deprecated, {}, prop.location, prop.tags}; if (t.parent) ctv->parent = clone(*t.parent, dest, seenTypes, seenTypePacks, cloneState); if (t.metatable) ctv->metatable = clone(*t.metatable, dest, seenTypes, seenTypePacks, cloneState); } void TypeCloner::operator()(const AnyTypeVar& t) { defaultClone(t); } void TypeCloner::operator()(const UnionTypeVar& t) { if (FFlag::LuauPrepopulateUnionOptionsBeforeAllocation) { std::vector<TypeId> options; options.reserve(t.options.size()); for (TypeId ty : t.options) options.push_back(clone(ty, dest, seenTypes, seenTypePacks, cloneState)); TypeId result = dest.addType(UnionTypeVar{std::move(options)}); seenTypes[typeId] = result; } else { TypeId result = dest.addType(UnionTypeVar{}); seenTypes[typeId] = result; UnionTypeVar* option = getMutable<UnionTypeVar>(result); LUAU_ASSERT(option != nullptr); for (TypeId ty : t.options) option->options.push_back(clone(ty, dest, seenTypes, seenTypePacks, cloneState)); } } void TypeCloner::operator()(const IntersectionTypeVar& t) { TypeId result = dest.addType(IntersectionTypeVar{}); seenTypes[typeId] = result; IntersectionTypeVar* option = getMutable<IntersectionTypeVar>(result); LUAU_ASSERT(option != nullptr); for (TypeId ty : t.parts) option->parts.push_back(clone(ty, dest, seenTypes, seenTypePacks, cloneState)); } void TypeCloner::operator()(const LazyTypeVar& t) { defaultClone(t); } } // anonymous namespace TypePackId clone(TypePackId tp, TypeArena& dest, SeenTypes& seenTypes, SeenTypePacks& seenTypePacks, CloneState& cloneState) { if (tp->persistent) return tp; RecursionLimiter _ra(&cloneState.recursionCount, FInt::LuauTypeCloneRecursionLimit); TypePackId& res = seenTypePacks[tp]; if (res == nullptr) { TypePackCloner cloner{dest, tp, seenTypes, seenTypePacks, cloneState}; Luau::visit(cloner, tp->ty); // Mutates the storage that 'res' points into. } return res; } TypeId clone(TypeId typeId, TypeArena& dest, SeenTypes& seenTypes, SeenTypePacks& seenTypePacks, CloneState& cloneState) { if (typeId->persistent) return typeId; RecursionLimiter _ra(&cloneState.recursionCount, FInt::LuauTypeCloneRecursionLimit); TypeId& res = seenTypes[typeId]; if (res == nullptr) { TypeCloner cloner{dest, typeId, seenTypes, seenTypePacks, cloneState}; Luau::visit(cloner, typeId->ty); // Mutates the storage that 'res' points into. // TODO: Make this work when the arena of 'res' might be frozen asMutable(res)->documentationSymbol = typeId->documentationSymbol; } return res; } TypeFun clone(const TypeFun& typeFun, TypeArena& dest, SeenTypes& seenTypes, SeenTypePacks& seenTypePacks, CloneState& cloneState) { TypeFun result; for (auto param : typeFun.typeParams) { TypeId ty = clone(param.ty, dest, seenTypes, seenTypePacks, cloneState); std::optional<TypeId> defaultValue; if (FFlag::LuauTypeAliasDefaults && param.defaultValue) defaultValue = clone(*param.defaultValue, dest, seenTypes, seenTypePacks, cloneState); result.typeParams.push_back({ty, defaultValue}); } for (auto param : typeFun.typePackParams) { TypePackId tp = clone(param.tp, dest, seenTypes, seenTypePacks, cloneState); std::optional<TypePackId> defaultValue; if (FFlag::LuauTypeAliasDefaults && param.defaultValue) defaultValue = clone(*param.defaultValue, dest, seenTypes, seenTypePacks, cloneState); result.typePackParams.push_back({tp, defaultValue}); } result.type = clone(typeFun.type, dest, seenTypes, seenTypePacks, cloneState); return result; } ScopePtr Module::getModuleScope() const { LUAU_ASSERT(!scopes.empty()); return scopes.front().second; } void freeze(TypeArena& arena) { if (!FFlag::DebugLuauFreezeArena) return; arena.typeVars.freeze(); arena.typePacks.freeze(); } void unfreeze(TypeArena& arena) { if (!FFlag::DebugLuauFreezeArena) return; arena.typeVars.unfreeze(); arena.typePacks.unfreeze(); } Module::~Module() { unfreeze(interfaceTypes); unfreeze(internalTypes); } bool Module::clonePublicInterface() { LUAU_ASSERT(interfaceTypes.typeVars.empty()); LUAU_ASSERT(interfaceTypes.typePacks.empty()); SeenTypes seenTypes; SeenTypePacks seenTypePacks; CloneState cloneState; ScopePtr moduleScope = getModuleScope(); moduleScope->returnType = clone(moduleScope->returnType, interfaceTypes, seenTypes, seenTypePacks, cloneState); if (moduleScope->varargPack) moduleScope->varargPack = clone(*moduleScope->varargPack, interfaceTypes, seenTypes, seenTypePacks, cloneState); for (auto& [name, tf] : moduleScope->exportedTypeBindings) tf = clone(tf, interfaceTypes, seenTypes, seenTypePacks, cloneState); for (TypeId ty : moduleScope->returnType) if (get<GenericTypeVar>(follow(ty))) *asMutable(ty) = AnyTypeVar{}; freeze(internalTypes); freeze(interfaceTypes); return cloneState.encounteredFreeType; } } // namespace Luau
cpp
/* ** Copyright 2012-2014 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : <EMAIL> */ #ifndef CCCP_PIPE_HANDLE_HH #define CCCP_PIPE_HANDLE_HH #include "com/centreon/connector/perl/namespace.hh" #include "com/centreon/handle.hh" CCCP_BEGIN() /** * @class pipe_handle pipe_handle.hh * "com/centreon/connector/perl/pipe_handle.hh" * @brief Wrap a pipe FD. * * Wrap a pipe file descriptor within a class. */ class pipe_handle : public handle { int _fd; public: pipe_handle(int fd = -1); ~pipe_handle() noexcept override; pipe_handle(pipe_handle const& ph) = delete; pipe_handle& operator=(pipe_handle const& ph) = delete; void close() noexcept override; static void close_all_handles(); native_handle get_native_handle() noexcept override; unsigned long read(void* data, unsigned long size) override; void set_fd(int fd); unsigned long write(void const* data, unsigned long size) override; }; CCCP_END() #endif // !CCCP_PIPE_HANDLE_HH
cpp
package everyos.bot.luwu.run.command.modules.chatlink.channel; import java.util.Map; import java.util.function.Consumer; import everyos.bot.chat4j.entity.ChatChannel; import everyos.bot.luwu.core.database.DBDocument; import everyos.bot.luwu.core.database.DBObject; import everyos.bot.luwu.core.entity.Channel; import everyos.bot.luwu.core.entity.Connection; import reactor.core.publisher.Mono; public class LinkChannel extends Channel { public LinkChannel(Connection connection, ChatChannel channel, Map<String, DBDocument> documents) { super(connection, channel, documents); } public Mono<LinkChannelInfo> getInfo() { return getGlobalDocument().map(channelDoc->{ DBObject channelData = channelDoc.getObject().getOrCreateObject("data", obj->{}); return new LinkChannelInfoImp(getConnection().getBotEngine(), channelData); }); } public Mono<Void> edit(Consumer<LinkChannelEditSpec> func) { return getGlobalDocument().flatMap(channelDoc->{ DBObject channelData = channelDoc.getObject().getOrCreateObject("data", obj->{}); func.accept(new LinkChannelEditSpecImp(channelData)); channelDoc.getObject().set("type", "chatlink"); return channelDoc.save(); }); } public static final LinkChannelFactory type = new LinkChannelFactory(); }
java
[{"internalId":"Class3: Test1","name":"Class3: Test1"},{"internalId":"Class3: Test2","name":"Class3: Test2"},{"internalId":"Class3: Test3","name":"Class3: Test3"},{"internalId":"Class2: IgnoredTest","name":"Class2: IgnoredTest"},{"internalId":"Class2: SyncTest","name":"Class2: SyncTest"},{"internalId":"Class2: Test1","name":"Class2: Test1"},{"internalId":"Class2: Test2","name":"Class2: Test2"},{"internalId":"Class2: Test3","name":"Class2: Test3"},{"internalId":"Class2: Test3FailedWithoutMessage","name":"Class2: Test3FailedWithoutMessage"},{"internalId":"Class2: Test4","name":"Class2: Test4"},{"internalId":"Class2: TestWithTestCaseSource(0)","name":"Class2: TestWithTestCaseSource(0)"},{"internalId":"Class2: TestWithTestCaseSource(1)","name":"Class2: TestWithTestCaseSource(1)"},{"internalId":"Class2: TestWithTestCaseSource(2)","name":"Class2: TestWithTestCaseSource(2)"},{"internalId":"Class1: AttachmentsAreOptional","name":"Class1: AttachmentsAreOptional"},{"internalId":"Class1: Test1","name":"Class1: Test1"},{"internalId":"Class1: Test2","name":"Class1: Test2"},{"internalId":"Class1: Test3","name":"Class1: Test3"},{"internalId":"Class1: Test4","name":"Class1: Test4"},{"internalId":"FailedClass: Test1","name":"FailedClass: Test1"},{"internalId":"FailedClass: Test2","name":"FailedClass: Test2"},{"internalId":"IgnoredClass: Test1","name":"IgnoredClass: Test1"},{"internalId":"IgnoredClass: Test2","name":"IgnoredClass: Test2"},{"internalId":"Class1: Test1","name":"Class1: Test1"},{"internalId":"Class1: Test2","name":"Class1: Test2"}]
json
{ "name": "@e11community/token-exporter", "version": "3.2.2", "description": "Find NPM auth tokens in HOME/.npmrc and export them as environment variables", "main": "./build/src/lib.js", "types": "./build/src/lib.d.ts", "files": [ "build/src/**/*", "scripts/**/*" ], "bin": { "npmrc-export": "./scripts/npmrc-export.js", "npmrc-write-cwd": "./scripts/npmrc-write-cwd.js" }, "scripts": { "atest": "jest ${0}", "build": "tsc", "build:watch": "tsc --watch", "clean": "gts clean", "fix": "gts fix", "lint": "gts lint", "publish": "yarn npm publish --access public", "publish:dev": "yarn npm publish --access public --tag dev", "test": "jest", "test:coverage": "jest --coverage", "version": "yarn version", "version:dev": "yarn version prerelease", "prepack": "yarn run clean && yarn run build", "pretest": "yarn run build", "posttest": "yarn run lint" }, "keywords": [ "auth", "token" ], "author": "Engineering 11", "license": "MIT", "bugs": { "url": "https://github.com/e11community/token-exporter/issues" }, "repository": { "url": "https://github.com/e11community/token-exporter", "type": "git" }, "homepage": "https://github.com/e11community/token-exporter#readme", "devDependencies": { "gts": "^3.1.0", "ts-node": "^10.1.0" }, "dependencies": { "@types/node": "^16.4.10", "typescript": "^4.3.5" } }
json
I was messing around on Facebook when a post popped in to my feed from Adidas that @slkav had shared. It immediately caught my eye because of the unusual size of the box so I naturally hit the play button and was very surprised at what I found. As you’ll see from the video below an interactive advert (or game depending on what way you look at it) appears and you are asked to scrape off the ice to reveal a shoe. Once you have revealed the shoe (should take about 4 seconds max) then a whole range of products open up that you can browse within your own wall without having to navigate away. Now anybody can add a flash game or widget to their wall but I haven’t seen a brand engaging in this way before especially with a different game 24 days running. Replacing Tabs? We were all shocked during the week when we saw that the new Facebook pages would remove the tabs at the top of the page where applications and games usually sit and moving them to a less prominent placement in the sidebar. Placing interactive content like this within the feed would be one way of getting around the fact that less people were viewing your tabs but at the same time I’m not sure people want to see every brand under the sun adding flash games to their feeds. It works as a one off campaign but I’m not sure this format would work on a regular basis. I have to take my hat off to Adidas here because this is a great, innovative way to increase interaction through the wall and engage users with their products. They have however fallen at the last hurdle because having a broken link through to the purchase page is just not acceptable especially at this busy time of year. That link has been broken for a full 24 hours now and with over a million likes and millions more like me seeing this through their wall that is just not acceptable. Remember Adidas’ Facebook Shoe? Get the most important tech news in your inbox each week.
english
Tesla Motors founder Martin Eberhard and current CEO Elon Musk have quietly settled their legal bickering, kissed and made up. No one's offering any details because the terms are confidential, but Tesla Motors confirmed that that two men have "resolved their dispute." That dispute, you'll recall, started when Eberhard filed a lawsuit in June accusing Musk of taking control of the company, orchestrating his ouster in 2007 and attempting to “rewrite history” to take credit for developing the Roadster. Musk didn't take kindly to that and asked a judge to toss the suit. The company argued that Eberhard was a poor CEO who “left the company’s finances in shambles” and said his complaints — which include libel, slander and breach of contract — were bogus. The judge declined to dismiss the suit in late July. Eberhard appeared to cry uncle late last month when he asked a judge to dismiss the suit. We guessed at the time that Eberhard and Musk were headed to mediation or binding arbitration, something Musk later confirmed in a New Yorker profile (subscription req.). Looks like they've worked it out, with back-slapping and kisses all around. The two men offered the following quotes through Tesla Motors: "I'm glad that we could put this behind us and direct all our energy toward making Tesla one of the great car companies of the 21st century," Musk said. "We can now focus on the most important issue: making electric vehicles successful, something we both are passionate about," Eberhard said. "As a co-founder of the company, Elon's contributions to Tesla have been extraordinary," said Eberhard. "Industry-changing efforts are virtually impossible. Without Martin's indispensable efforts, Tesla Motors would not be here today," said Musk. In other news, Tesla delivered its 700th Roadster last week.
english
<reponame>thotran2015/dash_app {"allele_string": "G/A", "transcript_consequences": [{"polyphen_score": 0, "variant_allele": "A", "cadd_raw": 0.249599, "cdna_end": 784, "sift_score": 1, "cdna_start": 784, "hgnc_id": 20001, "polyphen_prediction": "benign", "sift_prediction": "tolerated", "gerp++_rs": -0.388, "cds_start": 494, "protein_start": 165, "impact": "MODERATE", "consequence_terms": ["missense_variant"], "gene_id": "ENSG00000169174", "transcript_id": "ENST00000302118", "amino_acids": "R/Q", "codons": "cGg/cAg", "strand": 1, "phylop100way_vertebrate": 0.478, "canonical": 1, "cadd_phred": 6.546, "cds_end": 494, "gene_symbol": "PCSK9", "protein_end": 165, "gene_symbol_source": "HGNC", "biotype": "protein_coding"}, {"hgnc_id": 20001, "impact": "MODERATE", "protein_start": 165, "polyphen_prediction": "benign", "gerp++_rs": -0.388, "sift_prediction": "tolerated_low_confidence", "cds_start": 494, "variant_allele": "A", "cadd_raw": 0.249599, "polyphen_score": 0, "cdna_start": 574, "cdna_end": 574, "sift_score": 0.63, "phylop100way_vertebrate": 0.478, "gene_symbol_source": "HGNC", "biotype": "protein_coding", "cadd_phred": 6.546, "cds_end": 494, "protein_end": 165, "gene_symbol": "PCSK9", "transcript_id": "ENST00000452118", "gene_id": "ENSG00000169174", "consequence_terms": ["missense_variant"], "strand": 1, "amino_acids": "R/Q", "codons": "cGg/cAg"}, {"strand": 1, "cadd_raw": 0.249599, "variant_allele": "A", "transcript_id": "ENST00000490692", "consequence_terms": ["upstream_gene_variant"], "gene_id": "ENSG00000169174", "distance": 4317, "biotype": "processed_transcript", "gene_symbol_source": "HGNC", "impact": "MODIFIER", "gene_symbol": "PCSK9", "cadd_phred": 6.546, "hgnc_id": 20001}, {"strand": 1, "variant_allele": "A", "transcript_id": "ENST00000543384", "cadd_raw": 0.249599, "gene_id": "ENSG00000169174", "consequence_terms": ["intron_variant"], "gene_symbol_source": "HGNC", "impact": "MODIFIER", "biotype": "protein_coding", "cadd_phred": 6.546, "gene_symbol": "PCSK9", "hgnc_id": 20001}], "input": "1:g.55512290G>A", "id": "1:g.55512290G>A", "colocated_variants": [{"start": 55512290, "clin_sig": ["uncertain_significance"], "frequencies": {"A": {"gnomad": 2.785e-05, "gnomad_amr": 0, "gnomad_sas": 0, "gnomad_eas": 0, "amr": 0, "gnomad_oth": 0.0001631, "gnomad_asj": 0, "sas": 0, "eas": 0, "afr": 0.0008, "gnomad_fin": 0, "gnomad_nfe": 2.64e-05, "gnomad_afr": 0.0001846, "eur": 0}}, "id": "rs372165281", "strand": 1, "minor_allele": "A", "clin_sig_allele": "A:uncertain_significance", "end": 55512290, "phenotype_or_disease": 1, "allele_string": "G/A/T", "AA": "T:0", "minor_allele_freq": 0.0002, "EA": "T:0.0001163"}, {"somatic": 1, "id": "COSV56161201", "strand": 1, "allele_string": "COSMIC_MUTATION", "phenotype_or_disease": 1, "end": 55512290, "start": 55512290}], "strand": 1, "most_severe_consequence": "missense_variant", "assembly_name": "GRCh37", "start": 55512290, "end": 55512290, "seq_region_name": "1"}
json
const WebSocket = require('ws'); const open = require('open'); const got = require('got'); const Log = require('./logger'); const bell = require('./bell'); const { preWork, login, onLesson } = require('./config'); (() => new Promise((resolve, reject) => { const ws = new WebSocket('wss://www.yuketang.cn/wsapp/'); ws.onclose = (e) => { Log.error(e); }; ws.onopen = () => { Log.log('connection opening...'); got(...preWork.genForm()) .then((resp) => { Log.response(resp); }) .catch(err => Log.error(err)); (function getQRCode() { ws.send('{"op":"requestlogin","role":"web","version":1.4,"type":"qrcode"}'); if (ws.readyState === 1) { setTimeout(getQRCode, 30 * 1000); } // ws.readyState === 1 && setTimeout(getQRCode, 1000 * 30); }()); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); // console.log(data); if (data.op === 'requestlogin') { open(data.ticket); } if (data.op === 'loginsuccess') { ws.close(); Log.log('WebSocket Closed'); resolve({ Auth: data.Auth, UserID: data.UserID, }); } }; ws.onerror = (error) => { reject(error); }; }))() .then((data) => { bell(); return got.post(...login.genForm(data)); }) .then((resp) => { Log.response(resp); return got(...onLesson.genForm(null)); }) .then((resp) => { Log.response(resp); if (!resp.body.success) { throw Error('getting onLessons info wrong'); } // eslint-disable-next-line camelcase const { on_lesson } = resp.body.data; // eslint-disable-next-line camelcase if (!(on_lesson && on_lesson.length > 0)) { throw Error('getting onLessons info wrong'); } // eslint-disable-next-line camelcase if (on_lesson && on_lesson.length > 0) { bell(); } }) .catch(e => console.log(e));
javascript
Periods are dreadful enough, the cramps, the mood swings and so on, But the most annoying part is experiencing rashes and discomfort due to sanitary pads. Here are some alternatives that can help you prevent them. Rashes are one of the most prevalent disorders associated with menstruation. There isn't a single woman who hasn't had period rashes, but the reality is that they can be avoided. Here are five ways to prevent it. This is a matter of personal choice. The only way to know if a menstrual cup is the right device for you is to buy one and give it a try. A French woman lost her feet and parts of her fingers were amputated after she used a menstrual cup for too long which led to toxic shock syndrome.
english
{"stats":{"minecraft:custom":{"minecraft:jump":174,"minecraft:time_since_rest":4424,"minecraft:leave_game":1,"minecraft:crouch_one_cm":5065,"minecraft:deaths":1,"minecraft:sprint_one_cm":29183,"minecraft:play_time":20847,"minecraft:damage_taken":1840,"minecraft:time_since_death":4398,"minecraft:walk_one_cm":33518,"minecraft:sneak_time":2204,"minecraft:climb_one_cm":503,"minecraft:total_world_time":20847,"minecraft:fall_one_cm":46090,"minecraft:fly_one_cm":15045}},"DataVersion":2865}
json
from giung2.config import CfgNode _C = CfgNode() _C.MODEL = CfgNode() _C.MODEL.META_ARCHITECTURE = CfgNode() _C.MODEL.META_ARCHITECTURE.NAME = 'ImageClassificationModelBase' # preprocessing for ImageClassificationModelBase _C.MODEL.PIXEL_MEAN = [0.0, 0.0, 0.0,] _C.MODEL.PIXEL_STD = [1.0, 1.0, 1.0,] # ---------------------------------------------------------------------- # # Datasets # ---------------------------------------------------------------------- # _C.DATASETS = CfgNode() _C.DATASETS.NAME = 'CIFAR10' # root directory that contains datasets _C.DATASETS.ROOT = './datasets/' # random seed for SHUFFLE_INDICES _C.DATASETS.SEED = 42 # data augmentation for training _C.DATASETS.DATA_AUGMENTATION = 'STANDARD' # MNIST, FashionMNIST _C.DATASETS.MNIST = CfgNode() _C.DATASETS.MNIST.SHUFFLE_INDICES = False _C.DATASETS.MNIST.TRAIN_INDICES = [0, 50000,] _C.DATASETS.MNIST.VALID_INDICES = [50000, 60000,] # CIFAR10, CIFAR100 _C.DATASETS.CIFAR = CfgNode() _C.DATASETS.CIFAR.SHUFFLE_INDICES = False _C.DATASETS.CIFAR.TRAIN_INDICES = [0, 45000,] _C.DATASETS.CIFAR.VALID_INDICES = [45000, 50000,] # TinyImageNet200 _C.DATASETS.TINY = CfgNode() _C.DATASETS.TINY.SHUFFLE_INDICES = False _C.DATASETS.TINY.TRAIN_INDICES = [0, 90000,] _C.DATASETS.TINY.VALID_INDICES = [90000, 100000,] # ImageNet1k_x32, ImageNet1k_x64 _C.DATASETS.DOWNSAMPLED_IMAGENET = CfgNode() _C.DATASETS.DOWNSAMPLED_IMAGENET.SHUFFLE_INDICES = True _C.DATASETS.DOWNSAMPLED_IMAGENET.TRAIN_INDICES = [0, 1231167,] _C.DATASETS.DOWNSAMPLED_IMAGENET.VALID_INDICES = [1231167, 1281167,] # ImageNet1k _C.DATASETS.IMAGENET = CfgNode() _C.DATASETS.IMAGENET.SHUFFLE_INDICES = True _C.DATASETS.IMAGENET.TRAIN_INDICES = [0, 1231167,] _C.DATASETS.IMAGENET.VALID_INDICES = [1231167, 1281167,] _C.DATASETS.IMAGENET.ROOT = './datasets/ILSVRC2012/' # ---------------------------------------------------------------------- # # Backbone # ---------------------------------------------------------------------- # _C.MODEL.BACKBONE = CfgNode() _C.MODEL.BACKBONE.NAME = 'PreResNet' # ResNet, PreResNet _C.MODEL.BACKBONE.RESNET = CfgNode() _C.MODEL.BACKBONE.RESNET.IN_PLANES = 16 _C.MODEL.BACKBONE.RESNET.FIRST_BLOCK = CfgNode() _C.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_NORM_LAYER = False _C.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_ACTIVATION = False _C.MODEL.BACKBONE.RESNET.FIRST_BLOCK.USE_POOL_LAYER = False _C.MODEL.BACKBONE.RESNET.FIRST_BLOCK.CONV_KSP = [3, 1, 1,] _C.MODEL.BACKBONE.RESNET.FIRST_BLOCK.POOL_KSP = [3, 2, 1,] _C.MODEL.BACKBONE.RESNET.BLOCK = 'BasicBlock' _C.MODEL.BACKBONE.RESNET.SHORTCUT = 'ProjectionShortcut' _C.MODEL.BACKBONE.RESNET.NUM_BLOCKS = [4, 4, 4,] _C.MODEL.BACKBONE.RESNET.WIDEN_FACTOR = 1 _C.MODEL.BACKBONE.RESNET.CONV_LAYERS = 'Conv2d' _C.MODEL.BACKBONE.RESNET.NORM_LAYERS = 'BatchNorm2d' _C.MODEL.BACKBONE.RESNET.ACTIVATIONS = 'ReLU' # ResNeXt _C.MODEL.BACKBONE.RESNEXT = CfgNode() _C.MODEL.BACKBONE.RESNEXT.IN_PLANES = 64 _C.MODEL.BACKBONE.RESNEXT.GROUPS = 32 _C.MODEL.BACKBONE.RESNEXT.WIDTH_PER_GROUP = 4 _C.MODEL.BACKBONE.RESNEXT.FIRST_BLOCK = CfgNode() _C.MODEL.BACKBONE.RESNEXT.FIRST_BLOCK.USE_NORM_LAYER = True _C.MODEL.BACKBONE.RESNEXT.FIRST_BLOCK.USE_ACTIVATION = True _C.MODEL.BACKBONE.RESNEXT.FIRST_BLOCK.USE_POOL_LAYER = True _C.MODEL.BACKBONE.RESNEXT.FIRST_BLOCK.CONV_KSP = [7, 2, 3,] _C.MODEL.BACKBONE.RESNEXT.FIRST_BLOCK.POOL_KSP = [3, 2, 1,] _C.MODEL.BACKBONE.RESNEXT.BLOCK = 'BottleneckBlock' _C.MODEL.BACKBONE.RESNEXT.SHORTCUT = 'ProjectionShortcut' _C.MODEL.BACKBONE.RESNEXT.NUM_BLOCKS = [3, 4, 6, 3,] _C.MODEL.BACKBONE.RESNEXT.WIDEN_FACTOR = 1 _C.MODEL.BACKBONE.RESNEXT.CONV_LAYERS = 'Conv2d' _C.MODEL.BACKBONE.RESNEXT.NORM_LAYERS = 'BatchNorm2d' _C.MODEL.BACKBONE.RESNEXT.ACTIVATIONS = 'ReLU' # VGGNet _C.MODEL.BACKBONE.VGGNET = CfgNode() _C.MODEL.BACKBONE.VGGNET.DEPTH = 16 _C.MODEL.BACKBONE.VGGNET.IN_PLANES = 64 _C.MODEL.BACKBONE.VGGNET.MLP_HIDDENS = [4096, 4096,] _C.MODEL.BACKBONE.VGGNET.CONV_LAYERS = 'Conv2d' _C.MODEL.BACKBONE.VGGNET.NORM_LAYERS = 'NONE' _C.MODEL.BACKBONE.VGGNET.ACTIVATIONS = 'ReLU' _C.MODEL.BACKBONE.VGGNET.LINEAR_LAYERS = 'Linear' # LeNet _C.MODEL.BACKBONE.LENET = CfgNode() _C.MODEL.BACKBONE.LENET.CONV_LAYERS = 'Conv2d' _C.MODEL.BACKBONE.LENET.ACTIVATIONS = 'Sigmoid' _C.MODEL.BACKBONE.LENET.LINEAR_LAYERS = 'Linear' # VisionTransformer _C.MODEL.BACKBONE.VIT = CfgNode() _C.MODEL.BACKBONE.VIT.PATCH_SIZE = 16 _C.MODEL.BACKBONE.VIT.HIDDEN_SIZE = 768 _C.MODEL.BACKBONE.VIT.TRANSFORMER = CfgNode() _C.MODEL.BACKBONE.VIT.TRANSFORMER.MLP_DIM = 3072 _C.MODEL.BACKBONE.VIT.TRANSFORMER.NUM_HEADS = 12 _C.MODEL.BACKBONE.VIT.TRANSFORMER.NUM_LAYERS = 12 _C.MODEL.BACKBONE.VIT.TRANSFORMER.DROPOUT_RATE = 0.0 _C.MODEL.BACKBONE.VIT.TRANSFORMER.ATTENTION_DROPOUT_RATE = 0.0 # ---------------------------------------------------------------------- # # Classifier # ---------------------------------------------------------------------- # _C.MODEL.CLASSIFIER = CfgNode() _C.MODEL.CLASSIFIER.NAME = 'SoftmaxClassifier' # SoftmaxClassifier _C.MODEL.CLASSIFIER.SOFTMAX_CLASSIFIER = CfgNode() _C.MODEL.CLASSIFIER.SOFTMAX_CLASSIFIER.NUM_CLASSES = 10 _C.MODEL.CLASSIFIER.SOFTMAX_CLASSIFIER.NUM_HEADS = 1 _C.MODEL.CLASSIFIER.SOFTMAX_CLASSIFIER.USE_BIAS = True _C.MODEL.CLASSIFIER.SOFTMAX_CLASSIFIER.LINEAR_LAYERS = 'Linear' # ---------------------------------------------------------------------- # # Batch Normalization # ---------------------------------------------------------------------- # _C.MODEL.BATCH_NORMALIZATION = CfgNode() _C.MODEL.BATCH_NORMALIZATION.EPSILON = 1e-5 _C.MODEL.BATCH_NORMALIZATION.MOMENTUM = 0.9 # ---------------------------------------------------------------------- # # Layer Normalization # ---------------------------------------------------------------------- # _C.MODEL.LAYER_NORMALIZATION = CfgNode() _C.MODEL.LAYER_NORMALIZATION.EPSILON = 1e-5 # ---------------------------------------------------------------------- # # Group Normalization # ---------------------------------------------------------------------- # _C.MODEL.GROUP_NORMALIZATION = CfgNode() _C.MODEL.GROUP_NORMALIZATION.EPSILON = 1e-5 _C.MODEL.GROUP_NORMALIZATION.NUM_GROUPS = 32 # ---------------------------------------------------------------------- # # Filter Response Normalization # ---------------------------------------------------------------------- # _C.MODEL.FILTER_RESPONSE_NORMALIZATION = CfgNode() _C.MODEL.FILTER_RESPONSE_NORMALIZATION.EPSILON = 1e-6 _C.MODEL.FILTER_RESPONSE_NORMALIZATION.USE_LEARNABLE_EPSILON = False # ---------------------------------------------------------------------- # # Dropout # ---------------------------------------------------------------------- # _C.MODEL.DROPOUT = CfgNode() _C.MODEL.DROPOUT.DROP_RATE = 0.5 # ---------------------------------------------------------------------- # # BatchEnsemble # ---------------------------------------------------------------------- # _C.MODEL.BATCH_ENSEMBLE = CfgNode() # the size of ensembles _C.MODEL.BATCH_ENSEMBLE.ENSEMBLE_SIZE = 4 # initialization of rank-one factors _C.MODEL.BATCH_ENSEMBLE.INITIALIZER = CfgNode() _C.MODEL.BATCH_ENSEMBLE.INITIALIZER.NAME = "normal" _C.MODEL.BATCH_ENSEMBLE.INITIALIZER.VALUES = [1.0, 1.0,]
python
- The Lucknow-Delhi Tejas Expres has a capacity of carrying 758 passengers. New Delhi: India's first private train Lucknow-Delhi-Lucknow Tejas Express Lucknow was flagged off by Uttar Pradesh Chief Minister Yogi Adityanath at Lucknow on October 4. The commercial run for Delhi to Lucknow Tejas Express started commercial operations from October 5, 2019. Train number 82502 IRCTC Tejas Express New Delhi-Lucknow runs six days of the week except on Tuesday. Tt may be noted after the success of first private train Delhi-Lucknow Tejas Express, the government is now planning to hand over the development of 50 railway stations and operations of about 150 trains to private players. However, according to top railway officials cited in a report, country’s first private train has violated the tariff law under the Railways Act, 1989, since the Central government is the only competent authority to decide on tariff and not the IRCTC. IRCTC is not empowered to fix the tariff, the officials added. “If a non-Government railway fails to comply with, any requisition made, decision or direction given, by the Central Government, under any of the provisions of this Act, or otherwise contravenes any of the provisions of this Act, it shall be open to the Central Government, by order, to levy a penalty not exceeding two hundred and fifty rupees and a further penalty not exceeding one hundred and fifty rupees for every day during which the contravention continues. . . ”, this means as per Section 169 of the Act, violation of these rules by a non-Governmental railway, like the private train, would attract penalty. It is worth mentioning that the ticket of Train number 82501 IRCTC Tejas Express Lucknow to Delhi Executive Chair Car is priced at Rs 2,310. AC Chair car (CC) ticket, on the other hand, will cost you Rs 1,505. Train Number 82502 IRCTC Tejas Express ticket for Executive Chair Car (EC) will cost you Rs 2,450. The AC Chair car (CC) ticket is priced at Rs 1,755. Compared to this, Train No 12004 Delhi-Lucknow Shatabdi Express, which takes 6 hours 35 minutes to cover the same distance, charges Rs 1,855 for AC Executive Class and Rs 1,165 for the AC Chair Car including GST, Super Fast and reservation charges. The tariff for AC Chair Car for the Suhaildev Super Fast Express and Garib Rath Express on the same route is Rs 645 and Rs 480 respectively. According to senior railway officials, the tariff fixed is apparently in violation of the Railways Act. Also, the fares are higher even though there is hardly any change in the running time. Worth mentioning here is that the train has nine AC chair car coaches and one executive class air-conditioned chair car coach. The executive class air-conditioned chair car coach has a total of 56 seats. Nine AC chair car coaches have 78 seats each. The Lucknow-Delhi Tejas Expres has a capacity of carrying 758 passengers.
english
Weeks after 20 Indian soldiers were killed in violent clashes with Chinese soldiers at Galwan, Prime Minister Narendra Modi Friday arrived in Leh, Ladakh to review the ongoing border conflict. This is the first high profile visit from the executive leadership to the region ever since the border standoff erupted in early May. The Prime Minister, accompanied by Chief of Defence Staff General Bipin Rawat and Army Chief General MM Naravane, arrived at Nimu this morning and interacted with Army, Air Force and ITBP personnel. (Twitter/BJP) Modi was accompanied by Chief of Defence Staff General Bipin Rawat and Army Chief General MM Naravane, at Nimu and the trio interacted with Army, Air Force and ITBP personnel this morning. Indian and Chinese troops have been involved in a face-off at multiple locations in the region. The friction points include North bank of Pangong Tso, Hot Springs, Vohra Post and Galwan Valley. While at Pangong Tso, China has built substantial structures till Finger 4, which is 8 km west of India’s claim of LAC at Finger 8; they have also built some structures at Patrolling Point 14 in the Galwan Valley. “India’s enemies have seen your fire and fury. Those who are weak can never initiate peace. Bravery is a pre-requisite for peace. Your will power is as strong and firm as Himalayas; the whole country is proud of you," Modi added.
english
<filename>public/css/cardfaces.css .cardc .cardicon.Bishop .ci.head { width: 70px; height: 70px; top: 40px; border-radius: 1000px; left: 35px; background-color: rgb(225, 207, 2); } .cardc .cardicon.Bishop .ci.hat { width: 70px; height: 20px; border-radius: 10px; left: 0px; background-color: rgb(26, 66, 151); } .cardc .cardicon.Bishop .ci.hat-top { height: 15px; left: 10px; border-radius: 7px; top: -2px; width: 50px; background-color: rgb(51, 88, 166); } .cardc .cardicon.Bishop .ci.hat-bottom { width: 60px; height: 3px; border-radius: 5px; top: 14px; left: 5px; background-color: rgba(228, 223, 223, 0.85098); border-top: 2px dotted #ddffee; border-bottom: 1px solid #ffffff; } .cardc .cardicon.Bishop .ci.eyes { width: 50px; height: 5px; left: 10px; top: 28px; background-color: rgba(0, 0, 0, 0); } .cardc .cardicon.Bishop .ci.eye-left { border-radius: 40px; width: 8px; height: 6px; left: 4px; background-color: rgb(7, 44, 35); } .cardc .cardicon.Bishop .ci.eye-right { width: 8px; height: 6px; right: 4px; border-radius: 40px; background-color: rgb(7, 44, 35); } .cardc .cardicon.Bishop .ci.mouth { width: 10px; height: 3px; border-radius: 4px; left: 30px; top: 50px; background-color: rgba(106, 73, 11, 0.8); } .cardc .cardicon.Bishop2 .ci.head { width: 70px; height: 70px; top: 40px; border-radius: 1000px; left: 35px; background-color: rgb(225, 171, 2); } .cardc .cardicon.Bishop2 .ci.hat { width: 70px; height: 20px; border-radius: 10px; left: 0px; background-color: rgb(26, 26, 151); } .cardc .cardicon.Bishop2 .ci.hat-top { height: 15px; left: 10px; border-radius: 7px; top: -2px; width: 50px; background-color: rgb(51, 63, 166); } .cardc .cardicon.Bishop2 .ci.hat-bottom { width: 60px; height: 3px; border-radius: 4px; top: 14px; left: 5px; border-top-width: 2px; border-top-style: dotted; border-top-color: rgb(221, 255, 238); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(255, 255, 255); background-color: rgba(197, 96, 96, 0.85098); } .cardc .cardicon.Bishop2 .ci.hair { background-color: rgb(0, 0, 0); } .cardc .cardicon.Bishop2 .ci.eyes { width: 50px; height: 5px; left: 10px; top: 28px; background-color: rgba(0, 0, 0, 0); } .cardc .cardicon.Bishop2 .ci.eye-left { border-radius: 40px; width: 8px; height: 6px; left: 4px; background-color: rgb(7, 44, 35); } .cardc .cardicon.Bishop2 .ci.eye-right { width: 8px; height: 6px; right: 4px; border-radius: 40px; background-color: rgb(7, 44, 35); } .cardc .cardicon.Bishop2 .ci.mouth { width: 15px; height: 1px; border-radius: 7px; left: 23px; top: 47px; bottom: 40px; right: 40px; background-color: rgba(106, 73, 11, 0.8); } .cardc .cardicon.Bishop3 .ci.head { width: 70px; height: 70px; top: 40px; border-radius: 1000px; left: 35px; background-color: rgb(165, 126, 7); } .cardc .cardicon.Bishop3 .ci.hat { width: 70px; height: 20px; border-radius: 10px; left: 0px; top: 0px; background-color: rgb(26, 26, 151); } .cardc .cardicon.Bishop3 .ci.hat-top { height: 15px; left: 10px; border-radius: 7px; top: 4px; width: 50px; background-color: rgb(51, 63, 166); } .cardc .cardicon.Bishop3 .ci.hat-bottom { width: 60px; height: 3px; border-radius: 4px; top: 15px; left: 5px; border-top-width: 2px; border-top-style: dotted; border-top-color: rgb(221, 255, 238); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(255, 255, 255); background-color: rgba(197, 96, 96, 0.85098); } .cardc .cardicon.Bishop3 .ci.hair { background-color: rgb(0, 0, 0); } .cardc .cardicon.Bishop3 .ci.eyes { width: 50px; height: 5px; left: 10px; top: 28px; background-color: rgba(0, 0, 0, 0); } .cardc .cardicon.Bishop3 .ci.eye-left { border-radius: 40px; width: 8px; height: 6px; left: 4px; background-color: rgb(7, 44, 35); } .cardc .cardicon.Bishop3 .ci.eye-right { width: 8px; height: 6px; right: 4px; border-radius: 40px; background-color: rgb(7, 44, 35); } .cardc .cardicon.Bishop3 .ci.mouth { width: 31px; height: 2px; border-radius: 7px; left: 20px; top: 37px; bottom: 40px; right: 40px; background-color: rgba(90, 65, 4, 0.8); } .cardc .cardicon.Bishop3 .ci.lower-lip { width: 12px; height: 2px; top: 0px; bottom: 4px; left: 12px; border-radius: 2px; background-color: rgba(255, 255, 255, 0.85098); } .cardc .cardicon.Bishop3 .ci.shoulders { width: 66px; height: 10px; top: 95px; left: 36px; border-radius: 4px; background-color: rgb(5, 19, 87); } .cardc .cardicon.Bishop3 .ci.shoulder-left { width: 30px; height: 16px; top: 6px; left: -20px; border-radius: 10px; background-color: rgb(225, 127, 34); } .cardc .cardicon.Bishop3 .ci.shoulder-right { width: 30px; height: 16px; top: 6px; bottom: 12px; left: 54px; right: 56px; border-radius: 10px; background-color: rgb(225, 127, 34); } .cardc .cardicon.Bishop3 .ci.body { width: 80px; height: 50px; top: 98px; bottom: 200px; left: 28px; border-radius: 5px; background-color: rgb(0, 20, 122); } .cardc .cardicon.Bishop3 .ci.zipper { width: 8px; height: 60px; left: 34px; background-color: rgb(11, 198, 227); }
css
<gh_stars>1-10 package confucius import ( "fmt" "io" "log" "runtime" ) type LogCallback func(level LogLevel, message string, file string, line int) type LogOption func(l *logger) type LogLevel int func (l LogLevel) String() string { switch l { case DebugLevel: return "DEBUG" case TraceLevel: return "TRACE" case InfoLevel: return "INFO" case WarningLevel: return "WARNING" case ErrorLevel: return "ERROR" case PanicLevel: return "PANIC" case FatalLevel: return "FATAL" } return "UNKNOWN" } const ( DebugLevel LogLevel = iota TraceLevel InfoLevel WarningLevel ErrorLevel PanicLevel FatalLevel ) func defaultLogger() *logger { return &logger{ level: DebugLevel, output: io.Discard, useCallback: false, callback: defaultCallback(io.Discard), } } func defaultCallback(output io.Writer) LogCallback { return func(level LogLevel, message string, file string, line int) { l := log.New(output, fmt.Sprintf("%-8s", level), log.LstdFlags) switch level { case PanicLevel: l.Panic(message) case FatalLevel: l.Fatal(message) default: l.Print(message) } } } func Callback(callback LogCallback) LogOption { return func(l *logger) { l.useCallback = true l.callback = callback l.output = io.Discard } } func SetLevel(level LogLevel) LogOption { return func(l *logger) { l.level = level } } func SetOutput(writer io.Writer) LogOption { return func(l *logger) { if !l.useCallback { l.output = writer l.callback = defaultCallback(writer) } else { l.Warn("log output feature is not usable when using callback") } } } type logger struct { useCallback bool callback LogCallback level LogLevel output io.Writer } func (l *logger) Print(level LogLevel, message string, args ...interface{}) { if level < l.level { return } msg := fmt.Sprintf(message, args...) if _, file, line, ok := runtime.Caller(2); ok { l.callback(level, msg, file, line) } else { l.callback(level, msg, "n/a", -1) } } func (l *logger) Debug(message string, args ...interface{}) { l.Print(DebugLevel, message, args...) } func (l *logger) Trace(message string, args ...interface{}) { l.Print(TraceLevel, message, args...) } func (l *logger) Info(message string, args ...interface{}) { l.Print(InfoLevel, message, args...) } func (l *logger) Warn(message string, args ...interface{}) { l.Print(WarningLevel, message, args...) } func (l *logger) Error(message string, args ...interface{}) { l.Print(ErrorLevel, message, args...) } func (l *logger) Fatal(message string, args ...interface{}) { l.Print(FatalLevel, message, args...) } func (l *logger) Panic(message string, args ...interface{}) { l.Print(PanicLevel, message, args...) }
go
Koh Nang Yuan - A paradisiacal phenomenon! Displaying the beauty of Punjab and its change of weather in a 'ting'. Paradise Is The Word Comes To My Mind After Seeing The Place .#WallpapersoftheSky. Clear Sky, Top View, Beach Life .Koh Nang Yuan Island - Thailand .
english
“I think I found coprolite mom. That’s dinosaur poop, you know.” I did, in fact, know what coprolite was – but I had no idea my five-year-old was so informed on the topic. On one of the hottest days of the summer, our family of five had embarked on the Fossil Safari offered in Dinosaur Provincial Park, a fossil hotbed in Alberta’s arid Badlands region. After a quick tour bus ride through the hoodoos, our guide offered an overview on the various fossils in the area, and admonitions about not handling or picking up the fossils, before allowing us to roam the area freely. As families discovered fossils scattered throughout the sandy ground, the guide wandered around helping us identify what we were looking at. If you have a wannabe palaeontologist, there are four great places to visit to discover your own Canadian fossils. At the Royal Tyrell Museum in Drumheller, Alberta visitors can enjoy a world-class museum and nearby hikes and walking trails. Numerous programs are available, suitable for all ages. In Dinosite, participants can search for fossils and see real dinosaur remains still in the ground in a 90-minute, 3km hike through the badlands. In the Dig Experience, participants use the tools and techniques of palaeontology to uncover fossil replicas in a simulated dig site. For those wanting to get their hands dirty, Dinosaur Provincial Park, a few hours from Drumheller, is where it’s at. A UNESCO World Heritage site where palaeontological digs continue today, the park contains one of the richest bonebeds in the world. Amongst the coulees and hoodoos, visitors can take part in guided fossil tours, like the family-friendly Fossil Safari we experienced, or join in a fully authentic dinosaur dig. These digs feature an experienced palaeontological technician and participants take part in excavating fossils, which are then donated to the Royal Tyrell Museum. The hilly region of Morden, Manitoba is rich in fossils from Late Cretaceous Period, 80 million years ago. The Canadian Fossil Discovery Centre conducts Fossil Dig Adventure Tours for children, families, and earth science enthusiasts of all ages. The 16,000 square foot museum houses the largest collection of marine reptile fossils in Canada, and holds the Guinness World Record for having the largest mosasaur on display in the world. Just be sure not to call them dinosaurs – these marine reptiles co-existed with dinosaurs, but aren’t classified as dinos. Near Hungry Hollow, Ontario, this 67-acre conservation area features natural trails, waterfalls and the Arkona Lions Museum. Well-known for its rich fossils dating 400 million years ago from the Devonian era, commonly found fossils include trilobites, brachiopods and crinoids. Evidence of ancient life can be found in this locality as well, as arrowheads, stone tools and pieces of pottery have been found in the area. Guided hikes and educational programs are available, though many prefer to take a self-guided tour. Digging for fossils is strictly forbidden, but visitors are permitted to take home one of each type of fossil they’ve found on the surface.
english
Thala Dhoni-led Chennai Super Kings forayed back to their home ground, Chepauk stadium in Chennai. CSK played an IPL match at the home pitch with the Tamil audience after almost four years. The Yellow Army played against Lucknow Super Giants last night. LSG won the toss and chose to field first. Ruturaj Gaikwad and Devon Conway gave a fiery start for CSK by scoring 80 runs in the powerplay. Rutu smashed 57 runs and Devon collected 47 runs. Shivam Dube, Moeen Ali and Ambati Rayudu scored 27, 19 and 27 respectively. Then, MS Dhoni came to the crease in the final over and smoked two sixes in Mark Wood's ball. CSK put 217 runs on the board at the end of 20 overs. CSK bowlers managed to defend and the Yellow brigade won by 12 runs. Moeen Ali and Mitchell Santner bowled an impressive spell. Ali took four wickets and only conceded 26 runs in four overs. On the downside, the fast bowlers bowled too many extras resulting in a slow over rate. 13 wides and 3 no-balls were bowled by CSK last night. Thala Dhoni talked about this issue at the post-match presentation. Dhoni said, "Fast bowling, we need to slightly improve. We need to bowl according to the conditions. One more thing is they'll have to bowl no no-balls or extra wides. Or they'll have to play under a new captain. It will be my second warning and then I'll be off. " Fans were shocked about the statement thinking that he is warning that he'll resign from the captaincy. But MS Dhoni was talking about the slow overrate consequences. As per the new IPL rules, the captain will face a one-match ban and have to pay a Rs 30 lakh fine if a team gets a slow overrate warning three times in the same season. He said that he has already received two warnings. MSD would have been fined Rs 12 lakh and Rs 24 lakh for the first two warnings. Follow us on Google News and stay updated with the latest!
english
{ "name": "@devpodio/modern-webpack-plugin", "version": "1.0.12", "description": "convert your assets to modern style", "publishConfig": { "access": "public" }, "main": "index.js", "repository": "https://github.com/devpodio/modern-webpack-plugin", "author": "<EMAIL>", "license": "Apache-2", "private": false, "dependencies": { "html-webpack-plugin": "^3.2.0" }, "devDependencies": { "debug": "^4.1.0" } }
json
When we will have to part. With those last words from my heart. We must be dreaming, For it has gone too fast. Will soon be in our past. I am but waiting for you. That seems just around the corner. And you will make it if you try. And never say goodbye.
english
h1 { font-family: 'Pacifico', cursive; font-size: 40px; } button { width: 50px; display: inline; } nav { height: 50px; } form { display: flex; align-items: center; } input { display: block; margin-top: 10px; padding: 0 10px; height: 40px; border: none; border-radius: 5px 0 0 5px; font-weight: bold; } input[type=submit] { background-color: green; color: white; border-radius: 0 5px 5px 0; } .search-bar { position: absolute; top: 10px; right: 30px; } .temperature { font-size: 100px; line-height: 105px; } .grid { display: grid; grid-template-columns: fit-content(500px) 1fr; grid-column-gap: 20px; } .column { display: flex; flex-direction: column; } .home { background-image: url("./images/clear.jpg"); background-size: cover; background-repeat: no-repeat; padding: 40px; height: 100vh; display: flex; flex-direction: column; justify-content: center; } .home.partly-cloudy { background-image: url("./images/Partly cloudy.jpg"); } .home.clear { background-image: url("./images/clear.jpg"); } .home.sunny { background-image: url("./images/sunny.jpg"); } .home-title { height: 100%; display: flex; flex-direction: column; justify-content: center; width: 50vw; } /* The switch - the box around the slider */ .switch { position: relative; display: flex; width: 60px; height: 34px; } /* Hide default HTML checkbox */ .switch input { opacity: 0; width: 0; height: 0; } /* The slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: 0.4s; transition: 0.4s; } .slider::before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: 0.4s; transition: 0.4s; } input:checked + .slider { background-color: #2196f3; } input:focus + .slider { box-shadow: 0 0 1px #2196f3; } input:checked + .slider::before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round::before { border-radius: 50%; } .flex { display: flex; align-items: center; }
css
The ATM kiosk in N. R. Square, where a bank employee was attacked in November, is being renovated. The Corporation Bank ATM kiosk is being painted and strengthened. The ATM machine, which had not been working for the past week, has been fixed. Following the early-morning attack on the woman, Jyothi Uday, while she was withdrawing money, the city police instructed banks to implement security measures at all ATM kiosks. These included immediately hiring guards, as well as installing alarm systems and CCTV cameras within 45 days. According to a guard at the N. R. Square kiosk, three unarmed guards are posted there in shifts of eight hours each. They have brought in a wooden plank for defence, a tactic employed by many ATM guards in the city. The kiosk also has CCTV cameras and alarm system, which would alert bank officials and the nearest police station in an emergency. However, a Corporation bank representative said that though the external CCTV camera had been installed, it posed a challenge as it required large storage capacity. The bank is yet to address the locking and unlocking system for the rolling shutter. This system had come in for criticism as the assailant had pulled down the shutters during and after the attack.
english
Kevin Pietersen and Matt Prior are not known to be particularly fond of each other, but when Prior announced his retirement both men showed they could be perfectly courteous to one another. Pietersen took to Twitter to congratulate Prior on his England career, and also wish him luck for the future. In response, Prior replied thanking Pietersen for the message. Pietersen and Prior’s bad blood can be traced back to the time when both men were still playing for England. Pietersen had Tweeted early in 2014, “Fewer Q&A’s, more Sussex nets methinks, @MattPrior! #josbuttler.” Prior hit back saying, “showing your class again Kevin... idiot.” He followed up with, “that will be why KP isn’t in the England set-up anymore.” Pietersen had also called Prior a “bully” and mocked him by calling him “The Big Cheese” in his autobiography. This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful. Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
english
/** * @author v.lugovksy * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.dashboard') .controller('DashboardPieChartCtrl', DashboardPieChartCtrl); /** @ngInject */ function DashboardPieChartCtrl($scope, $timeout, baConfig, baUtil, $http,$interval) { var config = { headers : { 'Content-Type': 'application/json;' } } var data = JSON.stringify({ apiKey:"<KEY>", command:"ChartOne", lang:"en", deviceId:"en2", viewData:{ fieldSet:{ }, whereFieldset:{ }, paging:{ Offset:0, Limit:10 } } }); var sum=0; var sum1=0; var visitors = 0; $http.post('http://raacom-factics-api.com/charts', data, config). then(function(response) { var maledata = response.data.male; var femaledata = response.data.female; var visitorsdata = response.data.visitor; for(var i=0; i<maledata.length ;i++){ sum+=maledata[i]; } for(var i=0; i<femaledata.length ;i++){ sum1+=femaledata[i]; } for(var i=0; i<visitorsdata.length ;i++){ visitors+=visitorsdata[i]; } chart_data(sum, sum1, visitors); }); $interval(function(){ var config = { headers : { 'Content-Type': 'application/json;' } } var data = JSON.stringify({ apiKey:"<KEY>", command:"ChartOne", lang:"en", deviceId:"en2", viewData:{ fieldSet:{ }, whereFieldset:{ }, paging:{ Offset:0, Limit:10 } } }); var sum=0; var sum1=0; var visitors = 0; $http.post('http://raacom-factics-api.com/charts', data, config). then(function(response) { var maledata = response.data.male; var femaledata = response.data.female; var visitorsdata = response.data.visitor; for(var i=0; i<maledata.length ;i++){ sum+=maledata[i]; } for(var i=0; i<femaledata.length ;i++){ sum1+=femaledata[i]; } for(var i=0; i<visitorsdata.length ;i++){ visitors+=visitorsdata[i]; } chart_data(sum, sum1, visitors); }); },15000); function chart_data(sum, sum1){ var pieColor = baUtil.hexToRGB(baConfig.colors.defaultText, 0.2); $scope.charts = [{ color: pieColor, description: 'Spotted Visitors', stats: visitors, icon: 'avatar', }, { color: pieColor, description: 'Spotted Males', stats: sum, icon: 'user', }, { color: pieColor, description: 'Spotted Females', stats: sum1, icon: 'woman', } ]; } function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } function loadPieCharts() { $('.chart').each(function () { var chart = $(this); chart.easyPieChart({ easing: 'easeOutBounce', onStep: function (from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); }, barColor: chart.attr('rel'), trackColor: 'rgba(0,0,0,0)', size: 84, scaleLength: 0, animation: 2000, lineWidth: 9, lineCap: 'round', }); }); $('.refresh-data').on('click', function () { updatePieCharts(); }); } function updatePieCharts() { $('.pie-charts .chart').each(function(index, chart) { $(chart).data('easyPieChart').update(getRandomArbitrary(55, 90)); }); } $timeout(function () { loadPieCharts(); updatePieCharts(); }, 1000); } })();
javascript
<reponame>yuwash/hextype { "name": "hextype", "version": "1.0.0", "description": "virtual keyboard based on six keys", "author": "<NAME> <<EMAIL>>", "license": "MIT", "scripts": { "start": "parcel src/index.html" }, "devDependencies": { "parcel-bundler": "^1.11.0", "parcel-plugin-svelte": "^4.0.5", "svelte": "^3.23.2" } }
json
# HorizontalScroll To implement HorizontalScroll component into your project you'll need to add the import: ```jsx import HorizontalScroll from "@kiwicom/orbit-components/lib/HorizontalScroll"; ``` After adding import into your project you can use it simply like: ```jsx <HorizontalScroll> <FirstComponent /> <SecondComponent /> <ThirdComponent /> ...etc </HorizontalScroll> ``` ## Props | Name | Type | Required | Default | Description | | ------------- | --------------------------- | ------------------ | ------- | ----------------------------------------- | | minHeight | `number` | | | set minimal height | | dataTest | `string` | | | prop for testing purposes | | spacing | [`Spacing`](#Spacing) | | "small" | the spacing between children elements | | children | `React.ReactNode` | :heavy_check_mark: | | content of HorizontalScroll | | scrollSnap | [`ScrollSnap`](#ScrollSnap) | | "none" | set value for `scroll-snap-type` property | | scrollPadding | `number` | | | set value for `scroll-padding` property | # ScrollSnap | ScrollSnap | | ------------- | | `"mandatory"` | | `"proximity"` | | `"inline"` | | `"none"` | # Spacing | Spacing | | ------------ | | `"none"` | | `"XXXSmall"` | | `"XXSmall"` | | `"XSmall"` | | `"small"` | | `"medium"` | | `"large"` | | `"XLarge"` | | `"XXLarge"` |
markdown
Claude Bigio is retired. To earn extra money she started a jewelry business about 7 years ago, but business she says is slow. But Claude also remembers her years working as a young woman, making a decent living. But times in Canada have surely changed, fast forward decades later and unemployment is at 7 point two percent, lower compared to the high rates during the recession, but teenagers and those in their early twenties are still being affected tremendously. A recent report by the CIBC suggests the future generation of Canadians is experiencing chronic unemployment. The youth unemployment rate is more than double the unemployment rate for Canadians aged 25 and older. With candles, hoodies, signs and anger, hundreds came to downtown Montreal\'s Square Phillips in solidarity with the Trayvon Martin family and to speak on what they believe was an obvious injustice in America when it came to the acquittal of George Zimmerman, who back in 2012 fatally shot 17-year-old, black, unarmed Trayvon Martin. For the hundreds of attendees the say the Trayvon Martin trial is not something exclusive to the United States and say racism also happens in Canada and when it comes to justice for brown people it\'s just us. Millions of people around the world have held demonstrations to mark the International Quds Day to show support for the Palestinian resistance against israel. The special relationship between Britain and America has taken a twist of the espionage kind - as the latest leak by American whistleblower Edward Snowden reveals that not only the two countries are closely working together to spy on citizens on both sides of the Atlantic, but also America has made secret payments of �100 million in just three years to secure access and influence over Britain\'s intelligence gathering programs. A large number of Afghans have staged a rally in the eastern city of Jalalabad to show their opposition to a possible security deal with the United States. Protesters say American forces are responsible for the deaths of many civilians in their country. Demonstrators also called on the participants of the Loya Jirga to reject a possible agreement. The Jirga is a gathering of elders from across Afghanistan which will decide on the fate of the deal next week. The deal between Kabul and Washington will allow thousands of American troops to stay in Afghanistan beyond 20-14. The issue of whether or not to grant legal immunity to American forces remains a sticking point. University students throughout Iran have joined in solidarity to show their support for the country\'s inalienable right to pursue nuclear technology for peaceful purposes. Several hundred students gathered outside Iran\'s Fordow Nuclear Facility to make the international community understand that Iran needs nuclear technology for civilian purposes. Students talked to us and explained why Iran is pursuing peaceful nuclear technology. Also in attendance was the head of Iran\'s Atomic Energy Organization (IAEO) Ali Akbar Salehi. In yet another show of anger at the US, Pakistan\'s Jaamat-e-Islami organization has drawn tens of thousands of people into the streets of Karachi to protest the American drone attacks in their country. The demonstration follows the blocking of NATO supplies in the northwestern city of Peshawar. Americans are backing a newly agreed accord with Iran by a vast margin. At the same time, polls show they are wary of military action against the Islamic Republic if diplomatic efforts fall short of goals. Reuters/Ipsos conducted the poll this week indicates that more Americans than previously thought, endorse a peaceful resolution with Iran over its diplomatic differences that have spanned decades. New revelations show that the chief Saudi spy, Prince Bandar bin Sultan is pushing ahead a campaign of persecution against Christians in Syria. Although the world is yet to react to this, it seems that Saudi rulers will soon have something new on their hands to worry about. This could be of particular significance, given that Riyadh will have to bear the brunt of any consequences for Prince bin Sultan\'s adventurism. Syrian people have held rallies to show solidarity with president Bashar al-Assad. Syrian people have held rallies to show solidarity with president Bashar al-Assad. The rallies were held in the capital Damascus and the town of Nabak. Similar demonstrations have frequently taken place during the past couple of years. Foreign-backed insurgents have repeatedly fired mortar shells and carried out bombings in urban and rural areas where they suspect people support the Damascus government. The attacks have caused heavy casualties. Are you looking for a special gift to give your loved one? Are you looking for a special gift to give your loved one? Why not try to create and crave your Art in cucumber Swan? Chocolate ganache: Chocolate filling: Allama Amin Shaheedi (MWM PAK)
english
<filename>js/tylkodlaswoich.js console.log('+++++++++++++++++++++++++++++') var opispost = function(ret){ zapisano = true; console.log('#5 opispost=',ret); console.log(zapisano); var modalx = document.getElementById("modalx"); modalx.innerHTML = '<p>Zapisano</p>'; modalx.style.display="block"; setTimeout(function(){ modalx.innerHTML = '?'; modalx.style.display="none"; },500); } var zapisano = false; setInterval(function(){ zapisano=false; //console.log(zapisano); },5000); function zapiszEdycje(editContent){ //if (zapisano) return; //console.log('zapiszEdycje'); //console.log(editContent); var posty = JSON.stringify(editContent); ajaxxPOST('./zapis.php',posty,opispost); } var saveEdit = function(ten){ if (this.id){ console.log(this.id,this.textContent) editContent.info[this.id]=this.textContent; } if (this.parentElement.nodeName==='TR'){ var txt = this.parentElement.textContent; var dzieciTabeli = this.parentElement.parentElement.children; var dzieciTR = this.parentElement.children; //console.log(dzieciTabeli); //console.log(dzieciTR.length,dzieciTR); var ktory = null; for (var c in dzieciTabeli){ if (typeof(dzieciTabeli[c])==='object'){ var toto = txt===dzieciTabeli[c].textContent; if (toto) ktory = c; //console.log(toto,c,txt,dzieciTabeli[c].textContent) } } var arr =[]; for (var c in dzieciTR){ if (typeof(dzieciTR[c])==='object'){ //console.log(dzieciTR[c],dzieciTR[c].textContent) arr.push(dzieciTR[c].textContent) } } } //console.log(arr); //console.log(ktory); //console.log(editContent.pokoje[ktory]); if (ktory){ editContent.pokoje[ktory].pietro = arr[0].trim(); editContent.pokoje[ktory].pokoj = arr[1].trim(); editContent.pokoje[ktory].kto = arr[2].trim(); } zapiszEdycje(editContent); } var edycjaTablicy = function(){ //document.designMode='on'; var atr = "contenteditable"; //console.log('atr=',atr); var edity = document.querySelectorAll("div#infoTAB table th,div#infoTAB table td, p.adres,h1 span,div#komunikat"); //console.log(edity); edity.forEach(function(y,i){ y.contentEditable = 'true'; y.addEventListener("input", saveEdit, false); }); } function refreshPage(){ console.log('refreshPage();') var posty = '{"budynek":"'+editContent.info.budynek+'"}'; //ajaxxPOST('./refresh.php','3',function(ret){ ajaxx('./refresh.php?step=6',function(ret){ console.log('refresh.php=',ret); }) } // DOM READY document.addEventListener('DOMContentLoaded', function() { setTimeout(function(){ edycjaTablicy(); document.body.insertAdjacentHTML('afterbegin', '<button onClick="document.location.href=\'./?tv=test\';">tv test</button>'); document.body.insertAdjacentHTML('afterbegin', '<button onClick="document.location.href=\'./?tv=WI2\';">tv WI2</button>'); document.body.insertAdjacentHTML('afterbegin', '<button onClick="document.location.href=\'./?tv=WI1\';">tv WI1</button>'); document.body.insertAdjacentHTML('afterbegin', '<button onClick="document.location.href=\'./\';">tv WIZUT</button>'); document.body.insertAdjacentHTML('afterbegin', '<button onClick="refreshPage();">refresh</button>'); },1500); }); //dom ready
javascript
<reponame>zn0507/config-keeper package com.suixingpay.config.server.service.impl; import com.jarvis.cache.annotation.CacheDeleteTransactional; import com.suixingpay.config.server.condition.ApplicationCondition; import com.suixingpay.config.server.entity.ApplicationDO; import com.suixingpay.config.server.mapper.ApplicationMapper; import com.suixingpay.config.server.service.ApplicationService; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author: qiujiayu[<EMAIL>] * @date: 2017年8月31日 下午11:29:57 * @version: V1.0 * @review: qiujiayu[<EMAIL>]/2017年8月31日 下午11:29:57 */ @Service @Transactional(readOnly = true, rollbackFor = Throwable.class) public class ApplicationServiceImpl implements ApplicationService { @Autowired private ApplicationMapper applicationMapper; @Override @Transactional(rollbackFor = Throwable.class) @CacheDeleteTransactional public void addApplication(@NonNull ApplicationDO application) { if (this.applicationMapper.addApplication(application) <= 0) { throw new RuntimeException("add application fail"); } } @Override @Transactional(rollbackFor = Throwable.class) @CacheDeleteTransactional public void updateApplication(@NonNull ApplicationDO application) { if (this.applicationMapper.updateApplication(application) <= 0) { throw new RuntimeException("update application fail"); } } @Override public ApplicationDO getByName(@NonNull String name) { return this.applicationMapper.getByName(name); } @Override public Long countByCondition(@NonNull ApplicationCondition condition) { return applicationMapper.countByCondition(condition); } @Override public List<ApplicationDO> listByCondition(@NonNull ApplicationCondition condition) { return applicationMapper.listByCondition(condition); } }
java
package paranoia.services.rnd; import paranoia.visuals.custom.ParanoiaImage; import javax.swing.JPanel; public class BonusDutyCard extends ParanoiaCard { private ParanoiaImage icon; public BonusDutyCard(Integer id){ super(CardType.BONUS_DUTY, id, -1); } @Override public String toString() { return null; } @Override public JPanel getVisual() { return this; } }
java
{"limit":100,"name":"White sq shield","value":1152,"highalch":691,"id":6631,"lowalch":460,"name_pt":"Escudo retangular branco","price":2636,"last":2636}
json
<filename>maps/gsiv/rooms/8485.json { "id": 8485, "title": [ "[Temple, High Priestess' Chamber]" ], "description": [ "The dust is thick in this once elegant room. The window remains in the pane, although cracks spider through the glass in crazed patterns, fragmenting your view of the outside. The bed has been ripped in half, and a small nightstand smashed against the wall. A white sheet lays draped over the featherbed like a shroud, and a ruined portrait leans in the corner, canvas ripped by four parallel slashes. A small white door stands open in the north wall." ], "paths": [ "Obvious exits: out" ], "location": "the Temple of Love", "wayto": { "8484": "out", "8486": "go door" }, "timeto": { "8484": 0.2, "8486": 0.2 }, "image": "wl-trollfang-1264234799.png", "image_coords": [ 37, 727, 47, 737 ] }
json
<filename>a4/src/cloud/assignments/a4/AmericanPutOption.java package cloud.assignments.a4; import java.util.ArrayList; public class AmericanPutOption { private int n; private double k, t, s, r, u, d; // Constants that need to be computed when we receive the above params // via the constructor. private double dt, p, disc, americanPutValue; private ArrayList<Double> stArrayList, cArrayList; public AmericanPutOption(double k, double t, double s, double r, int n, double u, double d) { this.k = k; this.t = t; this.s = s; this.r = r; this.n = n; this.u = u; this.d = d; this.americanPutValue = 0.0; this.disc = 0.0; stArrayList = new ArrayList<Double>(); cArrayList = new ArrayList<Double>(); } public double setAndReturnAmericanPutValue() { computeConstants(); initAssetPrices(); initOptionValuesAtMaturity(); applyEarlyExerciseCondition(); this.americanPutValue = cArrayList.get(0); return this.americanPutValue; } private void applyEarlyExerciseCondition() { for (int i = n-1; i >= 0; i--) { for (int j = 0; j < i; j++) { double val = disc * (p * cArrayList.get(j+1) + (1-p) * cArrayList.get(j)); cArrayList.set(j, val); double element = stArrayList.get(j) / d; stArrayList.set(j, element); cArrayList.set(j, Math.max(cArrayList.get(j), k - stArrayList.get(j))); } } } private void initOptionValuesAtMaturity() { for (int i = 0; i < this.n; i++) { cArrayList.add( Math.max(0.0, this.k - stArrayList.get(i))); } } private void initAssetPrices() { stArrayList.add(0, this.s * Math.pow(this.d, this.n)); for (int i = 1; i < this.n; i++) { stArrayList.add( stArrayList.get(i-1) * (this.u / this.d) ); } } private void computeConstants() { this.dt = this.dt / this.n; this.p = (Math.exp(this.r * this.dt) - this.d) / (this.u - this.d); this.disc = Math.exp(-this.r * this.dt); } }
java
<gh_stars>0 package com.circumgraph.storage.internal.mappers; import com.circumgraph.model.ObjectLocation; import com.circumgraph.model.OutputTypeDef; import com.circumgraph.storage.StoredObjectValue; import com.circumgraph.storage.StructuredValue; import com.circumgraph.storage.internal.StoredObjectValueImpl; import com.circumgraph.storage.mutation.StructuredMutation; import com.circumgraph.storage.types.ValueMapper; import reactor.core.publisher.Mono; /** * Mapper for root object stored in a {@link com.circumgraph.storage.Collection}. */ public class RootObjectMapper implements ValueMapper<StoredObjectValue, StructuredMutation> { private final ValueMapper<StructuredValue, StructuredMutation> mapper; public RootObjectMapper( ValueMapper<StructuredValue, StructuredMutation> mapper ) { this.mapper = mapper; } @Override public OutputTypeDef getDef() { return mapper.getDef(); } @Override public Mono<StoredObjectValue> applyMutation( MappingEncounter encounter, ObjectLocation location, StoredObjectValue previousValue, StructuredMutation mutation ) { return mapper.applyMutation( encounter, location, previousValue, mutation ).map(StoredObjectValueImpl::new); } }
java
We believe one should not look at indices, before concluding Indian markets are expensive. The additions to indices specially in large cap have mostly been costlier stocks making their past absolute valuations un-comparable. Indian seems to be in a Goldilocks situation with High Growth of corporate earnings, an ever growing macro economy contributing to ~15% of worlds incremental growth and witnessing start of a Capex cycle to help India become a manufacturing hub for the world. Themes we like are a) Power, b) Water c) Defense, d) Railways, e) ER&D and f) Chemicals. Stock Reports Plus, powered by Refinitiv, undertakes detailed company analysis for 4,000+ listed stocks. In addition to detailed company analysis, the report also collates analysts’ forecasts and trend analysis for each component. An average score in Stock Reports Plus is calculated by undertaking quantitative analysis of five key investment tools - earnings, fundamentals, relative valuation, risk and price momentum. It is a global phenomenon, when any new sector emerges, it gets extremely high valuation, then too much money flows into it. Then soon comes a phase of realization that it has become too hot to handle and then correction takes place which might take years. Microfinance companies have gone through this cycle. More than a decade back, first listing of a micro finance company was a massive success though it is a different matter very soon it was embroiled in a controversy and finally taken over by a large private bank. Since then a number of finance companies have got listed and after a phase of out performance, they have been facing headwinds but then headwinds also don't remain for ever. Is the worst over for them and is it time to once again look at them ? Global private equity firm Warburg Pincus, through its affiliate Honey Rose Investment, sold 6,457,849 shares, representing 6.4% stake for Rs 359 crore, according to bulk deals data. Chicago-based investment firm Creation Investments Fusion, Llc has sold 3,841,172 shares, representing 3.8% stake for Rs 213 crore. Besides Warburg Pincus, Chicago-based investment firm Creation Investments Fusion, Llc, which is also a part of the promoter group, may as well sell part stake. The total number of shares on offer is 93.5 lakh, and the floor price for the same has been set at Rs 535, reports said. Global hedge funds went on a stock-buying spree just ahead of a U.S. jobs report that drove the S&P 500 and Nasdaq to their highest closing levels since early 2022, a Morgan Stanley's prime brokerage note showed. The bulk deal data on the BSE showed a 'Rare Enterprise' as the buyer of about 90,000 shares of Him on Wednesday, triggering a 20% spike - the highest tradable limit of the day - in Him shares on Thursday. Earlier today, a delegation led by Principal Secretary to Prime Minister, Pramod Kumar Mishra took stock of ongoing efforts to rescue 41 trapped workers in the Silkyara tunnel in Uttarkashi on the 16th day of the operations. Union Home Secretary Ajay Kumar Bhalla and Uttarakhand Chief Secretary SS Sandhu along with Pramod Kumar Mishra inspected the work inside the tunnel.The Principal Secretary also enquired about the food items sent to the workers trapped inside the tunnel. PK Mishra also spoke to the trapped workers and their families. Chris Cooper, a micro tunnelling expert, has arrived at the Silkyara tunnel incident site to monitor the rescue operation of 40 trapped workers. A heavy-duty drilling machine is expected to arrive from Indore today. Chief Minister Pushkar Singh Dhami is holding a meeting with senior officials to review relief and rescue operations. Multibagger returns among the midcaps were lower, compared with the smallcaps, with just 9 companies rising over 100% in the last one year period. REC Ltd topped the charts in the midcap segment by delivering 247% returns in Samvat 2079, closely followed by IRFC (247%) and Power Finance Corp (240%). The capital market is a better source of long-term funding than banks because of reasons around rate and tenure. Yet, only a small fraction of midsized companies have effectively used this options to its advantage. About 57 smallcap stocks delivered double-digit weekly returns with four of them offering over 25% returns. Jaiprakash Associates was the top gainer in the pack with nearly 40% return, followed by SEPC Ltd (35.1%), Greenlam Industries (29.6%), and Apollo Micro Systems (25%). India's state-run insurer Life Insurance Corporation (LIC), Mankind Pharma, Campus Activewear, TVS Supply Chain Solutions, Kaynes Technology, and ten other stocks will see their lock-in period expire in November. Brokerage Emkay has compiled the data in its IPO Tracker report. During the quarter, FIIs raised their stake in at least 529 stocks, out of which a vast majority of 496 counters have given positive returns in the fiscal year and 95 have more than doubled investor wealth, shows ACE Equity data. AU SFB, in a late evening regulatory filing on Sunday, announced its approval of the amalgamation. Post the deal announcement, Fincare's Rs 625-crore initial public offering will be on the back burner, said Divya Sehgal, a nominee director on its board and added that the promoter of the entity will infuse Rs 700 crore into the bank before the merger. Did you inquire about buying an EV this festive season? If not then do it, because that will give you an idea of the whole chain in the auto space where to put your money. Also give an idea about what is hype and what real business is about. Real businesses finally eat hype for breakfast as macro finally wins the war of both, the valuations and cash flows and probably the decisive battle will start sooner than later. In the midcap segment, only Supreme Industries rose in double-digits with 13% gain. New India Assurance and Crisil were distant close, with 9% and 7% gains, respectively.Among the Sensex pack, Nestle India topped the charts with 3.07% returns, followed by Ultratech at 1.07% and Power Grid at 0.6%. Ujjivan Small Finance Bank CEO, Ittira Davis, expects small finance banks to grow at around 25% this year. The affordable housing sector has seen the biggest growth for Ujjivan this quarter, followed by micro banking. Davis believes the growth in the housing sector is due to the housing finance companies (HFCs) seeing an increase in demand. Ujjivan is also prepared for a higher interest rate environment, with deposits growing faster than loans. Davis expects small finance banks to grow at a stable rate of 25% this year.
english
As we all know Jose Aldo, UFC’s long-time featherweight champion pulled out of his UFC 189 bout with Conor McGregor due to his rib injury. And he received some negative reactions for withdrawing, from many people including MMA analyst Chael Sonnen and the UFC president Dana White himself. It seems like “Scarface” has had enough negativity on his injury and has taken a step further by threatening to file a defamation suit against the former fighter Sonnen. Sonnen on his "You're Welcome!" podcast said: "I get a phone call. So I answer it on the car speaker. It's a lawyer from Brazil threatening to sue me for defamation. Her client? Jose Aldo. They said, 'we won't sue you if you stop talking about it.' I said, 'Hold on, I'll go a step further than that, if I said it and it's not true, I'll give them an apology.' I don't want to go around saying the guy put out two X-rays if that's not true, but I'm a little confused here. I parroted this information, I heard it and I repeated it, so where did this story come from? I heard this at a UFC press conference. The attorney said, 'yeah, well pay attention in the next few days, you won't hear the UFC saying it anymore because before we called and threatened you with a lawsuit, we called and threatened them with a lawsuit.' I have to assume he's telling the truth. Jose Aldo is threatening to sue me and claims that he threatened to sue the UFC. That's a pretty big bluff. That's a big enough bluff that I think he's telling the truth." He also tweeted the following: The “American Gangster” also invited Aldo to appear on his podcast to set things straight. It would have been one hell of a podcast if the champion would have taken him up on the offer.
english
<gh_stars>10-100 {"fundProfile": {"fundId": "1884", "citFundId": "7555", "instrumentId": 27075102, "shortName": "Inst Tot Bd Mkt Ix Tr", "longName": "Vanguard Institutional Total Bond Market Index Trust", "inceptionDate": "2016-06-24T00:00:00-04:00", "newspaperAbbreviation": "VanTBdMIxInsSel ", "style": "Bond Funds", "type": "Bond Funds", "category": "Intermediate-Term Bond", "customizedStyle": "Bond - Inter-term Investment", "fixedIncomeInvestmentStyleId": "2", "fixedIncomeInvestmentStyleName": "Intermediate-term Treasury", "secDesignation": "", "maximumYearlyInvestment": "", "expenseRatio": "0.0100", "expenseRatioAsOfDate": "2020-04-28T00:00:00-04:00", "isInternalFund": true, "isExternalFund": false, "isMutualFund": true, "isETF": false, "isVLIP": false, "isVVAP": false, "is529": false, "hasAssociatedInvestorFund": true, "hasMoreThan1ShareClass": true, "isPESite": true, "fundFact": {"isActiveFund": true, "isClosed": false, "isClosedToNewInvestors": false, "isFundOfFunds": false, "isMSCIIndexedFund": false, "isIndex": true, "isLoadFund": false, "isMoneyMarket": false, "isBond": true, "isBalanced": false, "isStock": false, "isInternational": false, "isMarketNeutralFund": false, "isInternationalStockFund": false, "isInternationalBalancedFund": false, "isDomesticStockFund": false, "isTaxable": true, "isTaxExempt": false, "isTaxManaged": false, "isTaxableBondFund": true, "isTaxExemptBondFund": false, "isTaxExemptMoneyMarketFund": false, "isTaxSensitiveFund": true, "isSpecialtyStockFund": false, "isHybridFund": false, "isGlobal": false, "isManagedPayoutFund": false, "isGNMAFund": false, "isInvestorShare": false, "isAdmiralShare": false, "isInstitutionalShare": false, "isAdmiralFund": false, "isStableValueFund": false, "isCompanyStockFund": false, "isREITFund": false, "isVariableInsuranceFund": false, "isComingledTrustFund": false, "isConvertibleFund": false, "isAssetAllocationFund": false, "isStateMunicipalBond": false, "isNationalMunicipalBond": false, "isQualifiedOnly": false, "isPreciousMetalsFund": false, "mIsVIPSFund": false, "isSectorSpecific": false, "hasOtherIndex": false, "isTargetRetirementFund": false, "isRetirementSavingsTrustFund": false, "isNon40ActFund": true, "isUnfundedFund": false, "isCreditSuisseFund": false, "isKaiserFund": false, "isFundAccessFund": false, "isFundTransferableToVGI": false, "hasTransactionFee": false, "isNTFFund": false, "hasMoreThan1ShareClass": false, "isOpenToFlagship": false, "isOpenToFlagshipPlus": false, "isCitFund": true, "isAcctType15Fund": false, "isEtfOfEtfs": false, "isStandaloneEtf": false}, "associatedFundIds": {"investorFundId": "0084", "admiralFundId": "0584", "etfFundId": "0928", "institutionalFundId": "0222", "institutionalPlusFundId": "0850"}, "fundCategory": {"customizedHighCategoryName": "Bond - Inter-term Investment", "high": {"type": "HIGH", "id": 3, "name": "Bond Funds"}, "mid": {"type": "MID", "id": 31, "name": "Bond Funds"}, "low": {"type": "LOW", "id": 3105, "name": "Intermediate-Term Bond"}}, "largeTransactionAmount": 25000000, "qualifiedTransactionAmount": 50000000, "minimumInitialInvestment": 3000000000.0, "signalFundFlag": false}, "historicalReturn": {"percent": "8.85", "startDate": "1972-12-31T00:00:00-05:00", "endDate": "2011-12-31T00:00:00-05:00"}}
json
{ "videoId": "0AKNxqOT8hw", "channelId": "UCVtFOytbRpEvzLjvqGG5gxQ", "title": "KSI - DOMAIN", "link": "https://www.youtube.com/watch?v=0AKNxqOT8hw", "pubDate": "2012-12-25T10:54:58.000Z", "author": "KSI", "id": "yt:video:0AKNxqOT8hw", "isoDate": "2012-12-25T10:54:58.000Z", "description": "Listen on Apple Music: https://apple.co/3mPpiPJ\nA film by <NAME>. \nThe sequel to ‘Killa Killa feat. Aiyana Lee (Part I)’ is here. \nKSI unveils the next chapter of the action packed short film with new visuals for ‘Domain’ \n(Warning: Video contains expletives and scenes of violence). \nTHIS IS NOT REAL LIFE FAM", "thumbnail": { "url": "https://i1.ytimg.com/vi/0AKNxqOT8hw/hqdefault.jpg", "width": "480", "height": "360" }, "starRating": { "count": "301141", "average": "4.95", "min": "1", "max": "5" }, "statistics": { "views": "1761684" }, "original_created_at": "2020-12-25T10:54:58.000Z", "created_at": "2012-12-26T07:31:56.557Z", "tags": [] }
json
.left-main-nav{ /*width: 100%;*/ /*background: coral;*/ } .left-main-nav li{ list-style: none; } .left-main-nav a{ color: black; text-decoration: none; display: block; padding: 10px 0px 10px 10px; /*border-bottom: 1px solid black;*/ } .left-main-nav a:hover{ /*background: lightgray;*/ color: green; text-transform: uppercase; font-weight: bold; border-bottom: 1px solid black; } .left-main-nav .sub-arrow:after{ content: '\203A'; float: right; margin-right: 20px; transform: rotate(90deg); -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); } .left-main-nav-ul ul{ display: none; } .left-main-nav-ul ul a:before{ content: '\203A'; margin-right: 10px; } .left-main-nav-ul li.tap ul{ display: block; padding-left: 10px; } .left-main-nav li.tap .sub-arrow:after{ content: '\2039'; }
css
{ "name": "@antdp/dependencies", "version": "1.5.3", "description": "核心依赖包,在这里升级依赖,包含底层编译 umi,代码检测等", "repository": "https://github.com/antdpro/antdp/tree/master/packages/dependencies", "license": "MIT", "keywords": [ "dependencies", "antdp", "antd" ], "dependencies": { "@babel/runtime": "7.12.5" }, "devDependencies": { "react": "16.14.0", "react-dom": "16.14.0" } }
json
{ "directions": [ "Position rack in bottom third of oven and preheat to 325\u00b0F. Pat turkey dry. Place turkey on rack set in large roasting pan. Rub turkey breast with 2 tablespoons butter. Sprinkle with salt and pepper. Fold 2-foot-square piece of cheesecloth in half twice, forming 12-inch square. Dip cloth into water; squeeze out excess moisture. Drape cloth over turkey breast, tucking cloth under at sides. Roast 30 minutes.", "Meanwhile, bring 1 1/2 cups broth, Port and 4 tablespoons butter to simmer in heavy medium saucepan, stirring until butter melts. Baste turkey with 3/4 cup Port mixture. Roast turkey 1 hour 10 minutes, basting twice with remaining Port mixture.", "Add water, onion, carrot and apple to roasting pan; stir to coat vegetables with pan juices. Baste turkey with pan juices. Roast 20 minutes. Remove cheesecloth. Roast turkey until skin browns and meat thermometer inserted into innermost part of thigh registers 180\u00b0F, basting occasionally with pan juices, about 50 minutes. Transfer turkey to platter; tent with foil.", "Place roasting pan over medium-high heat. Bring pan juices and vegetables to boil, scraping up any browned bits. Add Gravy Base and boil uncovered 5 minutes. Scrape mixture into strainer set over large measuring cup, pressing on solids with back of spoon. Spoon fat off top of pan juices. Add enough additional broth to cup to measure 3 cups liquid if necessary, or transfer pan juices to saucepan and boil until reduced to 3 cups if necessary. Bring pan juices to simmer in heavy medium saucepan. Mix 3 tablespoons butter and flour in small bowl to form paste. Add paste to pan juices; bring to boil, whisking constantly. Boil until sauce thickens, whisking occasionally, about 5 minutes. Season to taste with salt and pepper. Serve turkey, passing gravy separately." ], "ingredients": [ "1 13- to 14-pound turkey; neck, gizzard and heart reserved for Gravy Base", "9 tablespoons butter, room temperature", "1 1/2 cups (or more) canned low-salt chicken broth", "1/2 cup tawny Port", "1 cup water", "1 medium onion, coarsely chopped", "1 large carrot, coarsely chopped", "1 medium Granny Smith apple, peeled, cored, coarsely chopped", "Gravy Base", "3 tablespoons all purpose flour" ], "language": "en-US", "source": "www.epicurious.com", "tags": [ "Poultry", "turkey", "Roast", "Christmas", "Thanksgiving", "Port", "Fall" ], "title": "Port-Basted Roast Turkey with Pan Gravy", "url": "http://www.epicurious.com/recipes/food/views/port-basted-roast-turkey-with-pan-gravy-2764" }
json
import numpy as np class MF(): ''' Matrix Factorisation alogrithm based on <NAME>'s method Key input is the sparse user-item ratings array, with user ratings in an array with a row per user, and a column per item. Values are the users known rating, or zero if no rating is available. The output is a user-item ratings array with all items given a rating. The predicted raings can be extracted from this array. ''' def __init__(self, latent_features = 3, alpha = 0.0002, beta = 0.02, bias = False): self.latent_features = latent_features self.alpha = alpha self.beta = beta self.R_est = None self.H = None self.W = None self.R = None self.bias = bias self.user_bias = None self.item_bias = None def fit(self, R, iter = 1000, error_threshold = 0.05): self.R = R self.users, self.items = R.shape self.H = np.random.rand(self.users, self.latent_features) self.W = np.random.rand(self.latent_features, self.items) if self.bias: self.user_bias = np.random.rand(self.users, 1) self.item_bias = np.random.rand(1, self.items) for i in range(iter): if i % (int(iter / 25)) == 0: print("Iteration {0}...".format(i)) # get Error: R_est = self._R_est() error = np.subtract(self.R, R_est) #Check for good match before max iter is reached if self._error() < error_threshold: print("Local minima found after {0} iterations".format(i)) break #Perform Gradient Decent for user in range(self.users): for item in range(self.items): if self.R[user,item] > 0: #Only use data where we have obvs e = error[user, item] for k in range(self.latent_features): self.H[user,k] += self.alpha * (2 * e * self.W[k,item] - self.beta * self.H[user, k]) self.W[k,item] += self.alpha * (2 * e * self.H[user,k] - self.beta * self.W[k, item]) if self.bias: self.item_bias[0, item] += self.alpha * (e - self.beta * self.item_bias[0, item]) self.user_bias[user, 0] += self.alpha * (e - self.beta * self.user_bias[user, 0]) self.R_est = np.matmul(self.H, self.W) return self._R_est() def _error(self): sum_error = 0 error = np.subtract(self.R, self._R_est()) for user in range(self.users): for item in range(self.items): if self.R[user,item] > 0: sum_error += abs(error[user, item]) prop_error = sum_error / np.sum(self.R) return prop_error def _R_est(self): if self.bias: return np.matmul(self.H, self.W) + self.user_bias + self.item_bias else: return np.matmul(self.H, self.W) if __name__ == "__main__": #ratings array R = np.array([ [1, 0, 0, 4, 5], [2, 5, 1, 5, 5], [1, 4, 1, 5, 4], [4, 1, 4, 0, 3]]) mf = MF(bias=True) R_est = mf.fit(R, error_threshold=0.005) print(R_est)
python
<filename>pkg/sql/table.go<gh_stars>0 // Copyright 2015 The Cockroach Authors. // // Use of this software is governed by the Business Source License included // in the file licenses/BSL.txt and at www.mariadb.com/bsl11. // // Change Date: 2022-10-01 // // On the date above, in accordance with the Business Source License, use // of this software will be governed by the Apache License, Version 2.0, // included in the file licenses/APL.txt and at // https://www.apache.org/licenses/LICENSE-2.0 package sql import ( "context" "fmt" "strings" "github.com/cockroachdb/cockroach/pkg/internal/client" "github.com/cockroachdb/cockroach/pkg/jobs" "github.com/cockroachdb/cockroach/pkg/jobs/jobspb" "github.com/cockroachdb/cockroach/pkg/roachpb" "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror" "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" "github.com/cockroachdb/cockroach/pkg/sql/sqlbase" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/pkg/errors" ) // // This file contains routines for low-level access to stored object // descriptors, as well as accessors for the table cache. // // For higher levels in the SQL layer, these interface are likely not // suitable; consider instead schema_accessors.go and resolver.go. // var testDisableTableLeases bool // TestDisableTableLeases disables table leases and returns // a function that can be used to enable it. func TestDisableTableLeases() func() { testDisableTableLeases = true return func() { testDisableTableLeases = false } } func (p *planner) getVirtualTabler() VirtualTabler { return p.extendedEvalCtx.VirtualSchemas } var errTableDropped = errors.New("table is being dropped") var errTableAdding = errors.New("table is being added") func filterTableState(tableDesc *sqlbase.TableDescriptor) error { switch { case tableDesc.Dropped(): return errTableDropped case tableDesc.Adding(): return errTableAdding case tableDesc.State != sqlbase.TableDescriptor_PUBLIC: return errors.Errorf("table in unknown state: %s", tableDesc.State.String()) } return nil } // An uncommitted database is a database that has been created/dropped // within the current transaction using the TableCollection. A rename // is a drop of the old name and creation of the new name. type uncommittedDatabase struct { name string id sqlbase.ID dropped bool } type uncommittedTable struct { *sqlbase.MutableTableDescriptor *sqlbase.ImmutableTableDescriptor } // TableCollection is a collection of tables held by a single session that // serves SQL requests, or a background job using a table descriptor. The // collection is cleared using releaseTables() which is called at the // end of each transaction on the session, or on hitting conditions such // as errors, or retries that result in transaction timestamp changes. type TableCollection struct { // leaseMgr manages acquiring and releasing per-table leases. leaseMgr *LeaseManager // A collection of table descriptor valid for the timestamp. // They are released once the transaction using them is complete. // If the transaction gets pushed and the timestamp changes, // the tables are released. leasedTables []*sqlbase.ImmutableTableDescriptor // Tables modified by the uncommitted transaction affiliated // with this TableCollection. This allows a transaction to see // its own modifications while bypassing the table lease mechanism. // The table lease mechanism will have its own transaction to read // the table and will hang waiting for the uncommitted changes to // the table. These table descriptors are local to this // TableCollection and invisible to other transactions. A dropped // table is marked dropped. uncommittedTables []uncommittedTable // databaseCache is used as a cache for database names. // This field is nil when the field is initialized for an internalPlanner. // TODO(andrei): get rid of it and replace it with a leasing system for // database descriptors. databaseCache *databaseCache // dbCacheSubscriber is used to block until the node's database cache has been // updated when releaseTables is called. dbCacheSubscriber dbCacheSubscriber // Same as uncommittedTables applying to databases modified within // an uncommitted transaction. uncommittedDatabases []uncommittedDatabase // allDescriptors is a slice of all available descriptors. The descriptors // are cached to avoid repeated lookups by users like virtual tables. The // cache is purged whenever events would cause a scan of all descriptors to // return different values, such as when the txn timestamp changes or when // new descriptors are written in the txn. allDescriptors []sqlbase.DescriptorProto } type dbCacheSubscriber interface { // waitForCacheState takes a callback depending on the cache state and blocks // until the callback declares success. The callback is repeatedly called as // the cache is updated. waitForCacheState(cond func(*databaseCache) bool) } // getMutableTableDescriptor returns a mutable table descriptor. // // If flags.required is false, getMutableTableDescriptor() will gracefully // return a nil descriptor and no error if the table does not exist. // func (tc *TableCollection) getMutableTableDescriptor( ctx context.Context, txn *client.Txn, tn *tree.TableName, flags ObjectLookupFlags, ) (*sqlbase.MutableTableDescriptor, error) { if log.V(2) { log.Infof(ctx, "reading mutable descriptor on table '%s'", tn) } if tn.SchemaName != tree.PublicSchemaName { if flags.required { return nil, sqlbase.NewUnsupportedSchemaUsageError(tree.ErrString(tn)) } return nil, nil } refuseFurtherLookup, dbID, err := tc.getUncommittedDatabaseID(tn.Catalog(), flags.required) if refuseFurtherLookup || err != nil { return nil, err } if dbID == sqlbase.InvalidID && tc.databaseCache != nil { // Resolve the database from the database cache when the transaction // hasn't modified the database. dbID, err = tc.databaseCache.getDatabaseID(ctx, tc.leaseMgr.db.Txn, tn.Catalog(), flags.required) if err != nil || dbID == sqlbase.InvalidID { // dbID can still be invalid if required is false and the database is not found. return nil, err } } if refuseFurtherLookup, table, err := tc.getUncommittedTable(dbID, tn, flags.required); refuseFurtherLookup || err != nil { return nil, err } else if mut := table.MutableTableDescriptor; mut != nil { log.VEventf(ctx, 2, "found uncommitted table %d", mut.ID) return mut, nil } phyAccessor := UncachedPhysicalAccessor{} obj, err := phyAccessor.GetObjectDesc(ctx, txn, tn, flags) if obj == nil { return nil, err } return obj.(*sqlbase.MutableTableDescriptor), err } // getTableVersion returns a table descriptor with a version suitable for // the transaction: table.ModificationTime <= txn.Timestamp < expirationTime. // The table must be released by calling tc.releaseTables(). // // If flags.required is false, getTableVersion() will gracefully // return a nil descriptor and no error if the table does not exist. // // It might also add a transaction deadline to the transaction that is // enforced at the KV layer to ensure that the transaction doesn't violate // the validity window of the table descriptor version returned. // func (tc *TableCollection) getTableVersion( ctx context.Context, txn *client.Txn, tn *tree.TableName, flags ObjectLookupFlags, ) (*sqlbase.ImmutableTableDescriptor, error) { if log.V(2) { log.Infof(ctx, "planner acquiring lease on table '%s'", tn) } if tn.SchemaName != tree.PublicSchemaName { if flags.required { return nil, sqlbase.NewUnsupportedSchemaUsageError(tree.ErrString(tn)) } return nil, nil } refuseFurtherLookup, dbID, err := tc.getUncommittedDatabaseID(tn.Catalog(), flags.required) if refuseFurtherLookup || err != nil { return nil, err } if dbID == sqlbase.InvalidID && tc.databaseCache != nil { // Resolve the database from the database cache when the transaction // hasn't modified the database. dbID, err = tc.databaseCache.getDatabaseID(ctx, tc.leaseMgr.db.Txn, tn.Catalog(), flags.required) if err != nil || dbID == sqlbase.InvalidID { // dbID can still be invalid if required is false and the database is not found. return nil, err } } // TODO(vivek): Ideally we'd avoid caching for only the // system.descriptor and system.lease tables, because they are // used for acquiring leases, creating a chicken&egg problem. // But doing so turned problematic and the tests pass only by also // disabling caching of system.eventlog, system.rangelog, and // system.users. For now we're sticking to disabling caching of // all system descriptors except the role-members-table. avoidCache := flags.avoidCached || testDisableTableLeases || (tn.Catalog() == sqlbase.SystemDB.Name && tn.TableName.String() != sqlbase.RoleMembersTable.Name) if refuseFurtherLookup, table, err := tc.getUncommittedTable(dbID, tn, flags.required); refuseFurtherLookup || err != nil { return nil, err } else if immut := table.ImmutableTableDescriptor; immut != nil { // If not forcing to resolve using KV, tables being added aren't visible. if immut.Adding() && !avoidCache { err := errTableAdding if !flags.required { err = nil } return nil, err } log.VEventf(ctx, 2, "found uncommitted table %d", immut.ID) return immut, nil } readTableFromStore := func() (*sqlbase.ImmutableTableDescriptor, error) { phyAccessor := UncachedPhysicalAccessor{} obj, err := phyAccessor.GetObjectDesc(ctx, txn, tn, flags) if obj == nil { return nil, err } return obj.(*sqlbase.ImmutableTableDescriptor), err } if avoidCache { return readTableFromStore() } // First, look to see if we already have the table. // This ensures that, once a SQL transaction resolved name N to id X, it will // continue to use N to refer to X even if N is renamed during the // transaction. for _, table := range tc.leasedTables { if table.Name == string(tn.TableName) && table.ParentID == dbID { log.VEventf(ctx, 2, "found table in table collection for table '%s'", tn) return table, nil } } origTimestamp := txn.OrigTimestamp() table, expiration, err := tc.leaseMgr.AcquireByName(ctx, origTimestamp, dbID, tn.Table()) if err != nil { // Read the descriptor from the store in the face of some specific errors // because of a known limitation of AcquireByName. See the known // limitations of AcquireByName for details. if err == errTableDropped || err == sqlbase.ErrDescriptorNotFound { return readTableFromStore() } // Lease acquisition failed with some other error. This we don't // know how to deal with, so propagate the error. return nil, err } if !origTimestamp.Less(expiration) { log.Fatalf(ctx, "bad table for T=%s, expiration=%s", origTimestamp, expiration) } tc.leasedTables = append(tc.leasedTables, table) log.VEventf(ctx, 2, "added table '%s' to table collection", tn) // If the table we just acquired expires before the txn's deadline, reduce // the deadline. We use OrigTimestamp() that doesn't return the commit timestamp, // so we need to set a deadline on the transaction to prevent it from committing // beyond the table version expiration time. txn.UpdateDeadlineMaybe(ctx, expiration) return table, nil } // getTableVersionByID is a by-ID variant of getTableVersion (i.e. uses same cache). func (tc *TableCollection) getTableVersionByID( ctx context.Context, txn *client.Txn, tableID sqlbase.ID, flags ObjectLookupFlags, ) (*sqlbase.ImmutableTableDescriptor, error) { log.VEventf(ctx, 2, "planner getting table on table ID %d", tableID) if flags.avoidCached || testDisableTableLeases { table, err := sqlbase.GetTableDescFromID(ctx, txn, tableID) if err != nil { return nil, err } if err := filterTableState(table); err != nil { return nil, err } return sqlbase.NewImmutableTableDescriptor(*table), nil } for _, table := range tc.uncommittedTables { if immut := table.ImmutableTableDescriptor; immut.ID == tableID { log.VEventf(ctx, 2, "found uncommitted table %d", tableID) if immut.Dropped() { return nil, sqlbase.NewUndefinedRelationError( tree.NewUnqualifiedTableName(tree.Name(fmt.Sprintf("<id=%d>", tableID))), ) } return immut, nil } } // First, look to see if we already have the table -- including those // via `getTableVersion`. for _, table := range tc.leasedTables { if table.ID == tableID { log.VEventf(ctx, 2, "found table %d in table cache", tableID) return table, nil } } origTimestamp := txn.OrigTimestamp() table, expiration, err := tc.leaseMgr.Acquire(ctx, origTimestamp, tableID) if err != nil { if err == sqlbase.ErrDescriptorNotFound { // Transform the descriptor error into an error that references the // table's ID. return nil, sqlbase.NewUndefinedRelationError( &tree.TableRef{TableID: int64(tableID)}) } return nil, err } if !origTimestamp.Less(expiration) { log.Fatalf(ctx, "bad table for T=%s, expiration=%s", origTimestamp, expiration) } tc.leasedTables = append(tc.leasedTables, table) log.VEventf(ctx, 2, "added table '%s' to table collection", table.Name) // If the table we just acquired expires before the txn's deadline, reduce // the deadline. We use OrigTimestamp() that doesn't return the commit timestamp, // so we need to set a deadline on the transaction to prevent it from committing // beyond the table version expiration time. txn.UpdateDeadlineMaybe(ctx, expiration) return table, nil } // getMutableTableVersionByID is a variant of sqlbase.GetTableDescFromID which returns a mutable // table descriptor of the table modified in the same transaction. func (tc *TableCollection) getMutableTableVersionByID( ctx context.Context, tableID sqlbase.ID, txn *client.Txn, ) (*sqlbase.MutableTableDescriptor, error) { log.VEventf(ctx, 2, "planner getting mutable table on table ID %d", tableID) if table := tc.getUncommittedTableByID(tableID).MutableTableDescriptor; table != nil { log.VEventf(ctx, 2, "found uncommitted table %d", tableID) return table, nil } return sqlbase.GetMutableTableDescFromID(ctx, txn, tableID) } func (tc *TableCollection) releaseLeases(ctx context.Context) { if len(tc.leasedTables) > 0 { log.VEventf(ctx, 2, "releasing %d tables", len(tc.leasedTables)) for _, table := range tc.leasedTables { if err := tc.leaseMgr.Release(table); err != nil { log.Warning(ctx, err) } } tc.leasedTables = tc.leasedTables[:0] } } // releaseTables releases all tables currently held by the TableCollection. func (tc *TableCollection) releaseTables(ctx context.Context) { tc.releaseLeases(ctx) tc.uncommittedTables = nil tc.uncommittedDatabases = nil tc.releaseAllDescriptors() } // Wait until the database cache has been updated to properly // reflect all dropped databases, so that future commands on the // same gateway node observe the dropped databases. func (tc *TableCollection) waitForCacheToDropDatabases(ctx context.Context) { for _, uc := range tc.uncommittedDatabases { if !uc.dropped { continue } // Wait until the database cache has been updated to properly // reflect a dropped database, so that future commands on the // same gateway node observe the dropped database. tc.dbCacheSubscriber.waitForCacheState( func(dc *databaseCache) bool { // Resolve the database name from the database cache. dbID, err := dc.getCachedDatabaseID(uc.name) if err != nil || dbID == sqlbase.InvalidID { // dbID can still be 0 if required is false and // the database is not found. Swallowing error here // because it was felt there was no value in returning // it to a higher layer only to be swallow there. This // entire codepath is only called from one place so // it's better to swallow it here. return true } // If the database name still exists but it now references another // db with a more recent id, we're good - it means that the database // name has been reused. return dbID > uc.id }) } } func (tc *TableCollection) hasUncommittedTables() bool { return len(tc.uncommittedTables) > 0 } func (tc *TableCollection) addUncommittedTable(desc sqlbase.MutableTableDescriptor) error { if desc.Version != desc.ClusterVersion.Version+1 { return errors.Errorf( "descriptor version %d not incremented from cluster version %d", desc.Version, desc.ClusterVersion.Version) } tbl := uncommittedTable{ MutableTableDescriptor: &desc, ImmutableTableDescriptor: sqlbase.NewImmutableTableDescriptor(desc.TableDescriptor), } for i, table := range tc.uncommittedTables { if table.MutableTableDescriptor.ID == desc.ID { tc.uncommittedTables[i] = tbl return nil } } tc.uncommittedTables = append(tc.uncommittedTables, tbl) tc.releaseAllDescriptors() return nil } // returns all the idVersion pairs that have undergone a schema change. // Returns nil for no schema changes. The version returned for each // schema change is ClusterVersion - 1, because that's the one that will be // used when checking for table descriptor two version invariance. // Also returns strings representing the new <name, version> pairs func (tc *TableCollection) getTablesWithNewVersion() []IDVersion { var tables []IDVersion for _, table := range tc.uncommittedTables { if mut := table.MutableTableDescriptor; !mut.IsNewTable() { tables = append(tables, NewIDVersionPrev(&mut.ClusterVersion)) } } return tables } type dbAction bool const ( dbCreated dbAction = false dbDropped dbAction = true ) func (tc *TableCollection) addUncommittedDatabase(name string, id sqlbase.ID, action dbAction) { db := uncommittedDatabase{name: name, id: id, dropped: action == dbDropped} tc.uncommittedDatabases = append(tc.uncommittedDatabases, db) tc.releaseAllDescriptors() } // getUncommittedDatabaseID returns a database ID for the requested tablename // if the requested tablename is for a database modified within the transaction // affiliated with the LeaseCollection. func (tc *TableCollection) getUncommittedDatabaseID( requestedDbName string, required bool, ) (c bool, res sqlbase.ID, err error) { // Walk latest to earliest so that a DROP DATABASE followed by a // CREATE DATABASE with the same name will result in the CREATE DATABASE // being seen. for i := len(tc.uncommittedDatabases) - 1; i >= 0; i-- { db := tc.uncommittedDatabases[i] if requestedDbName == db.name { if db.dropped { if required { return true, sqlbase.InvalidID, sqlbase.NewUndefinedDatabaseError(requestedDbName) } return true, sqlbase.InvalidID, nil } return false, db.id, nil } } return false, sqlbase.InvalidID, nil } // getUncommittedTable returns a table for the requested tablename // if the requested tablename is for a table modified within the transaction // affiliated with the LeaseCollection. // // The first return value "refuseFurtherLookup" is true when there is // a known deletion of that table, so it would be invalid to miss the // cache and go to KV (where the descriptor prior to the DROP may // still exist). func (tc *TableCollection) getUncommittedTable( dbID sqlbase.ID, tn *tree.TableName, required bool, ) (refuseFurtherLookup bool, table uncommittedTable, err error) { // Walk latest to earliest so that a DROP TABLE followed by a CREATE TABLE // with the same name will result in the CREATE TABLE being seen. for i := len(tc.uncommittedTables) - 1; i >= 0; i-- { table := tc.uncommittedTables[i] mutTbl := table.MutableTableDescriptor // If a table has gotten renamed we'd like to disallow using the old names. // The renames could have happened in another transaction but it's still okay // to disallow the use of the old name in this transaction because the other // transaction has already committed and this transaction is seeing the // effect of it. for _, drain := range mutTbl.DrainingNames { if drain.Name == string(tn.TableName) && drain.ParentID == dbID { // Table name has gone away. if required { // If it's required here, say it doesn't exist. err = sqlbase.NewUndefinedRelationError(tn) } // The table collection knows better; the caller has to avoid // going to KV in any case: refuseFurtherLookup = true return true, uncommittedTable{}, err } } // Do we know about a table with this name? if mutTbl.Name == string(tn.TableName) && mutTbl.ParentID == dbID { // Right state? if err = filterTableState(mutTbl.TableDesc()); err != nil && err != errTableAdding { if !required { // If it's not required here, we simply say we don't have it. err = nil } // The table collection knows better; the caller has to avoid // going to KV in any case: refuseFurtherLookup = true return true, uncommittedTable{}, err } // Got a table. return false, table, nil } } return false, uncommittedTable{}, nil } func (tc *TableCollection) getUncommittedTableByID(id sqlbase.ID) uncommittedTable { // Walk latest to earliest so that a DROP TABLE followed by a CREATE TABLE // with the same name will result in the CREATE TABLE being seen. for i := len(tc.uncommittedTables) - 1; i >= 0; i-- { table := tc.uncommittedTables[i] if table.MutableTableDescriptor.ID == id { return table } } return uncommittedTable{} } // getAllDescriptors returns all descriptors visible by the transaction, // first checking the TableCollection's cached descriptors for validity // before defaulting to a key-value scan, if necessary. func (tc *TableCollection) getAllDescriptors( ctx context.Context, txn *client.Txn, ) ([]sqlbase.DescriptorProto, error) { if tc.allDescriptors == nil { descs, err := GetAllDescriptors(ctx, txn) if err != nil { return nil, err } tc.allDescriptors = descs } return tc.allDescriptors, nil } // releaseAllDescriptors releases the cached slice of all descriptors // held by TableCollection. func (tc *TableCollection) releaseAllDescriptors() { tc.allDescriptors = nil } // Copy the modified schema to the table collection. Used when initializing // an InternalExecutor. func (tc *TableCollection) copyModifiedSchema(to *TableCollection) { if tc == nil { return } to.uncommittedTables = tc.uncommittedTables to.uncommittedDatabases = tc.uncommittedDatabases // Do not copy the leased descriptors because we do not want // the leased descriptors to be released by the "to" TableCollection. // The "to" TableCollection can re-lease the same descriptors. } type tableCollectionModifier interface { copyModifiedSchema(to *TableCollection) } // createOrUpdateSchemaChangeJob finalizes the current mutations in the table // descriptor. If a schema change job in the system.jobs table has not been // created for mutations in the current transaction, one is created. The // identifiers of the mutations and newly-created job are written to a new // MutationJob in the table descriptor. // // The job creation is done within the planner's txn. This is important - if the // txn ends up rolling back, the job needs to go away. // // If a job for this table has already been created, update the job's details // and description. func (p *planner) createOrUpdateSchemaChangeJob( ctx context.Context, tableDesc *sqlbase.MutableTableDescriptor, stmt string, ) (sqlbase.MutationID, error) { mutationID := tableDesc.ClusterVersion.NextMutationID var job *jobs.Job var spanList []jobspb.ResumeSpanList if len(tableDesc.MutationJobs) > len(tableDesc.ClusterVersion.MutationJobs) { // Already created a job and appended the job ID to MutationJobs. jobID := tableDesc.MutationJobs[len(tableDesc.MutationJobs)-1].JobID var err error job, err = p.ExecCfg().JobRegistry.LoadJobWithTxn(ctx, jobID, p.txn) if err != nil { return sqlbase.InvalidMutationID, err } spanList = job.Details().(jobspb.SchemaChangeDetails).ResumeSpanList } span := tableDesc.PrimaryIndexSpan() for i := len(tableDesc.ClusterVersion.Mutations) + len(spanList); i < len(tableDesc.Mutations); i++ { spanList = append(spanList, jobspb.ResumeSpanList{ ResumeSpans: []roachpb.Span{span}, }, ) } if job == nil { jobRecord := jobs.Record{ Description: stmt, Username: p.User(), DescriptorIDs: sqlbase.IDs{tableDesc.GetID()}, Details: jobspb.SchemaChangeDetails{ResumeSpanList: spanList}, Progress: jobspb.SchemaChangeProgress{}, } job = p.ExecCfg().JobRegistry.NewJob(jobRecord) if err := job.WithTxn(p.txn).Created(ctx); err != nil { return sqlbase.InvalidMutationID, err } tableDesc.MutationJobs = append(tableDesc.MutationJobs, sqlbase.TableDescriptor_MutationJob{ MutationID: mutationID, JobID: *job.ID()}) } else { if err := job.WithTxn(p.txn).SetDetails( ctx, jobspb.SchemaChangeDetails{ResumeSpanList: spanList}, ); err != nil { return sqlbase.InvalidMutationID, err } if err := job.WithTxn(p.txn).SetDescription( ctx, func(ctx context.Context, description string) (string, error) { return strings.Join([]string{description, stmt}, ";"), nil }, ); err != nil { return sqlbase.InvalidMutationID, err } } return mutationID, nil } // createDropTablesJob creates a schema change job in the system.jobs table. // The identifiers of the newly-created job are written in the table descriptor. // If no job is created (no tables were dropped), a job ID of 0 is returned. // // The job creation is done within the planner's txn. This is important - if the` // txn ends up rolling back, the job needs to go away. func (p *planner) createDropTablesJob( ctx context.Context, tableDescs []*sqlbase.MutableTableDescriptor, droppedDetails []jobspb.DroppedTableDetails, stmt string, drainNames bool, droppedDatabaseID sqlbase.ID, ) (int64, error) { if len(tableDescs) == 0 { return 0, nil } descriptorIDs := make([]sqlbase.ID, 0, len(tableDescs)) for _, tableDesc := range tableDescs { descriptorIDs = append(descriptorIDs, tableDesc.ID) } detailStatus := jobspb.Status_DRAINING_NAMES if !drainNames { detailStatus = jobspb.Status_WAIT_FOR_GC_INTERVAL } for _, droppedDetail := range droppedDetails { droppedDetail.Status = detailStatus } runningStatus := RunningStatusDrainingNames if !drainNames { runningStatus = RunningStatusWaitingGC } jobRecord := jobs.Record{ Description: stmt, Username: p.User(), DescriptorIDs: descriptorIDs, Details: jobspb.SchemaChangeDetails{DroppedTables: droppedDetails, DroppedDatabaseID: droppedDatabaseID}, Progress: jobspb.SchemaChangeProgress{}, RunningStatus: runningStatus, } job := p.ExecCfg().JobRegistry.NewJob(jobRecord) if err := job.WithTxn(p.txn).Created(ctx); err != nil { return 0, err } if err := job.WithTxn(p.txn).Started(ctx); err != nil { return 0, err } for _, tableDesc := range tableDescs { tableDesc.DropJobID = *job.ID() } return *job.ID(), nil } // queueSchemaChange queues up a schema changer to process an outstanding // schema change for the table. func (p *planner) queueSchemaChange( tableDesc *sqlbase.TableDescriptor, mutationID sqlbase.MutationID, ) { sc := SchemaChanger{ tableID: tableDesc.GetID(), mutationID: mutationID, nodeID: p.extendedEvalCtx.NodeID, leaseMgr: p.LeaseMgr(), jobRegistry: p.ExecCfg().JobRegistry, leaseHolderCache: p.ExecCfg().LeaseHolderCache, rangeDescriptorCache: p.ExecCfg().RangeDescriptorCache, clock: p.ExecCfg().Clock, settings: p.ExecCfg().Settings, execCfg: p.ExecCfg(), } p.extendedEvalCtx.SchemaChangers.queueSchemaChanger(sc) } // writeSchemaChange effectively writes a table descriptor to the // database within the current planner transaction, and queues up // a schema changer for future processing. func (p *planner) writeSchemaChange( ctx context.Context, tableDesc *sqlbase.MutableTableDescriptor, mutationID sqlbase.MutationID, ) error { if tableDesc.Dropped() { // We don't allow schema changes on a dropped table. return fmt.Errorf("table %q is being dropped", tableDesc.Name) } return p.writeTableDesc(ctx, tableDesc, mutationID) } func (p *planner) writeSchemaChangeToBatch( ctx context.Context, tableDesc *sqlbase.MutableTableDescriptor, mutationID sqlbase.MutationID, b *client.Batch, ) error { if tableDesc.Dropped() { // We don't allow schema changes on a dropped table. return fmt.Errorf("table %q is being dropped", tableDesc.Name) } return p.writeTableDescToBatch(ctx, tableDesc, mutationID, b) } func (p *planner) writeDropTable( ctx context.Context, tableDesc *sqlbase.MutableTableDescriptor, ) error { return p.writeTableDesc(ctx, tableDesc, sqlbase.InvalidMutationID) } func (p *planner) writeTableDesc( ctx context.Context, tableDesc *sqlbase.MutableTableDescriptor, mutationID sqlbase.MutationID, ) error { b := p.txn.NewBatch() if err := p.writeTableDescToBatch(ctx, tableDesc, mutationID, b); err != nil { return err } return p.txn.Run(ctx, b) } func (p *planner) writeTableDescToBatch( ctx context.Context, tableDesc *sqlbase.MutableTableDescriptor, mutationID sqlbase.MutationID, b *client.Batch, ) error { if tableDesc.IsVirtualTable() { return pgerror.AssertionFailedf("virtual descriptors cannot be stored, found: %v", tableDesc) } if tableDesc.IsNewTable() { if err := runSchemaChangesInTxn(ctx, p.txn, p.Tables(), p.execCfg, p.EvalContext(), tableDesc, p.ExtendedEvalContext().Tracing.KVTracingEnabled(), ); err != nil { return err } } else { // Only increment the table descriptor version once in this transaction. if err := tableDesc.MaybeIncrementVersion(ctx, p.txn); err != nil { return err } // Schedule a schema changer for later. p.queueSchemaChange(tableDesc.TableDesc(), mutationID) } if err := tableDesc.ValidateTable(p.extendedEvalCtx.Settings); err != nil { return pgerror.AssertionFailedf("table descriptor is not valid: %s\n%v", err, tableDesc) } if err := p.Tables().addUncommittedTable(*tableDesc); err != nil { return err } descKey := sqlbase.MakeDescMetadataKey(tableDesc.GetID()) descVal := sqlbase.WrapDescriptor(tableDesc) if p.extendedEvalCtx.Tracing.KVTracingEnabled() { log.VEventf(ctx, 2, "Put %s -> %s", descKey, descVal) } b.Put(descKey, descVal) return nil }
go
"""Test API utilities.""" import json from pytradfri.api.libcoap_api import APIFactory from pytradfri.gateway import Gateway def test_constructor_timeout_passed_to_subprocess(monkeypatch): """Test that original timeout is passed to subprocess.""" capture = {} def capture_args(*args, **kwargs): capture.update(kwargs) return json.dumps([]) monkeypatch.setattr("subprocess.check_output", capture_args) api = APIFactory("anything", timeout=20, psk="abc") api.request(Gateway().get_devices()) assert capture["timeout"] == 20 def test_custom_timeout_passed_to_subprocess(monkeypatch): """Test that custom timeout is passed to subprocess.""" capture = {} def capture_args(*args, **kwargs): capture.update(kwargs) return json.dumps([]) monkeypatch.setattr("subprocess.check_output", capture_args) api = APIFactory("anything", psk="abc") api.request(Gateway().get_devices(), timeout=1) assert capture["timeout"] == 1
python
OKD Institute of Social Change and Development invites candidates for the recruitment of Multi-Tasking Staff & Front Desk Manager, Apply Now! Omeo Kumar Das Institute of Social Change And Development (OKDISCD) Assam released the latest job notification for the recruitment of Multi-Tasking Staff and Front Desk Manager vacancy. Interested candidates can apply before the last date. Check more details on the OKDISCD job vacancy 2022. Omeo Kumar Das Institute of Social Change And Development (OKDISCD) Assam is inviting applications from eligible candidates for the post of Multi-Tasking Staff and Front Desk Manager. Desirous candidates can check all the job details of no of posts, age limit, salary, qualification, etc prescribed below: Multi-Tasking Staff (Regular) Front Desk Manager (Temporary Contractual) Multi-Tasking Staff (Regular) Front Desk Manager (Temporary Contractual) Experience : Minimum 3 years of work experience in Academic / Educational / Research Institute or similar organisations. Candidates will have to download the Standard Form of Application available in the Institute's website www. okd. in and must submit the duly signed filled in form addressed to "The Director (i/c), Omeo Kumar Das Institute of Social Change and Development",. The Last date of receipt of applications for both the posts is 14th October 2022 till 5. 00 PM. The application must be accompanied with the following: b) Self-attested copies of testimonials in support of his / her age, caste, educational qualification, work experience etc. Omeo Kumar Das Institute of Social Change and Development is an autonomous Institute situated in Guwahati, Assam. It was established in 1989 under the joint initiative of Government of Assam and Indian Council of Social Science Research (ICSSR), New Delhi. It promotes and coordinates research on problems and processes of social transformation and development of Assam and other States of the North Eastern region of India.
english
<filename>framework/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/util/CayenneWidgetFactory.java /***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.modeler.util; import java.awt.Color; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Collection; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.table.TableCellEditor; import org.apache.cayenne.modeler.ModelerPreferences; import org.apache.cayenne.modeler.undo.JComboBoxUndoListener; import org.apache.cayenne.modeler.util.combo.AutoCompletion; import org.apache.cayenne.modeler.util.combo.ComboBoxCellEditor; import org.apache.cayenne.swing.components.textpane.JCayenneTextPane; import org.apache.cayenne.swing.components.textpane.syntax.EJBQLSyntaxConstant; import org.syntax.jedit.DefaultInputHandler; import org.syntax.jedit.JEditTextArea; /** * Utility class to create standard Swing widgets following default look-and-feel of * CayenneModeler. * */ // TODO: (Andrus) investigate performance impact of substituting // constructors for all new widgets with cloning the prototype public class CayenneWidgetFactory { /** * Not intended for instantiation. */ protected CayenneWidgetFactory() { super(); } /** * Creates a new JComboBox with a collection of model objects. */ public static JComboBox createComboBox(Collection<String> model, boolean sort) { return createComboBox(model.toArray(), sort); } /** * Creates a new JComboBox with an array of model objects. */ public static JComboBox createComboBox(Object[] model, boolean sort) { JComboBox comboBox = CayenneWidgetFactory.createComboBox(); if (sort) { Arrays.sort(model); } comboBox.setModel(new DefaultComboBoxModel(model)); return comboBox; } /** * Creates a new JComboBox. */ public static JComboBox createComboBox() { JComboBox comboBox = new JComboBox(); initFormWidget(comboBox); comboBox.setBackground(Color.WHITE); comboBox.setMaximumRowCount(ModelerPreferences.COMBOBOX_MAX_VISIBLE_SIZE); return comboBox; } /** * Creates undoable JComboBox. * */ public static JComboBox createUndoableComboBox() { JComboBox comboBox = new JComboBox(); initFormWidget(comboBox); comboBox.addItemListener(new JComboBoxUndoListener()); comboBox.setBackground(Color.WHITE); comboBox.setMaximumRowCount(ModelerPreferences.COMBOBOX_MAX_VISIBLE_SIZE); return comboBox; } /** * Creates undoable JTextField. * */ public static JTextField createUndoableTextField() { return new JTextFieldUndoable(); } /** * Creates undoable JTextField. * */ public static JTextField createUndoableTextField(int size) { return new JTextFieldUndoable(size); } /** * Creates cell editor for text field */ public static DefaultCellEditor createCellEditor(JTextField textField) { return new CayenneCellEditor(textField); } /** * Creates cell editor for a table with combo as editor component. Type of this editor * depends on auto-completion behavior of JComboBox * * @param combo JComboBox to be used as editor component */ public static TableCellEditor createCellEditor(JComboBox combo) { if (Boolean.TRUE.equals(combo .getClientProperty(AutoCompletion.AUTOCOMPLETION_PROPERTY))) { return new ComboBoxCellEditor(combo); } DefaultCellEditor editor = new DefaultCellEditor(combo); editor.setClickCountToStart(1); return editor; } /** * Creates a new JTextField with a default columns count of 20. */ public static JTextField createTextField() { return createTextField(20); } /** * Creates a new JTextField with a specified columns count. */ public static JTextField createTextField(int columns) { final JTextField textField = new JTextField(columns); initFormWidget(textField); initTextField(textField); return textField; } protected static void initTextField(final JTextField textField) { // config focus textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // transfer focus textField.transferFocus(); } }); } /** * Initializes a "form" element with a standard font and height. */ protected static void initFormWidget(JComponent component) { component.setFont(component.getFont().deriveFont(Font.PLAIN, 12)); /* * Dimension size = component.getPreferredSize(); if (size == null) { size = new * Dimension(); } size.setSize(size.getWidth(), 20); * component.setPreferredSize(size); */ } /** * Creates a borderless button that can be used as a clickable label. */ public static JButton createLabelButton(String text) { JButton but = createButton(text); but.setBorderPainted(false); but.setHorizontalAlignment(SwingConstants.LEFT); but.setFocusPainted(false); but.setMargin(new Insets(0, 0, 0, 0)); but.setBorder(null); return but; } /** * Creates a normal button. */ public static JButton createButton(String text) { return new JButton(text); } /** * Creates and returns a JEdit text component with syntax highlighing */ public static JEditTextArea createJEditTextArea() { JEditTextArea area = new JEditTextAreaUndoable(); if (OperatingSystem.getOS() == OperatingSystem.MAC_OS_X) { area.setInputHandler(new MacInputHandler()); } return area; } // public static JSQLTextPane createJSQLTextPane() { // JSQLTextPane area = new JSQLTextPane(); // return area; // } public static JCayenneTextPane createJEJBQLTextPane() { JCayenneTextPane area = new JCayenneTextPaneUndoable(new EJBQLSyntaxConstant()); return area; } /** * Class for enabling Mac OS X keys */ private static class MacInputHandler extends DefaultInputHandler { MacInputHandler() { addDefaultKeyBindings(); } /** * Sets up the default key bindings. */ public void addDefaultKeyBindings() { addKeyBinding("BACK_SPACE", BACKSPACE); addKeyBinding("M+BACK_SPACE", BACKSPACE_WORD); addKeyBinding("DELETE", DELETE); addKeyBinding("M+DELETE", DELETE_WORD); addKeyBinding("ENTER", INSERT_BREAK); addKeyBinding("TAB", INSERT_TAB); addKeyBinding("INSERT", OVERWRITE); addKeyBinding("M+\\", TOGGLE_RECT); addKeyBinding("HOME", HOME); addKeyBinding("END", END); addKeyBinding("M+A", SELECT_ALL); addKeyBinding("S+HOME", SELECT_HOME); addKeyBinding("S+END", SELECT_END); addKeyBinding("M+HOME", DOCUMENT_HOME); addKeyBinding("M+END", DOCUMENT_END); addKeyBinding("MS+HOME", SELECT_DOC_HOME); addKeyBinding("MS+END", SELECT_DOC_END); addKeyBinding("PAGE_UP", PREV_PAGE); addKeyBinding("PAGE_DOWN", NEXT_PAGE); addKeyBinding("S+PAGE_UP", SELECT_PREV_PAGE); addKeyBinding("S+PAGE_DOWN", SELECT_NEXT_PAGE); addKeyBinding("LEFT", PREV_CHAR); addKeyBinding("S+LEFT", SELECT_PREV_CHAR); addKeyBinding("A+LEFT", PREV_WORD); // option + left addKeyBinding("AS+LEFT", SELECT_PREV_WORD); // option + shift + left addKeyBinding("RIGHT", NEXT_CHAR); addKeyBinding("S+RIGHT", SELECT_NEXT_CHAR); addKeyBinding("A+RIGHT", NEXT_WORD); // option + right addKeyBinding("AS+RIGHT", SELECT_NEXT_WORD); // option + shift + right addKeyBinding("UP", PREV_LINE); addKeyBinding("S+UP", SELECT_PREV_LINE); addKeyBinding("DOWN", NEXT_LINE); addKeyBinding("S+DOWN", SELECT_NEXT_LINE); addKeyBinding("M+ENTER", REPEAT); // Clipboard addKeyBinding("M+C", CLIP_COPY); // command + c addKeyBinding("M+V", CLIP_PASTE); // command + v addKeyBinding("M+X", CLIP_CUT); // command + x } } }
java
<gh_stars>1-10 {"title": "Dix mille lieues sans le vouloir", "description": "Deux ans avant l'histoire qui nous occupe, <NAME>, employ\u00e9 \u00e0 la banque Eldheim, \u00e0 Paris, a \u00e9t\u00e9 retrouv\u00e9 assassin\u00e9. Aucune piste n'ayant permis de r\u00e9soudre l'affaire, la police a fini par classer celle-ci. <NAME>, employ\u00e9 au m\u00eame bureau que son p\u00e8re, poursuit toutefois ses propres recherches sur la mort inexpliqu\u00e9e de ce dernier. \n\n<br><br>Une succursale en province pr\u00e9sentant de mauvais comptes et des soup\u00e7ons pesant sur l'agent en charge l\u00e0-bas, Jean y est envoy\u00e9 pour discr\u00e8tement investiguer. Le soir m\u00eame, dans le train en partance pour Nancy, il s'endort la pipe au bec pour se r\u00e9veiller dans des circonstances plus qu'\u00e9trange... \nQue s'est-il donc pass\u00e9 ? D\u00e9couvrons-le ensemble !\n \n<br> - R\u00e9sum\u00e9 par Ezwa", "duration": 15014, "language": "French", "authors": [{"id": "15403", "name": "<NAME>"}], "coverArt": "https://archive.org/download/10000lieuessansvouloir_2102_librivox/dix_mille_2102.jpg", "copyright_year": "1903", "genres": ["General Fiction"], "supporters": [{"role": "Read by", "name": "Ezwa"}, {"role": "Book Coordinator", "name": "Ezwa"}, {"role": "Meta Coordinator", "name": "Ezwa"}, {"role": "Proof Listener", "name": "<NAME>"}], "sections": [{"section": 1, "title": "De Paris \u00e0... ?", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_01_lermina_64kb.mp3", "duration": 1639}, {"section": 2, "title": "Dans la nuit", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_02_lermina_64kb.mp3", "duration": 1008}, {"section": 3, "title": "Il y a des juges \u00e0... Leipzig", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_03_lermina_64kb.mp3", "duration": 959}, {"section": 4, "title": "Sous l'\u0153il de l'empereur", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_04_lermina_64kb.mp3", "duration": 2931}, {"section": 5, "title": "L'Autorit\u00e9 ne se trompe jamais", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_05_lermina_64kb.mp3", "duration": 793}, {"section": 6, "title": "Vive la Pologne !", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_06_lermina_64kb.mp3", "duration": 1940}, {"section": 7, "title": "Dans la bagarre", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_07_lermina_64kb.mp3", "duration": 1712}, {"section": 8, "title": "Sous la terre !", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_08_lermina_64kb.mp3", "duration": 2338}, {"section": 9, "title": "Cinq mille lieues !", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_09_lermina_64kb.mp3", "duration": 1169}, {"section": 10, "title": "Justice !", "readers": [123], "path": "https://www.archive.org/download/10000lieuessansvouloir_2102_librivox/10000lieuessansvouloir_10_lermina_64kb.mp3", "duration": 525}]}
json
<filename>root/pli/ms/sutta/kn/ja/ja349_root-pli-ms.json { "ja349:0.1": "Jātaka", "ja349:0.2": "Catukkanipāta", "ja349:0.3": "Cūḷakuṇālavagga", "ja349:0.4": "9. Sandhibhedajātaka", "ja349:1.1": "“Neva itthīsu sāmaññaṁ,", "ja349:1.2": "nāpi bhakkhesu sārathi;", "ja349:1.3": "Athassa sandhibhedassa,", "ja349:1.4": "passa yāva sucintitaṁ.", "ja349:2.1": "Asi tikkhova maṁsamhi,", "ja349:2.2": "pesuññaṁ parivattati;", "ja349:2.3": "Yatthūsabhañca sīhañca,", "ja349:2.4": "bhakkhayanti migādhamā.", "ja349:3.1": "Imaṁ so sayanaṁ seti,", "ja349:3.2": "yamimaṁ passasi sārathi;", "ja349:3.3": "Yo vācaṁ sandhibhedassa,", "ja349:3.4": "pisuṇassa nibodhati.", "ja349:4.1": "Te janā sukhamedhanti,", "ja349:4.2": "narā saggagatāriva;", "ja349:4.3": "Ye vācaṁ sandhibhedassa,", "ja349:4.4": "nāvabodhanti sārathī”ti.", "ja349:5.1": "Sandhibhedajātakaṁ navamaṁ." }
json
<reponame>fearless0307/zulip { "content": "Foggy in the morning.\nMaximum temperature to be 24.\nMinimum temperature to be 12", "subject": "Here is your weather update for the day:" }
json