qid
int64
2
74.7M
question
stringlengths
31
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
63.3k
response_k
stringlengths
4
60.5k
240,272
I am working on a sharepoint 2013 on-premises team site. now i want to set a column which is of type date/time to be equal to today date,so i added a script inside the Edit form, then i tried to set the date value using SPUtiltiy, as follow:- ``` var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = dd + '/' + mm + '/' + yyyy; alert(today); SPUtility.GetSPFieldByInternalName('OrderDateCustomerApproved_').SetValue(today); ``` but i got this error:- ``` Unable to set date, invalid arguments (requires year, month, and day as integers). throw "Unable to set date, invalid arguments (requires year, month, and day as integers)."; ``` so i tried to do so using pure JavaScript appraoch as follow:- ``` $('select[id^="OrderDateCustomerApproved_"]').val(today); ``` where this did not raise any error, but the field was not populated with today date!! so can anyone adivce on this please? [![enter image description here](https://i.stack.imgur.com/P9FcS.png)](https://i.stack.imgur.com/P9FcS.png)
2018/04/18
[ "https://sharepoint.stackexchange.com/questions/240272", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/84413/" ]
I use the following piece of code to set value to Date-time field with SPUtility and jQuery ``` var currentDate = new Date(); $(SPUtility.GetSPFieldByInternalName(internalFieldName).Controls).find('input').first().val((currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear()); ``` My Site collection uses `MM/DD/YYYY` format for dates so i'm setting it in that format. You will have to change the format if needed.
I was working on something similar last week. Maybe this will point you in the right direction. ``` <script> 'use strict'; (function() { var timeSinceFieldViewCtx = {}; timeSinceFieldViewCtx.Templates = {}; timeSinceFieldViewCtx.Templates.Fields = { "Time": { /* Change to your Date Column - Same as below */ "View": timeSinceFieldViewTemplate } }; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(timeSinceFieldViewCtx); })(); function timeSinceFieldViewTemplate(ctx) { var dateDiff = new Date() - new Date(ctx.CurrentItem.Time); /* Change to your Date Column */ var daysDiff = Math.floor(dateDiff / 1000 / 60 / 60 / 24); return daysDiff; } window.addEventListener('DOMContentLoaded', function() { var x = document.getElementsByClassName('ms-vb-lastCell'); for( var i =0; i < x.length; ++i ) { console.log(x[i].innerText + " Type Of: " + typeof Number(x[i].innerText)); if (Number(x[i].innerText) > 30 ) { x[i].style.color = 'green'; x[i].style.fontWeight='normal'; } if (Number(x[i].innerText) > 60 ) { x[i].style.color = 'green'; x[i].style.fontWeight= 'bold'; } } }, true); </script> ```
240,272
I am working on a sharepoint 2013 on-premises team site. now i want to set a column which is of type date/time to be equal to today date,so i added a script inside the Edit form, then i tried to set the date value using SPUtiltiy, as follow:- ``` var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = dd + '/' + mm + '/' + yyyy; alert(today); SPUtility.GetSPFieldByInternalName('OrderDateCustomerApproved_').SetValue(today); ``` but i got this error:- ``` Unable to set date, invalid arguments (requires year, month, and day as integers). throw "Unable to set date, invalid arguments (requires year, month, and day as integers)."; ``` so i tried to do so using pure JavaScript appraoch as follow:- ``` $('select[id^="OrderDateCustomerApproved_"]').val(today); ``` where this did not raise any error, but the field was not populated with today date!! so can anyone adivce on this please? [![enter image description here](https://i.stack.imgur.com/P9FcS.png)](https://i.stack.imgur.com/P9FcS.png)
2018/04/18
[ "https://sharepoint.stackexchange.com/questions/240272", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/84413/" ]
My data column is: [![enter image description here](https://i.stack.imgur.com/y7SjA.png)](https://i.stack.imgur.com/y7SjA.png) A demo code based on my data column for your reference: ``` <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = dd + '/' + mm + '/' + yyyy; $("input[id^='Date_x0020_Customer_x0020_Approv_']").val(today); }) </script> ``` Note: you need to change id in the above code to yours.
I use the following piece of code to set value to Date-time field with SPUtility and jQuery ``` var currentDate = new Date(); $(SPUtility.GetSPFieldByInternalName(internalFieldName).Controls).find('input').first().val((currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear()); ``` My Site collection uses `MM/DD/YYYY` format for dates so i'm setting it in that format. You will have to change the format if needed.
240,272
I am working on a sharepoint 2013 on-premises team site. now i want to set a column which is of type date/time to be equal to today date,so i added a script inside the Edit form, then i tried to set the date value using SPUtiltiy, as follow:- ``` var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = dd + '/' + mm + '/' + yyyy; alert(today); SPUtility.GetSPFieldByInternalName('OrderDateCustomerApproved_').SetValue(today); ``` but i got this error:- ``` Unable to set date, invalid arguments (requires year, month, and day as integers). throw "Unable to set date, invalid arguments (requires year, month, and day as integers)."; ``` so i tried to do so using pure JavaScript appraoch as follow:- ``` $('select[id^="OrderDateCustomerApproved_"]').val(today); ``` where this did not raise any error, but the field was not populated with today date!! so can anyone adivce on this please? [![enter image description here](https://i.stack.imgur.com/P9FcS.png)](https://i.stack.imgur.com/P9FcS.png)
2018/04/18
[ "https://sharepoint.stackexchange.com/questions/240272", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/84413/" ]
My data column is: [![enter image description here](https://i.stack.imgur.com/y7SjA.png)](https://i.stack.imgur.com/y7SjA.png) A demo code based on my data column for your reference: ``` <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = dd + '/' + mm + '/' + yyyy; $("input[id^='Date_x0020_Customer_x0020_Approv_']").val(today); }) </script> ``` Note: you need to change id in the above code to yours.
SharePoint adds a format function to a date object, so you can use that to do your formatting as well. And I don't used the ID of the field, I use the title because that makes things easier to read. ``` $("input[title='Date Customer Approved']").val(today.format('MM/dd/yyyy')); ```
240,272
I am working on a sharepoint 2013 on-premises team site. now i want to set a column which is of type date/time to be equal to today date,so i added a script inside the Edit form, then i tried to set the date value using SPUtiltiy, as follow:- ``` var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = dd + '/' + mm + '/' + yyyy; alert(today); SPUtility.GetSPFieldByInternalName('OrderDateCustomerApproved_').SetValue(today); ``` but i got this error:- ``` Unable to set date, invalid arguments (requires year, month, and day as integers). throw "Unable to set date, invalid arguments (requires year, month, and day as integers)."; ``` so i tried to do so using pure JavaScript appraoch as follow:- ``` $('select[id^="OrderDateCustomerApproved_"]').val(today); ``` where this did not raise any error, but the field was not populated with today date!! so can anyone adivce on this please? [![enter image description here](https://i.stack.imgur.com/P9FcS.png)](https://i.stack.imgur.com/P9FcS.png)
2018/04/18
[ "https://sharepoint.stackexchange.com/questions/240272", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/84413/" ]
I use the following piece of code to set value to Date-time field with SPUtility and jQuery ``` var currentDate = new Date(); $(SPUtility.GetSPFieldByInternalName(internalFieldName).Controls).find('input').first().val((currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear()); ``` My Site collection uses `MM/DD/YYYY` format for dates so i'm setting it in that format. You will have to change the format if needed.
SharePoint adds a format function to a date object, so you can use that to do your formatting as well. And I don't used the ID of the field, I use the title because that makes things easier to read. ``` $("input[title='Date Customer Approved']").val(today.format('MM/dd/yyyy')); ```
37,902,100
I ran and configure the key and the rest with `aws configure` But when I run `eb init` I got the error > > ERROR: 'init/20160618/us-west-2/elasticbeanstalk/aws4\_request' not a valid key=value pair (missing equal-sign) in Authorization header: 'AWS4-HMAC-SHA256 Credential=eb init/20160618/us-west-2/elasticbeanstalk/aws4\_request, SignedHeaders=host;x-amz-date, Signature=95e3...56e4'. > > > `Awsebcli` and `Python` should be set up correctly with version `EB CLI 3.7.6 (Python 2.7.1)`. Can someone help me figure out why?
2016/06/18
[ "https://Stackoverflow.com/questions/37902100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6484033/" ]
You have to remove or edit the file **config** on the occult directory named .aws, this directory usually is in C:/User/{Your user}/.aws or unix /User/{Your user}/.aws
I encountered the same issue with the same error message, I solved the issue by adding "aws\_access\_key\_id" and "aws\_access\_key\_id" inside both "config" and "credentials" files inside ~/.aws/ directory.
15,792,426
I have a javascript function that adds text to an asp:textbox. But once I try to save the textbox in the C# Codebehind, the textbox.Text property is still holding the original value, not the updated value. Here's the code Javascript ``` function GetLanguages(e) { var newLang = e.nextSibling; var checkedValues = ''; var chkEng = document.getElementById ("<%=chkEnglish.ClientID %>"); var chkFr = document.getElementById ("<%=chkFrench.ClientID %>"); var chkList1 = document.getElementById ("<%=chkTopLanguages.ClientID %>"); var arrayOfCheckBoxes = chkList1.getElementsByTagName("input"); var txtLangValue = document.getElementById("<%=txtLANG.ClientID %>"); if(chkEng.checked) checkedValues = "English"; if(chkFr.checked) { if(checkedValues.length > 0) checkedValues += ";"; checkedValues += "French"; } for(var i=0;i<arrayOfCheckBoxes.length;i++) { var checkBoxRef = arrayOfCheckBoxes[i]; if(checkBoxRef.checked) { var labelArray = checkBoxRef.parentNode.getElementsByTagName('label'); if ( labelArray.length > 0 ) { if ( checkedValues.length > 0 ) checkedValues += ";"; checkedValues += labelArray[0].innerHTML; } } } txtLangValue.value = checkedValues; } ``` CodeBehind ``` List<string> lstItemsChecked = new List<string>(txtLANG.Text.Split(';')); foreach (string language in lstItemsChecked) { foreach (DataRow row in dsTopLanguages.Tables[0].Rows) { if (row["Language"].ToString() == language) { if (strLanguages.Length > 0) strLanguages += ";"; strLanguages += row["LanguageID"].ToString(); } } } ``` The txtLANG.Text.Split call results to the original value of the textbox, not the value updated via javascript
2013/04/03
[ "https://Stackoverflow.com/questions/15792426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1818485/" ]
uggh, figured out what was wrong. Long day, way over complicated things. I forgot to wrap my data load code with if(!IsPostback){} so it was reloading the original record data before saving the values to the database. Sorry!
And you are sure that the javascript function is being called and that the textbox is getting its value updated? Have you tried adding the following at the end of your JavaScript function to make sure the value of the text box is being updated? ``` alert(txtLangValue.value); ```
22,157,943
im working in one small project about handling feeds im looking to handle the feeds in listview and show details in viewpager and get the same feed when i click on the listview im lost about how i can pass the cursor position to the viewpaver that it s the complet listfragment ``` public class EntryListFragmentt extends ListFragment implements OnItemClickListener ,LoaderManager.LoaderCallbacks<Cursor>{ private static final String TAG = "EntryListFragmentt"; private OnItemSelectedListener mParentOnItemSelectedListener; /** * Cursor adapter for controlling ListView results. */ private SimpleCursorAdapter mAdapter; public static ImageLoader imageLoader; Uri detailUri; static int pos; private LoaderManager.LoaderCallbacks<Cursor> mCallbacks; /** * Handle to a SyncObserver. The ProgressBar element is visible until the SyncObserver reports * that the sync is complete. * * <p>This allows us to delete our SyncObserver once the application is no longer in the * foreground. */ ConnectionDetector cd; private Object mSyncObserverHandle; /** * Options menu used to populate ActionBar. */ private Menu mOptionsMenu; /** * Projection for querying the content provider. */ private static final String[] PROJECTION = new String[]{ FeedContract.Entry._ID, FeedContract.Entry.COLUMN_NAME_TITLE, FeedContract.Entry.COLUMN_NAME_LINK, FeedContract.Entry.COLUMN_IMAG_LINK, FeedContract.Entry.COLUMN_TEXT_ENTRY, FeedContract.Entry.COLUMN_NAME_PUBLISHED }; // Column indexes. The index of a column in the Cursor is the same as its relative position in // the projection. /** Column index for _ID */ private static final int COLUMN_ID = 0; /** Column index for title */ private static final int COLUMN_TITLE = 1; /** Column index for link */ private static final int COLUMN_URL_STRING = 2; /** Column index for published */ private static final int COLUMN_IMAG_LINK = 3; private static final int COLUMN_TEXT_ENTRY = 4; private static final int COLUMN_PUBLISHED = 5; AlertDialogManager alert = new AlertDialogManager(); /** * List of Cursor columns to read from when preparing an adapter to populate the ListView. */ private static final String[] FROM_COLUMNS = new String[]{ FeedContract.Entry.COLUMN_NAME_TITLE, FeedContract.Entry.COLUMN_NAME_PUBLISHED, FeedContract.Entry.COLUMN_NAME_LINK // FeedContract.Entry.COLUMN_TEXT_ENTRY }; /** * List of Views which will be populated by Cursor data. */ private static final int[] TO_FIELDS = new int[]{ R.id.tx_title_actu, R.id.tx_date_actu, R.id.img_actu // R.id.tx_text_actu }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public static EntryListFragmentt newInstance() { return new EntryListFragmentt(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } /** @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //View view = inflater // .inflate(R.layout.activity_entry_list, container, false); return container; } **/ /** * Create SyncAccount at launch, if needed. * * <p>This will create a new account with the system for our application, register our * {@link SyncService} with it, and establish a sync schedule. */ @Override public void onAttach(Activity activity) { super.onAttach(activity); // Create account, if needed SyncUtils.CreateSyncAccount(activity); } // private void loaddata(){ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mAdapter = new SimpleCursorAdapter( getActivity(), // Current context R.layout.actu_listitem, // Layout for individual rows null, // Cursor FROM_COLUMNS, // Cursor columns to use TO_FIELDS, // Layout fields to use 0 // No flags ); mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { private String slink; @Override public boolean setViewValue(View view, Cursor cursor, int i) { if (i == COLUMN_PUBLISHED ) { // Convert timestamp to human-readable date Time t = new Time(); t.set(cursor.getLong(i)); ((TextView) view).setText(t.format("%Y-%m-%d %H:%M")); // Drawable fimag = ResourceUtils.getDrawableByName( imaglink, getActivity()); //String faceName = "ic_launcher"; return true; } else if (i == COLUMN_URL_STRING ){ slink = CursorUtils.getString(FeedContract.Entry.COLUMN_NAME_LINK, cursor).trim(); // int vlink = Integer.parseInt(CursorUtils.getString(FeedContract.Entry.COLUMN_NAME_LINK, cursor)); ImageView vimage =(ImageView) view.findViewById(R.id.img_actu); //vimage.setImageResource(getActivity().getResources().getIdentifier("app.oc.gov.ma:drawable/"+slink,null,null)); vimage.setImageDrawable(ResourceUtils.getDrawableByName(slink, getActivity())); // imageLoader=new ImageLoader(getActivity().getApplicationContext()); //imageLoader.DisplayImage(imaglink, vimage); // vimage.setImageResource(R.drawable.a); // Let SimpleCursorAdapter handle other fields automatically return true; } else { return false; } } }); mCallbacks = this; setListAdapter(mAdapter); setEmptyText(getText(R.string.loading)); getLoaderManager().initLoader(0, null, mCallbacks); } @Override public void onResume() { super.onResume(); mSyncStatusObserver.onStatusChanged(0); // Watch for sync state changes final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE; mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver); } @Override public void onPause() { super.onPause(); if (mSyncObserverHandle != null) { ContentResolver.removeStatusChangeListener(mSyncObserverHandle); mSyncObserverHandle = null; } } /** * Query the content provider for data. * * <p>Loaders do queries in a background thread. They also provide a ContentObserver that is * triggered when data in the content provider changes. When the sync adapter updates the * content provider, the ContentObserver responds by resetting the loader and then reloading * it. */ @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { // We only have one loader, so we can ignore the value of i. // (It'll be '0', as set in onCreate().) return new CursorLoader(getActivity(), // Context FeedContract.Entry.CONTENT_URI, // URI PROJECTION, // Projection null, // Selection null, // Selection args // null); // Sort FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort } /** * Move the Cursor returned by the query into the ListView adapter. This refreshes the existing * UI with the data in the Cursor. */ @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { mAdapter.changeCursor(cursor); } /** * Called when the ContentObserver defined for the content provider detects that data has * changed. The ContentObserver resets the loader, and then re-runs the loader. In the adapter, * set the Cursor value to null. This removes the reference to the Cursor, allowing it to be * garbage-collected. */ @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { mAdapter.changeCursor(null); } /** * Create the ActionBar. */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); mOptionsMenu = menu; inflater.inflate(R.menu.main_actu, menu); } /** * Respond to user gestures on the ActionBar. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // If the user clicks the "Refresh" button. case R.id.menu_refresh: cd = new ConnectionDetector(getActivity().getApplicationContext()); // Check for internet connection if (!cd.isConnectingToInternet()) { // Internet Connection is not present setEmptyText(getText(R.string.noconnect)); alert.showAlertDialog(getActivity(), "Internet Connection Error", "Please connect to working Internet connection", false); }else { SyncUtils.TriggerRefresh(); return true; } return false; } return super.onOptionsItemSelected(item); } /** * Load an article in the default browser when selected by the user. */ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); // Get a URI for the selected item, then start an Activity that displays the URI. Any // Activity that filters for ACTION_VIEW and a URI can accept this. In most cases, this will // be a browser. // Get the item at the selected position, in the form of a Cursor. Cursor c = (Cursor) mAdapter.getItem(position); // Get the link to the article represented by the item. Uri detailUri = Uri.parse(FeedContract.Entry.CONTENT_URI + "/" + id); WhatsOnFragment.newInstance(position, detailUri); WhatsOnFragment WWhatsOnFragment = new WhatsOnFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.frame_container, WWhatsOnFragment); //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } public int getCount(int cmp) { return cmp ; } public static WhatsOnFragment newInstance(int position,int cmp, Uri detailUri) { WhatsOnFragment frag = new WhatsOnFragment(); Bundle args = new Bundle(); args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri); args.putInt(WhatsOnFragment.POSITION_KEY, position); frag.setArguments(args); return frag; } /** * Set the state of the Refresh button. If a sync is active, turn on the ProgressBar widget. * Otherwise, turn it off. * * @param refreshing True if an active sync is occuring, false otherwise */ public void setRefreshActionButtonState(boolean refreshing) { if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(null); } } } /** * Crfate a new anonymous SyncStatusObserver. It's attached to the app's ContentResolver in * onResume(), and removed in onPause(). If status changes, it sets the state of the Refresh * button. If a sync is active or pending, the Refresh button is replaced by an indeterminate * ProgressBar; otherwise, the button itself is displayed. */ private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { /** Callback invoked with the sync adapter status changes. */ @Override public void onStatusChanged(int which) { getActivity().runOnUiThread(new Runnable() { /** * The SyncAdapter runs on a background thread. To update the UI, onStatusChanged() * runs on the UI thread. */ @Override public void run() { // Create a handle to the account that was created by // SyncService.CreateSyncAccount(). This will be used to query the system to // see how the sync status has changed. Account account = GenericAccountService.GetAccount(); if (account == null) { // GetAccount() returned an invalid value. This shouldn't happen, but // we'll set the status to "not refreshing". setRefreshActionButtonState(false); return; } // Test the ContentResolver to see if the sync adapter is active or pending. // Set the state of the refresh button accordingly. boolean syncActive = ContentResolver.isSyncActive( account, FeedContract.CONTENT_AUTHORITY); boolean syncPending = ContentResolver.isSyncPending( account, FeedContract.CONTENT_AUTHORITY); setRefreshActionButtonState(syncActive || syncPending); } }); } }; } ``` that it s the fragment detail viewpager ``` public class WhatsOnFragment extends Fragment implements LoaderCallbacks<Cursor> { private static final String TAG="WhatsOnFragment"; private OnItemSelectedListener mParentOnImageSelectedListener; private Handler mHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; private Cursor mAnnouncementsCursor; private LayoutInflater mInflater; private int mTitleCol = -1; private int mDateCol = -1; private int mUrlCol = -1; //**********************************************'' /** Column index for _ID */ private static final int COLUMN_ID = 0; /** Column index for title */ private static final int COLUMN_TITLE = 1; /** Column index for link */ private static final int COLUMN_URL_STRING = 2; /** Column index for published */ private static final int COLUMN_IMAG_LINK = 3; private static final int COLUMN_TEXT_ENTRY = 4; private static final int COLUMN_PUBLISHED = 5; private static final String[] PROJECTION = new String[]{ FeedContract.Entry._ID, FeedContract.Entry.COLUMN_NAME_TITLE, FeedContract.Entry.COLUMN_NAME_LINK, FeedContract.Entry.COLUMN_IMAG_LINK, FeedContract.Entry.COLUMN_TEXT_ENTRY, FeedContract.Entry.COLUMN_NAME_PUBLISHED }; public static String POSITION_KEY = "position"; private static final int ANNOUNCEMENTS_LOADER_ID = 0; private Uri detailUri; public static int vpos; public static WhatsOnFragment newInstance(int position, Uri detailUri) { WhatsOnFragment frag = new WhatsOnFragment(); Bundle args = new Bundle(); args.putInt(POSITION_KEY, position); //args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri); frag.setArguments(args); return frag; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.v(TAG, "onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Bundle extras = getArguments(); //vpos = extras.getInt(POSITION_KEY,0); //vpos = savedInstanceState.getInt(POSITION_KEY, 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; // mRootView = (ViewGroup) inflater.inflate(R.layout.content_f, container,false); refresh(); return mRootView; } @Override public void onDetach() { super.onDetach(); // mHandler.removeCallbacks(mCountdownRunnable); getActivity().getContentResolver().unregisterContentObserver(mObserver); } private void refresh() { mHandler.removeCallbacks(mCountdownRunnable); //mRootView.removeAllViews(); setupDuring(); //getLoaderManager().initLoader(0, null, this); } private void setupDuring() { // Start background query to load announcements getLoaderManager().initLoader(0, null, this); getActivity().getContentResolver().registerContentObserver( FeedContract.Entry.CONTENT_URI, true, mObserver); } /** * Event that updates countdown timer. Posts itself again to * {@link #mHandler} to continue updating time. */ private final Runnable mCountdownRunnable = new Runnable() { public void run() { mHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), // Context FeedContract.Entry.CONTENT_URI, // URI PROJECTION, // Projection null, // Selection null, // Selection args // null); FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (getActivity() == null) { return; } if (data != null && data.getCount() > 0) { mTitleCol = data.getColumnIndex(FeedContract.Entry.COLUMN_NAME_TITLE); mDateCol = data.getColumnIndex(FeedContract.Entry.COLUMN_TEXT_ENTRY); showAnnouncements(data); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAnnouncementsCursor = null; } /** * Show the the announcements */ private void showAnnouncements(Cursor announcements) { mAnnouncementsCursor = announcements; ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate( R.layout.detail, mRootView, false); final ViewPager pager = (ViewPager) announcementsRootView.findViewById( R.id.pager); final PagerAdapter adapter = new AnnouncementsAdapter(); pager.setAdapter(adapter); //pager.setCurrentItem(0); pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { pager.setCurrentItem(pager.getCurrentItem()); } @Override public void onPageScrollStateChanged(int state) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // TODO Auto-generated method stub //Toast.makeText(getActivity().getApplicationContext(),"myposition " + position,Toast.LENGTH_LONG).show(); } }); //mRootView.removeAllViews(); mRootView.addView(announcementsRootView); } public class AnnouncementsAdapter extends PagerAdapter { @Override public Object instantiateItem(ViewGroup pager, int position) { mAnnouncementsCursor.moveToPosition(position); View rootView = (View) mInflater.inflate( R.layout.detail_fragment, pager, false); TextView titleView = (TextView) rootView.findViewById(R.id.title); TextView subtitleView = (TextView) rootView.findViewById(R.id.description); //WebView desc = (WebView) rootView.findViewById(R.id.desc); // Enable the vertical fading edge (by default it is disabled) ScrollView sv = (ScrollView) rootView.findViewById(R.id.sv); sv.setVerticalFadingEdgeEnabled(true); // Set webview properties //WebSettings ws = desc.getSettings(); //ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //ws.setLightTouchEnabled(false); //ws.setPluginState(PluginState.ON); //ws.setJavaScriptEnabled(true); titleView.setText(mAnnouncementsCursor.getString(mTitleCol)); subtitleView.setText(mAnnouncementsCursor.getString(mDateCol)); //desc.loadDataWithBaseURL("http://.../",mAnnouncementsCursor.getString(mDateCol), "text/html", "UTF-8", null); pager.addView(rootView, 0); return rootView; } @Override public void destroyItem(ViewGroup pager, int position, Object view) { pager.removeView((View) view); } @Override public int getCount() { return mAnnouncementsCursor.getCount(); } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } public Object getItem(int position) { WhatsOnFragment frag = new WhatsOnFragment(); Bundle args = new Bundle(); args.putInt(POSITION_KEY, position); //args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri); frag.setArguments(args); if (position > 0 && position < mAnnouncementsCursor.getCount() - 1) { return position; } return position; } } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID); if (loader != null) { loader.forceLoad(); } } }; } ```
2014/03/03
[ "https://Stackoverflow.com/questions/22157943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3376584/" ]
set setHasOptionsMenu(true); on create view ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_messages, container, false); //your code here setHasOptionsMenu(true); } ``` and override on option item selected ``` @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // consider your menu have refresh item case R.id.refresh: Toast.makeText(getActivity(), "Refresh active", Toast.LENGTH_LONG).show(); refresh_messages(); break; default: break; } return super.onOptionsItemSelected(item); } refresh_messages(){ //refresh code here } ```
In your main activity, assuming your fragment has an ID called R.id.details, ``` HomeFragment f = (HomeFragment)getFragmentManager().findFragmentById(R.id.details); if(f != null) { f.refresh_data(); } ``` You can assign an ID to a fragment in your XML layout file.
73,038,765
I have a variable `result` which contains a JSON object: ``` result = JsonConvert.DeserializeObject<PullRequestModel>(responseData); ``` I would like to use `for` loop over `result` as: ``` @for (var key = 0; key < result.value.length; key++) { } ``` But C# thinks `.length` is part of the PullRequestModel, and the code is not working. How do I get around this problem? This is the `PullRequestModel` ``` namespace TestApp.Model.PullRequestModel { public class Avatar { public string href { get; set; } } public class CompletionOptions { public string mergeCommitMessage { get; set; } public bool deleteSourceBranch { get; set; } public bool squashMerge { get; set; } public string mergeStrategy { get; set; } public bool triggeredByAutoComplete { get; set; } public List<object> autoCompleteIgnoreConfigIds { get; set; } } public class CreatedBy { public string displayName { get; set; } public string url { get; set; } public Links _links { get; set; } public string id { get; set; } public string uniqueName { get; set; } public string imageUrl { get; set; } public string descriptor { get; set; } public string href { get; set; } } public class Iterations { public string href { get; set; } } public class LastMergeCommit { public string commitId { get; set; } public string url { get; set; } } public class LastMergeSourceCommit { public string commitId { get; set; } public string url { get; set; } } public class LastMergeTargetCommit { public string commitId { get; set; } public string url { get; set; } } public class Links { public Avatar avatar { get; set; } public Self self { get; set; } public Repository repository { get; set; } public WorkItems workItems { get; set; } public SourceBranch sourceBranch { get; set; } public TargetBranch targetBranch { get; set; } public Statuses statuses { get; set; } public SourceCommit sourceCommit { get; set; } public TargetCommit targetCommit { get; set; } public MergeCommit mergeCommit { get; set; } public CreatedBy createdBy { get; set; } public Iterations iterations { get; set; } } public class MergeCommit { public string href { get; set; } } public class Project { public string id { get; set; } public string name { get; set; } public string state { get; set; } public string visibility { get; set; } public DateTime lastUpdateTime { get; set; } } public class Repository { public string id { get; set; } public string name { get; set; } public string url { get; set; } public Project project { get; set; } public string href { get; set; } } public class Reviewer { public string reviewerUrl { get; set; } public int vote { get; set; } public bool hasDeclined { get; set; } public bool isRequired { get; set; } public bool isFlagged { get; set; } public string displayName { get; set; } public string url { get; set; } public Links _links { get; set; } public string id { get; set; } public string uniqueName { get; set; } public string imageUrl { get; set; } public bool isContainer { get; set; } public List<VotedFor> votedFor { get; set; } } public class PullRequestModel { public List<Value> value { get; set; } public int count { get; set; } } public class Self { public string href { get; set; } } public class SourceBranch { public string href { get; set; } } public class SourceCommit { public string href { get; set; } } public class Statuses { public string href { get; set; } } public class TargetBranch { public string href { get; set; } } public class TargetCommit { public string href { get; set; } } public class Value { public Repository repository { get; set; } public int pullRequestId { get; set; } public int codeReviewId { get; set; } public string status { get; set; } public CreatedBy createdBy { get; set; } public DateTime creationDate { get; set; } public DateTime closedDate { get; set; } public string title { get; set; } public string description { get; set; } public string sourceRefName { get; set; } public string targetRefName { get; set; } public string mergeStatus { get; set; } public bool isDraft { get; set; } public string mergeId { get; set; } public LastMergeSourceCommit lastMergeSourceCommit { get; set; } public LastMergeTargetCommit lastMergeTargetCommit { get; set; } public LastMergeCommit lastMergeCommit { get; set; } public List<Reviewer> reviewers { get; set; } public List<object> labels { get; set; } public string url { get; set; } public Links _links { get; set; } public CompletionOptions completionOptions { get; set; } public bool supportsIterations { get; set; } public DateTime completionQueueTime { get; set; } } public class VotedFor { public string reviewerUrl { get; set; } public int vote { get; set; } public string displayName { get; set; } public string url { get; set; } public Links _links { get; set; } public string id { get; set; } public string uniqueName { get; set; } public string imageUrl { get; set; } public bool isContainer { get; set; } } public class WorkItems { public string href { get; set; } } } ``` This is the cause of the whole problem, if anyone is curious: ``` @if(result == null) { <p> No pull requests found</p> } else { @foreach (var item in result.value) { <div class="accordion"> <input type="checkbox" id="tab1"> <label class="accordion-label" for="tab1"> @item.title </label> <div class="accordion-content"> <WorkItems PersonalAccessToken="@PersonalAccessToken" WorkItemUrl="@item._links.workItems.href"></WorkItems> </div> </div> } } ``` The above code works (it's a Blazor app) I loop trough all Pull requests and show associated Work Items for the PR. But In order to crete a simple accordion, the I must increment `id="tab1">` because in each loop, so my idea was to ditch `@foreach` and use `@for` loop, so I can make use of the `key` to increment the value of `id="tab1">` Hope it makes sense
2022/07/19
[ "https://Stackoverflow.com/questions/73038765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13502536/" ]
```cs result = JsonConvert.DeserializeObject<PullRequestModel>(responseData); @for (var key = 0; key < result.value.Count; key++) { } ``` *List<>* exposes the **Count** property not **Length** property.
It would appear you are deserializing a single object and not an enumerable type. Please try using the following if you want to return something to loop through: ``` result = JsonConvert.DeserializeObject<List<PullRequestModel>>(responseData); @for (var key = 0; key < result.Count; key++) { } ``` Count is a property of of the List object in this case.
42,757,726
I need to disable default routes of `WP REST API` and add custom routes. I found [this question](https://stackoverflow.com/questions/37816170/rest-api-plugin-wordpress-disable-default-routes) which helps me to find following answer. > > > ``` > remove_action('rest_api_init', 'create_initial_rest_routes', 99); > > ``` > > However this will also remove any custom content type routes. So > instead you may choose to use: > > > > ``` > add_filter('rest_endpoints', function($endpoints) { > if ( isset( $endpoints['/wp/v2/users'] ) ) { > unset( $endpoints['/wp/v2/users'] ); > } > // etc > }); > > ``` > > But from that way I need to know all the default routes and remove one by one which is not a cleanest way to do. I would like to know whether there is any cleaner way to achieve that ? **UPDATE 1 :** As per the Chris's suggestion I would add more details to question. Currently I am using `rest_api_init` filter to add my custom routes by using `register_rest_route` method as per the below code which I found on [this article](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). ``` add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/sample/', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); function my_awesome_func( $data ) { return 'somthing'; } ``` The custom route works well, but unfortunately I can't disable the default routes such as `/wp/v2/posts`. **My question :** **How to unset/disable the default routes while using the `rest_api_init` filter to register new custom routes ?**
2017/03/13
[ "https://Stackoverflow.com/questions/42757726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219200/" ]
As per the other question, this is the only "clean" way to do it currently. The cleanest way to approach things in Wordpress is by using filters and/or actions - this allows you to interact with core without making changes *in* core. By tapping into filters/actions you are also giving *other* plugins the chance to operate on the filter/action arguments before/after your hook. If you take a look at `class-wp-rest-server.php` you can easily look at all available filters and actions related to rest. You will notice this one in particular: ``` /** * Filters the array of available endpoints. * * @since 4.4.0 * * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped * to an array of callbacks for the endpoint. These take the format * `'/path/regex' => array( $callback, $bitmask )` or * `'/path/regex' => array( array( $callback, $bitmask ). */ $endpoints = apply_filters( 'rest_endpoints', $this->endpoints ); ``` From my research, this is the very last spot to modify (remove, change or add) endpoints, and is the exact purpose of the filter. As a sidenote, you don't need to do it "one by one" - you *could* just do `$endpoints = []` to start fresh.
[REST API Toolbox](https://wordpress.org/plugins/rest-api-toolbox/) did the job for me. We can handle many things via that plugin. [![enter image description here](https://i.stack.imgur.com/isHvo.png)](https://i.stack.imgur.com/isHvo.png)
42,757,726
I need to disable default routes of `WP REST API` and add custom routes. I found [this question](https://stackoverflow.com/questions/37816170/rest-api-plugin-wordpress-disable-default-routes) which helps me to find following answer. > > > ``` > remove_action('rest_api_init', 'create_initial_rest_routes', 99); > > ``` > > However this will also remove any custom content type routes. So > instead you may choose to use: > > > > ``` > add_filter('rest_endpoints', function($endpoints) { > if ( isset( $endpoints['/wp/v2/users'] ) ) { > unset( $endpoints['/wp/v2/users'] ); > } > // etc > }); > > ``` > > But from that way I need to know all the default routes and remove one by one which is not a cleanest way to do. I would like to know whether there is any cleaner way to achieve that ? **UPDATE 1 :** As per the Chris's suggestion I would add more details to question. Currently I am using `rest_api_init` filter to add my custom routes by using `register_rest_route` method as per the below code which I found on [this article](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). ``` add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/sample/', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); function my_awesome_func( $data ) { return 'somthing'; } ``` The custom route works well, but unfortunately I can't disable the default routes such as `/wp/v2/posts`. **My question :** **How to unset/disable the default routes while using the `rest_api_init` filter to register new custom routes ?**
2017/03/13
[ "https://Stackoverflow.com/questions/42757726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219200/" ]
As per the other question, this is the only "clean" way to do it currently. The cleanest way to approach things in Wordpress is by using filters and/or actions - this allows you to interact with core without making changes *in* core. By tapping into filters/actions you are also giving *other* plugins the chance to operate on the filter/action arguments before/after your hook. If you take a look at `class-wp-rest-server.php` you can easily look at all available filters and actions related to rest. You will notice this one in particular: ``` /** * Filters the array of available endpoints. * * @since 4.4.0 * * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped * to an array of callbacks for the endpoint. These take the format * `'/path/regex' => array( $callback, $bitmask )` or * `'/path/regex' => array( array( $callback, $bitmask ). */ $endpoints = apply_filters( 'rest_endpoints', $this->endpoints ); ``` From my research, this is the very last spot to modify (remove, change or add) endpoints, and is the exact purpose of the filter. As a sidenote, you don't need to do it "one by one" - you *could* just do `$endpoints = []` to start fresh.
I recently had to disable member-only content from appearing in the REST API. Instead of filtering the rest endpoints, I filtered the args used to register the post types: ``` function dbdb_unset_rest_routes( $args, $post_type ) { $allowed_post_types = array( 'page', 'post', 'company', 'job' ); $allowed_post_types = apply_filters( 'dbdb_unset_rest_routes_types', $allowed_post_types ); if( in_array( $post_type, $allowed_post_types ) ){ return $args; } else { $args['show_in_rest'] = 0; } return $args; } add_filter( 'register_post_type_args', 'dbdb_unset_rest_routes', 20, 2 ); ``` The REST API calls `get_post_types()` in `create_initial_rest_routes()` and looks for any post types that have `show_in_rest` set to `true`. By filtering the args via the filter: `register_post_type_args` in `register_post_type()`, we can filter these routes from showing up in the API.
42,757,726
I need to disable default routes of `WP REST API` and add custom routes. I found [this question](https://stackoverflow.com/questions/37816170/rest-api-plugin-wordpress-disable-default-routes) which helps me to find following answer. > > > ``` > remove_action('rest_api_init', 'create_initial_rest_routes', 99); > > ``` > > However this will also remove any custom content type routes. So > instead you may choose to use: > > > > ``` > add_filter('rest_endpoints', function($endpoints) { > if ( isset( $endpoints['/wp/v2/users'] ) ) { > unset( $endpoints['/wp/v2/users'] ); > } > // etc > }); > > ``` > > But from that way I need to know all the default routes and remove one by one which is not a cleanest way to do. I would like to know whether there is any cleaner way to achieve that ? **UPDATE 1 :** As per the Chris's suggestion I would add more details to question. Currently I am using `rest_api_init` filter to add my custom routes by using `register_rest_route` method as per the below code which I found on [this article](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). ``` add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/sample/', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); function my_awesome_func( $data ) { return 'somthing'; } ``` The custom route works well, but unfortunately I can't disable the default routes such as `/wp/v2/posts`. **My question :** **How to unset/disable the default routes while using the `rest_api_init` filter to register new custom routes ?**
2017/03/13
[ "https://Stackoverflow.com/questions/42757726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219200/" ]
This question has already accepted answer. But if anybody find this useful. We can easily remove default routes. Add following code in your theme's (child theme's if any) functions.php or in any custom plugin ``` add_filter('rest_endpoints', function( $endpoints ) { foreach( $endpoints as $route => $endpoint ){ if( 0 === stripos( $route, '/wp/' ) ){ unset( $endpoints[ $route ] ); } } return $endpoints; }); ```
[REST API Toolbox](https://wordpress.org/plugins/rest-api-toolbox/) did the job for me. We can handle many things via that plugin. [![enter image description here](https://i.stack.imgur.com/isHvo.png)](https://i.stack.imgur.com/isHvo.png)
42,757,726
I need to disable default routes of `WP REST API` and add custom routes. I found [this question](https://stackoverflow.com/questions/37816170/rest-api-plugin-wordpress-disable-default-routes) which helps me to find following answer. > > > ``` > remove_action('rest_api_init', 'create_initial_rest_routes', 99); > > ``` > > However this will also remove any custom content type routes. So > instead you may choose to use: > > > > ``` > add_filter('rest_endpoints', function($endpoints) { > if ( isset( $endpoints['/wp/v2/users'] ) ) { > unset( $endpoints['/wp/v2/users'] ); > } > // etc > }); > > ``` > > But from that way I need to know all the default routes and remove one by one which is not a cleanest way to do. I would like to know whether there is any cleaner way to achieve that ? **UPDATE 1 :** As per the Chris's suggestion I would add more details to question. Currently I am using `rest_api_init` filter to add my custom routes by using `register_rest_route` method as per the below code which I found on [this article](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). ``` add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/sample/', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); function my_awesome_func( $data ) { return 'somthing'; } ``` The custom route works well, but unfortunately I can't disable the default routes such as `/wp/v2/posts`. **My question :** **How to unset/disable the default routes while using the `rest_api_init` filter to register new custom routes ?**
2017/03/13
[ "https://Stackoverflow.com/questions/42757726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219200/" ]
[REST API Toolbox](https://wordpress.org/plugins/rest-api-toolbox/) did the job for me. We can handle many things via that plugin. [![enter image description here](https://i.stack.imgur.com/isHvo.png)](https://i.stack.imgur.com/isHvo.png)
I recently had to disable member-only content from appearing in the REST API. Instead of filtering the rest endpoints, I filtered the args used to register the post types: ``` function dbdb_unset_rest_routes( $args, $post_type ) { $allowed_post_types = array( 'page', 'post', 'company', 'job' ); $allowed_post_types = apply_filters( 'dbdb_unset_rest_routes_types', $allowed_post_types ); if( in_array( $post_type, $allowed_post_types ) ){ return $args; } else { $args['show_in_rest'] = 0; } return $args; } add_filter( 'register_post_type_args', 'dbdb_unset_rest_routes', 20, 2 ); ``` The REST API calls `get_post_types()` in `create_initial_rest_routes()` and looks for any post types that have `show_in_rest` set to `true`. By filtering the args via the filter: `register_post_type_args` in `register_post_type()`, we can filter these routes from showing up in the API.
42,757,726
I need to disable default routes of `WP REST API` and add custom routes. I found [this question](https://stackoverflow.com/questions/37816170/rest-api-plugin-wordpress-disable-default-routes) which helps me to find following answer. > > > ``` > remove_action('rest_api_init', 'create_initial_rest_routes', 99); > > ``` > > However this will also remove any custom content type routes. So > instead you may choose to use: > > > > ``` > add_filter('rest_endpoints', function($endpoints) { > if ( isset( $endpoints['/wp/v2/users'] ) ) { > unset( $endpoints['/wp/v2/users'] ); > } > // etc > }); > > ``` > > But from that way I need to know all the default routes and remove one by one which is not a cleanest way to do. I would like to know whether there is any cleaner way to achieve that ? **UPDATE 1 :** As per the Chris's suggestion I would add more details to question. Currently I am using `rest_api_init` filter to add my custom routes by using `register_rest_route` method as per the below code which I found on [this article](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). ``` add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/sample/', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } ); function my_awesome_func( $data ) { return 'somthing'; } ``` The custom route works well, but unfortunately I can't disable the default routes such as `/wp/v2/posts`. **My question :** **How to unset/disable the default routes while using the `rest_api_init` filter to register new custom routes ?**
2017/03/13
[ "https://Stackoverflow.com/questions/42757726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219200/" ]
This question has already accepted answer. But if anybody find this useful. We can easily remove default routes. Add following code in your theme's (child theme's if any) functions.php or in any custom plugin ``` add_filter('rest_endpoints', function( $endpoints ) { foreach( $endpoints as $route => $endpoint ){ if( 0 === stripos( $route, '/wp/' ) ){ unset( $endpoints[ $route ] ); } } return $endpoints; }); ```
I recently had to disable member-only content from appearing in the REST API. Instead of filtering the rest endpoints, I filtered the args used to register the post types: ``` function dbdb_unset_rest_routes( $args, $post_type ) { $allowed_post_types = array( 'page', 'post', 'company', 'job' ); $allowed_post_types = apply_filters( 'dbdb_unset_rest_routes_types', $allowed_post_types ); if( in_array( $post_type, $allowed_post_types ) ){ return $args; } else { $args['show_in_rest'] = 0; } return $args; } add_filter( 'register_post_type_args', 'dbdb_unset_rest_routes', 20, 2 ); ``` The REST API calls `get_post_types()` in `create_initial_rest_routes()` and looks for any post types that have `show_in_rest` set to `true`. By filtering the args via the filter: `register_post_type_args` in `register_post_type()`, we can filter these routes from showing up in the API.
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
Question is old but I want to give a clear answer and explain why this happens for others who comes here: First of all, there is nothing wrong with the JavaScript code line in the question. It is absolutely valid and produces no parsing error. The reason for the problem in Vitalmax' case was most likely because he/she didn't posted additional code, which surrounded that line. Here is an example in PHP, which shows why the JS parser complains about the syntax: ``` <?php echo "alert('Hello again! This is how we\nadd line breaks to an alert box!');"; ?> ``` The parsed server-side output then is (this is what the browser gets): ``` alert("Hello again! This is how we add line breaks to an alert box!"); ``` In JavaScript, strings **must not** have real line breaks.\* Instead, they must always be escaped (like: \n), so the browser complains about an "unterminated string literal" at the real line break. There are some exceptions to this rule, like for horizontal tabulators (\t). So (in this case) you have to escape the line breaks twice with \\n. So when PHP parses and converts it from \\n to \n, JavaScript can convert it from \n to *[real line break]*. Correct PHP example would be: ``` <?php echo "alert('Hello again! This is how we\\nadd line breaks to an alert box!');"; ?> ``` Or: ``` <?php echo 'alert("Hello again! This is how we\nadd line breaks to an alert box!");'; ?> ``` In the second case you don't have to double escape it because escaped characters within PHP strings with single quotes are not decoded (\n stays \n). \*Note: It is possible to use the special quote sign ` which allows real line breaks in JS. Example: ``` alert(`Hello again! This is how we add line breaks to an alert box!`); ```
I had issues where \n and \n didn't work, then I tried using html break tag i.e. since that panel was written in html and it worked. example - ``` some text here <br> some more text ``` output: ``` some text here some more text ```
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
Adding changing `\n` to `\\n` should work if you are rendering the alert serverside (ie: On a website), but if you are running client side (ie: testing etc.) just `\\n` will not work work. For example, try running the following lines on [this](http://jsfiddle.net/) website. ``` alert("Hello again! This is how we"+"\n"+"add line breaks to an alert box!"); ``` or: ``` alert("Hello again! This is how we" +"\\n" +"add line breaks to an alert box!"); ``` In jsfiddle, the first one works, because it runs it client side, but if you are running it serverside, it requires the double slash (`\\n`) I'm not sure why this is, but I have tested it multiple times. Hope this helps!
I had issues where \n and \n didn't work, then I tried using html break tag i.e. since that panel was written in html and it worked. example - ``` some text here <br> some more text ``` output: ``` some text here some more text ```
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
This just happened to me... exactly. I needed to change it to `\\n` instead of `\n`. ``` alert("Hello again! This is how we"+"\\n"+"add line breaks to an alert box!"); ```
``` <script> alert("Hello. \n How are you?") </script> ```
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
This script works for me. ``` <script> alert("Hello. \r\n How are you?"); </script> ```
alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); \n --> this is working [working with \n](https://i.stack.imgur.com/aoQhV.png) \n --> does not work, it just treat it as continuous string of alert msges [does not working with \n](https://i.stack.imgur.com/tmMVi.png)
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
This just happened to me... exactly. I needed to change it to `\\n` instead of `\n`. ``` alert("Hello again! This is how we"+"\\n"+"add line breaks to an alert box!"); ```
Another way is using `String.fromCharCode()`: ``` alert("This unit has been removed from stock" + String.fromCharCode(13) + " Do you wish to RETURN this unit to stock?"); ```
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
Haven't tested but does this work? ``` alert("Hello again! This is how we \n add line breaks to an alert box!"); ```
`error "missing ; before statement"` That tells me the semicolon is missing from above this line of code. Usual syntax gotchya are if statements that don't close parentheses properly. Or curly braces.
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
Haven't tested but does this work? ``` alert("Hello again! This is how we \n add line breaks to an alert box!"); ```
A more functional way i would suggest is to define your own `print()` function and forget about putting `\\n` for each line manually ```js //define var print = new Function("var lines=arguments[0]+'\\n';; for(var i=1;i<arguments.length;i++){lines+=arguments[i]+'\\n';} alert(lines);"); //call print("say","hello","to","javascript","this","is ","awesome"); ``` Now you may call the `print()` with multiple arguments and each argument will be available in a separate line.
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
Adding changing `\n` to `\\n` should work if you are rendering the alert serverside (ie: On a website), but if you are running client side (ie: testing etc.) just `\\n` will not work work. For example, try running the following lines on [this](http://jsfiddle.net/) website. ``` alert("Hello again! This is how we"+"\n"+"add line breaks to an alert box!"); ``` or: ``` alert("Hello again! This is how we" +"\\n" +"add line breaks to an alert box!"); ``` In jsfiddle, the first one works, because it runs it client side, but if you are running it serverside, it requires the double slash (`\\n`) I'm not sure why this is, but I have tested it multiple times. Hope this helps!
This script works for me. ``` <script> alert("Hello. \r\n How are you?"); </script> ```
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
`error "missing ; before statement"` That tells me the semicolon is missing from above this line of code. Usual syntax gotchya are if statements that don't close parentheses properly. Or curly braces.
I had issues where \n and \n didn't work, then I tried using html break tag i.e. since that panel was written in html and it worked. example - ``` some text here <br> some more text ``` output: ``` some text here some more text ```
9,340,223
This code ```js alert("Hello again! This is how we" + "\n" + "add line breaks to an alert box!"); ``` doesn't work. Firefox JavaScript console names error as "unterminated string literal" and points on " symbol before \n. I want to fire an alert with multi-line text. No jQuery please.
2012/02/18
[ "https://Stackoverflow.com/questions/9340223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187192/" ]
Question is old but I want to give a clear answer and explain why this happens for others who comes here: First of all, there is nothing wrong with the JavaScript code line in the question. It is absolutely valid and produces no parsing error. The reason for the problem in Vitalmax' case was most likely because he/she didn't posted additional code, which surrounded that line. Here is an example in PHP, which shows why the JS parser complains about the syntax: ``` <?php echo "alert('Hello again! This is how we\nadd line breaks to an alert box!');"; ?> ``` The parsed server-side output then is (this is what the browser gets): ``` alert("Hello again! This is how we add line breaks to an alert box!"); ``` In JavaScript, strings **must not** have real line breaks.\* Instead, they must always be escaped (like: \n), so the browser complains about an "unterminated string literal" at the real line break. There are some exceptions to this rule, like for horizontal tabulators (\t). So (in this case) you have to escape the line breaks twice with \\n. So when PHP parses and converts it from \\n to \n, JavaScript can convert it from \n to *[real line break]*. Correct PHP example would be: ``` <?php echo "alert('Hello again! This is how we\\nadd line breaks to an alert box!');"; ?> ``` Or: ``` <?php echo 'alert("Hello again! This is how we\nadd line breaks to an alert box!");'; ?> ``` In the second case you don't have to double escape it because escaped characters within PHP strings with single quotes are not decoded (\n stays \n). \*Note: It is possible to use the special quote sign ` which allows real line breaks in JS. Example: ``` alert(`Hello again! This is how we add line breaks to an alert box!`); ```
Use single quotes. ``` alert("Hello again! This is how we"+'\n'+"add line breaks to an alert box!"); ```
8,886,258
**Preface** I've just started getting into Ruby and try to not only learn the language but also some development strategies. As kind of a beginner I'm concentrating on Test and Behaviour Driven Development. (yes, I'm doing both for comparison purposes) With my small software project I'm using * UnitTest (TDD) * Cucumber (BDD) * Rspec (TDD and BDD) On various places I encountered RCov as a tool for telling me how much of my actual code I'm really testing. I set up the following RakeTask in my `Rakefile` for the covarage analysis of the UnitTests: ``` desc "Run RCov to get coverage of UnitTests" Rcov::RcovTask.new(:rcov_units) do |t| t.pattern = 'tests/**/tc_*.rb' t.verbose = true t.rcov_opts << "--html" t.rcov_opts << "--text-summary" t.output_dir = "coverage/tests" end ``` This works fine and I'm getting a nice coloured HTML report in `coverage/tests`. **Problem Introduction** Similar I wrote the following RakeTasks for RCov to be used for coverage analysis of my specs: ``` desc "Run RCov to get coverage of Specs" Rcov::RcovTask.new(:rcov_spec) do |t| t.pattern = 'spec/**/*_spec.rb' t.verbose = true t.rcov_opts << "--html" t.rcov_opts << "--text-summary" t.output_dir = "coverage/spec" end ``` **Problem Definition** However, the generated HTML report in `coverage/spec` looks somehow incomplete and almost failed. None of the tested method bodies are marked as covered and thus red. However, I'm 100% sure they are executed within the specs. Only the lines `def method_name(args)` and `class ClassName` are marked 'green'. (as well lines with `attr_reader :instance_variable`) Am I missing something? --- ``` $: ruby --version ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux] $: rspec --version 2.8.0 $: rcov --version rcov 0.9.11 2010-02-28 $: rake --version rake, version 0.9.2 ```
2012/01/16
[ "https://Stackoverflow.com/questions/8886258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588243/" ]
Make sure that you are requiring rcov early enough. From <http://rubydoc.info/github/relevance/rcov/master/Rcov/CodeCoverageAnalyzer>: > > Note that you must require 'rcov' before the code you want to analyze is parsed (i.e. before it gets loaded or required). You can do that by either invoking ruby with the -rrcov command-line option or just: > > >
I fixed this by adding: `RSpec::Core::Runner.autorun` to the bottom of my spec file; worked even with rspec 2.9
8,886,258
**Preface** I've just started getting into Ruby and try to not only learn the language but also some development strategies. As kind of a beginner I'm concentrating on Test and Behaviour Driven Development. (yes, I'm doing both for comparison purposes) With my small software project I'm using * UnitTest (TDD) * Cucumber (BDD) * Rspec (TDD and BDD) On various places I encountered RCov as a tool for telling me how much of my actual code I'm really testing. I set up the following RakeTask in my `Rakefile` for the covarage analysis of the UnitTests: ``` desc "Run RCov to get coverage of UnitTests" Rcov::RcovTask.new(:rcov_units) do |t| t.pattern = 'tests/**/tc_*.rb' t.verbose = true t.rcov_opts << "--html" t.rcov_opts << "--text-summary" t.output_dir = "coverage/tests" end ``` This works fine and I'm getting a nice coloured HTML report in `coverage/tests`. **Problem Introduction** Similar I wrote the following RakeTasks for RCov to be used for coverage analysis of my specs: ``` desc "Run RCov to get coverage of Specs" Rcov::RcovTask.new(:rcov_spec) do |t| t.pattern = 'spec/**/*_spec.rb' t.verbose = true t.rcov_opts << "--html" t.rcov_opts << "--text-summary" t.output_dir = "coverage/spec" end ``` **Problem Definition** However, the generated HTML report in `coverage/spec` looks somehow incomplete and almost failed. None of the tested method bodies are marked as covered and thus red. However, I'm 100% sure they are executed within the specs. Only the lines `def method_name(args)` and `class ClassName` are marked 'green'. (as well lines with `attr_reader :instance_variable`) Am I missing something? --- ``` $: ruby --version ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux] $: rspec --version 2.8.0 $: rcov --version rcov 0.9.11 2010-02-28 $: rake --version rake, version 0.9.2 ```
2012/01/16
[ "https://Stackoverflow.com/questions/8886258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588243/" ]
I've got similar trouble. I am 100% sure that specs are not executed when I run them win RCov. But they do when I disable RCov. Downgrading RSpec to version 2.6.0 helped me.
I fixed this by adding: `RSpec::Core::Runner.autorun` to the bottom of my spec file; worked even with rspec 2.9
54,707,840
[EDIT] I uninstalled both vagrant and virtualbox. I had virtualbox version 5.0 and latest version of vagrant, now I have the latest version of both(virtual box 6.0.1) , i tried same regular steps and the same undesired output showed up. **vagrant** does not connect to \*vm\*\* on Windows 10 my vagrant ssh output: *"VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine."* I found on search engine that vm for windows 10 is bugged and here is official debugging page <https://github.com/hashicorp/vagrant/issues/9027> I tried it and didn't work for me. However, these may work for someone else: 1- `$vagrant --debug ssh` *undesired output*: check [screenshot](https://www.photobox.co.uk/my/photo/full?photo_id=501665682263) the last line is: INFO interface: Machine: error-exit ["Vagrant::Errors::VMNotRunningError", "VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine."] 2- `$vagrant up; vagrant ssh` *undesired output*: "VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine." 3- `$vagrant provision` *undesired output*: ==> default: VM is not currently running. Please, first bring it up with `vagrant up` then run this command. 4- I followed the steps mentioned here <https://kb.vmware.com/s/article/1007131> and restarted pc then ran vagrant ssh again, *undesired output*: VM must be running to open SSH connection. Run `vagrant up` to start the virtual machine. also tried: vagrant up; vagrant ssh (just in case there is other issues like time out?) undesired output: VM must be running to open SSH connection. Run `vagrant up` to start the virtual machine. 5-finally A- `vagrant destroy` B- `vagrant up` C- `vagrant ssh` *undesired output*: VM must be created before running this command. Run `vagrant up` first. I expect the output to be a **successful connection** between vagrant and vm. like this output [this output](https://www.photobox.co.uk/my/photo/full?photo_id=501665915980) done by Carl My vagrant file: ``` # -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. config.vm.box = "hashicorp/precise64" # Disable automatic box update checking. If you disable this, then # boxes will only be checked for updates when the user runs # `vagrant box outdated`. This is not recommended. # config.vm.box_check_update = false # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. In the example below, # accessing "localhost:8080" will access port 80 on the guest machine. # NOTE: This will enable public access to the opened port # config.vm.network "forwarded_port", guest: 80, host: 8080 # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine and only allow access # via 127.0.0.1 to disable public access # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1" # Create a private network, which allows host-only access to the machine # using a specific IP. # config.vm.network "private_network", ip: "192.168.33.10" # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. # config.vm.network "public_network" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # # config.vm.provider "virtualbox" do |vb| # # Display the VirtualBox GUI when booting the machine # vb.gui = true # # # Customize the amount of memory on the VM: # vb.memory = "1024" # end # # View the documentation for the provider you are using for more # information on available options. # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # config.vm.provision "shell", inline: <<-SHELL # apt-get update # apt-get install -y apache2 # SHELL end ```
2019/02/15
[ "https://Stackoverflow.com/questions/54707840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11002804/" ]
I've tried in diferents elements. ```js $('.test').mouseover(function(e){ console.log('ON'); $(this).removeClass('blue'); $(this).addClass('red'); }).mouseout(function(e){ $(this).removeClass('red'); console.log('OUT'); $(this).addClass('blue'); }); $('#test').mouseenter(function(e){ console.log('IN'); $(this).removeClass('red'); $(this).addClass('yellow'); }).mouseleave(function(e){ $(this).removeClass('yellow'); $(this).removeClass('yellow'); console.log('OUT'); $(this).addClass('red'); }); ``` ```css .test{ width: 60%; height: 60%; margin: 10px auto; } .yellow{ background-color: yellow; } .red{ background-color: red; } .blue{ background-color: blue; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <div class="test yellow"> <p>TEST</p> </div> </html> ``` Your code will be like: ``` $(".vetrina-deluxe-info-container-front").mouseenter(function() { $(this).closest('.js-in-viewport-hook').addClass("in-viewport"); }).mouseleave(function() { $(this).closest('.js-in-viewport-hook').removeClass("in-viewport"); }); ```
Did you try this code: ``` $(".vetrina-deluxe-info-container-front").hover(function() { $(this).closest('.js-in-viewport-hook').toggleClass("in-viewport"); }); ```
54,707,840
[EDIT] I uninstalled both vagrant and virtualbox. I had virtualbox version 5.0 and latest version of vagrant, now I have the latest version of both(virtual box 6.0.1) , i tried same regular steps and the same undesired output showed up. **vagrant** does not connect to \*vm\*\* on Windows 10 my vagrant ssh output: *"VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine."* I found on search engine that vm for windows 10 is bugged and here is official debugging page <https://github.com/hashicorp/vagrant/issues/9027> I tried it and didn't work for me. However, these may work for someone else: 1- `$vagrant --debug ssh` *undesired output*: check [screenshot](https://www.photobox.co.uk/my/photo/full?photo_id=501665682263) the last line is: INFO interface: Machine: error-exit ["Vagrant::Errors::VMNotRunningError", "VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine."] 2- `$vagrant up; vagrant ssh` *undesired output*: "VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine." 3- `$vagrant provision` *undesired output*: ==> default: VM is not currently running. Please, first bring it up with `vagrant up` then run this command. 4- I followed the steps mentioned here <https://kb.vmware.com/s/article/1007131> and restarted pc then ran vagrant ssh again, *undesired output*: VM must be running to open SSH connection. Run `vagrant up` to start the virtual machine. also tried: vagrant up; vagrant ssh (just in case there is other issues like time out?) undesired output: VM must be running to open SSH connection. Run `vagrant up` to start the virtual machine. 5-finally A- `vagrant destroy` B- `vagrant up` C- `vagrant ssh` *undesired output*: VM must be created before running this command. Run `vagrant up` first. I expect the output to be a **successful connection** between vagrant and vm. like this output [this output](https://www.photobox.co.uk/my/photo/full?photo_id=501665915980) done by Carl My vagrant file: ``` # -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. config.vm.box = "hashicorp/precise64" # Disable automatic box update checking. If you disable this, then # boxes will only be checked for updates when the user runs # `vagrant box outdated`. This is not recommended. # config.vm.box_check_update = false # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. In the example below, # accessing "localhost:8080" will access port 80 on the guest machine. # NOTE: This will enable public access to the opened port # config.vm.network "forwarded_port", guest: 80, host: 8080 # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine and only allow access # via 127.0.0.1 to disable public access # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1" # Create a private network, which allows host-only access to the machine # using a specific IP. # config.vm.network "private_network", ip: "192.168.33.10" # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. # config.vm.network "public_network" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # # config.vm.provider "virtualbox" do |vb| # # Display the VirtualBox GUI when booting the machine # vb.gui = true # # # Customize the amount of memory on the VM: # vb.memory = "1024" # end # # View the documentation for the provider you are using for more # information on available options. # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # config.vm.provision "shell", inline: <<-SHELL # apt-get update # apt-get install -y apache2 # SHELL end ```
2019/02/15
[ "https://Stackoverflow.com/questions/54707840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11002804/" ]
I've tried in diferents elements. ```js $('.test').mouseover(function(e){ console.log('ON'); $(this).removeClass('blue'); $(this).addClass('red'); }).mouseout(function(e){ $(this).removeClass('red'); console.log('OUT'); $(this).addClass('blue'); }); $('#test').mouseenter(function(e){ console.log('IN'); $(this).removeClass('red'); $(this).addClass('yellow'); }).mouseleave(function(e){ $(this).removeClass('yellow'); $(this).removeClass('yellow'); console.log('OUT'); $(this).addClass('red'); }); ``` ```css .test{ width: 60%; height: 60%; margin: 10px auto; } .yellow{ background-color: yellow; } .red{ background-color: red; } .blue{ background-color: blue; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <div class="test yellow"> <p>TEST</p> </div> </html> ``` Your code will be like: ``` $(".vetrina-deluxe-info-container-front").mouseenter(function() { $(this).closest('.js-in-viewport-hook').addClass("in-viewport"); }).mouseleave(function() { $(this).closest('.js-in-viewport-hook').removeClass("in-viewport"); }); ```
``` please check this i have added class on hover then i remove the class name when not hovered <p>hover me.</p> <script> $("p").hover(function(){ $(this).css({"color":"blue"}).addClass('color-blue'); }, function(){ $("p").css({"color":"red"}).removeClass('color-blue'); }); </script> ``` <https://jsfiddle.net/gapqc5wb/>
65,254,213
I'm sure this is a pretty universal question, but I somehow can't find any info on it online. I have an e-commerce site with different product prices. I then use Javascript to calculate the total price, but where exactly should I store each pricing value to avoid getting hacked? One tutorial I followed suggest adding the price to each item in the HTML file via a custom attribute, for example data-price="100". This is very convenient and it works, but I also heard hackers could basically tamper with any of the values in an HTML form, so how to prevent them from changing the price to 1 instead of 100? Would it be safer to define the values in the Javascript document instead? Or somewhere else? What is the best practice? Thank you so much!
2020/12/11
[ "https://Stackoverflow.com/questions/65254213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5296877/" ]
Generally, calculating the price of a product on the client-side is a practice that should be avoided. The best way to avoid an attack is to not calculate anything related to money on the client-side, but rather get the information from the server. Maybe you could implement a process to call the server for the price at a given point in the transaction process, initially displaying a calculated price (from your javascript). Edit: answer only.
Never trust the client. If they want to order 27 self-sealing stem bolts which cost 5 quatloos each then your JS might tell *them* that it will cost 135 quatloos but you should never trust their browser for that total. The browser should tell your server that they are ordering 27 self-sealing stem bolts. It's up to the server to determine the final amount to charge. When they make payment you should then compare the sum paid with the server-calculated cost.
14,499,597
PDF documents have hyperlinks to the contents on the same document (analogous to "#section" hrefs for an HTML document). Where's the back button to go back to the page I was on (where I clicked the hyperlink). Let's say I'm on the index of a PDF tutorial, page 4, and I click on Chapter 2's hyperlink in the index that takes me to page 38. Now, if I want to go back to page 4 again, which button or shortcut should I use? Within all browsers, excpet Google Chrome, you can press Alt and the left arrow to achieve this. Is there a similar shortcut within Google Chrome?
2013/01/24
[ "https://Stackoverflow.com/questions/14499597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903186/" ]
AFAIK there is no way to do it with the standard Chrome PDF Viewer. Take a look at their support page <https://support.google.com/chrome/answer/1060734>. You could try requesting this feature but keep in mind that the PDF viewer is part of Chrome, not Chromium.
Alt + Left should be what you want.
14,499,597
PDF documents have hyperlinks to the contents on the same document (analogous to "#section" hrefs for an HTML document). Where's the back button to go back to the page I was on (where I clicked the hyperlink). Let's say I'm on the index of a PDF tutorial, page 4, and I click on Chapter 2's hyperlink in the index that takes me to page 38. Now, if I want to go back to page 4 again, which button or shortcut should I use? Within all browsers, excpet Google Chrome, you can press Alt and the left arrow to achieve this. Is there a similar shortcut within Google Chrome?
2013/01/24
[ "https://Stackoverflow.com/questions/14499597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903186/" ]
AFAIK there is no way to do it with the standard Chrome PDF Viewer. Take a look at their support page <https://support.google.com/chrome/answer/1060734>. You could try requesting this feature but keep in mind that the PDF viewer is part of Chrome, not Chromium.
I think it is simpler to just open the hyperlink in a new tab *e.g.* with the middle mouse button. Then you can just close the tab afterwards.
14,499,597
PDF documents have hyperlinks to the contents on the same document (analogous to "#section" hrefs for an HTML document). Where's the back button to go back to the page I was on (where I clicked the hyperlink). Let's say I'm on the index of a PDF tutorial, page 4, and I click on Chapter 2's hyperlink in the index that takes me to page 38. Now, if I want to go back to page 4 again, which button or shortcut should I use? Within all browsers, excpet Google Chrome, you can press Alt and the left arrow to achieve this. Is there a similar shortcut within Google Chrome?
2013/01/24
[ "https://Stackoverflow.com/questions/14499597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903186/" ]
AFAIK there is no way to do it with the standard Chrome PDF Viewer. Take a look at their support page <https://support.google.com/chrome/answer/1060734>. You could try requesting this feature but keep in mind that the PDF viewer is part of Chrome, not Chromium.
While the builtin pdf reader in Chrome does not support `Alt + Left` you can use [this chrome extension](https://chrome.google.com/webstore/detail/pdf-viewer/oemmndcbldboiebfnladdacbdfmadadm?hl=en), to replace the pdf reader with one that supports the `Alt + Left` functionality that you desire. Moreover, when using this extension, if you press the back button on chrome's address bar it takes you back to the previous view.
14,499,597
PDF documents have hyperlinks to the contents on the same document (analogous to "#section" hrefs for an HTML document). Where's the back button to go back to the page I was on (where I clicked the hyperlink). Let's say I'm on the index of a PDF tutorial, page 4, and I click on Chapter 2's hyperlink in the index that takes me to page 38. Now, if I want to go back to page 4 again, which button or shortcut should I use? Within all browsers, excpet Google Chrome, you can press Alt and the left arrow to achieve this. Is there a similar shortcut within Google Chrome?
2013/01/24
[ "https://Stackoverflow.com/questions/14499597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903186/" ]
I think it is simpler to just open the hyperlink in a new tab *e.g.* with the middle mouse button. Then you can just close the tab afterwards.
Alt + Left should be what you want.
14,499,597
PDF documents have hyperlinks to the contents on the same document (analogous to "#section" hrefs for an HTML document). Where's the back button to go back to the page I was on (where I clicked the hyperlink). Let's say I'm on the index of a PDF tutorial, page 4, and I click on Chapter 2's hyperlink in the index that takes me to page 38. Now, if I want to go back to page 4 again, which button or shortcut should I use? Within all browsers, excpet Google Chrome, you can press Alt and the left arrow to achieve this. Is there a similar shortcut within Google Chrome?
2013/01/24
[ "https://Stackoverflow.com/questions/14499597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903186/" ]
While the builtin pdf reader in Chrome does not support `Alt + Left` you can use [this chrome extension](https://chrome.google.com/webstore/detail/pdf-viewer/oemmndcbldboiebfnladdacbdfmadadm?hl=en), to replace the pdf reader with one that supports the `Alt + Left` functionality that you desire. Moreover, when using this extension, if you press the back button on chrome's address bar it takes you back to the previous view.
Alt + Left should be what you want.
14,499,597
PDF documents have hyperlinks to the contents on the same document (analogous to "#section" hrefs for an HTML document). Where's the back button to go back to the page I was on (where I clicked the hyperlink). Let's say I'm on the index of a PDF tutorial, page 4, and I click on Chapter 2's hyperlink in the index that takes me to page 38. Now, if I want to go back to page 4 again, which button or shortcut should I use? Within all browsers, excpet Google Chrome, you can press Alt and the left arrow to achieve this. Is there a similar shortcut within Google Chrome?
2013/01/24
[ "https://Stackoverflow.com/questions/14499597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903186/" ]
I think it is simpler to just open the hyperlink in a new tab *e.g.* with the middle mouse button. Then you can just close the tab afterwards.
While the builtin pdf reader in Chrome does not support `Alt + Left` you can use [this chrome extension](https://chrome.google.com/webstore/detail/pdf-viewer/oemmndcbldboiebfnladdacbdfmadadm?hl=en), to replace the pdf reader with one that supports the `Alt + Left` functionality that you desire. Moreover, when using this extension, if you press the back button on chrome's address bar it takes you back to the previous view.
18,297,510
I have a NavBar in my web-app using Ruby on Rails and Twitter Bootstrap. The NAVBAR looks well in the browser as: ![NAVBAR in the browser](https://i.stack.imgur.com/6kOus.png) But, the Navbar breaks when I look up the web-app in the browser on my Galaxy Note. ![NAVBAR broken in smaller screen](https://i.stack.imgur.com/Tox0g.png) *Snippet from app/views/layouts/application.html.erb* ``` <div class="masthead"> <h3 class="active"><a href="/">WebsiteName</a></h3> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <ul class="nav"> <li class="active"><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact Us</a></li> <% if current_user %> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <strong><%= current_user.name %></strong> <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="/signout">Sign out</a></li> </ul> <% end %> </ul> </div> </div> </div> </div> ``` **The CSS for the NAVBAR** is borrowed primarily from: Justified Nav Example - <http://getbootstrap.com/2.3.2/examples/justified-nav.html> ``` /* Customize the navbar links to be fill the entire space of the .navbar */ .navbar .navbar-inner { padding: 0; } .navbar .nav { margin: 0; display: table; width: 100%; } .navbar .nav li { display: table-cell; width: 1%; float: none; } .navbar .nav li a { font-weight: bold; text-align: center; border-left: 1px solid rgba(255,255,255,.75); border-right: 1px solid rgba(0,0,0,.1); } .navbar .nav li:first-child a { border-left: 0; border-radius: 3px 0 0 3px; } .navbar .nav li:last-child a { border-right: 0; border-radius: 0 3px 3px 0; } ``` How can I fix this? I am learning Responsive CSS these days, and have no idea how to fix it. **UPDATE:** Please note that the above problem has been fixed. But I found something wrong when this got fixed though. If I decrease the size of window too much, the navbar gets broken. The User part goes outside the navbar. **The issue is also reflected in the Bootstrap example too**. I'm attaching the screenshots which showcase the issue. To see it yourself, simply decrease the window size in the [Bootstrap navbar example](http://getbootstrap.com/2.3.2/examples/justified-nav.html). ![enter image description here](https://i.stack.imgur.com/tNNvM.png) ![enter image description here](https://i.stack.imgur.com/tasvB.png)
2013/08/18
[ "https://Stackoverflow.com/questions/18297510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355722/" ]
**The problem is that the "Contact Us" link is wrapping.** Notice that, in the [Bootstrap example](http://getbootstrap.com/2.3.2/examples/justified-nav.html), the navbar does not have links with multiple words. Add `white-space: nowrap;` to the `.navbar .nav li a` class. Here is a functioning [demo](http://jsfiddle.net/bsJgR/2/). All you have to do is resize the width of the frame to test. The demo contains 2 navbars: * The first navbar with the issue fixed. * The second reproduces the faulty behavior to isolate the cause at the "Contact us" link, by setting its `style` attribute to `"white-space: normal;"` thus overriding the fix. **Also note** that you have a `</li>` missing before `<% end %>`.
define the heihgt of `.navbar .nav` 40px and add `overflow: hidden;`
18,297,510
I have a NavBar in my web-app using Ruby on Rails and Twitter Bootstrap. The NAVBAR looks well in the browser as: ![NAVBAR in the browser](https://i.stack.imgur.com/6kOus.png) But, the Navbar breaks when I look up the web-app in the browser on my Galaxy Note. ![NAVBAR broken in smaller screen](https://i.stack.imgur.com/Tox0g.png) *Snippet from app/views/layouts/application.html.erb* ``` <div class="masthead"> <h3 class="active"><a href="/">WebsiteName</a></h3> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <ul class="nav"> <li class="active"><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact Us</a></li> <% if current_user %> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <strong><%= current_user.name %></strong> <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="/signout">Sign out</a></li> </ul> <% end %> </ul> </div> </div> </div> </div> ``` **The CSS for the NAVBAR** is borrowed primarily from: Justified Nav Example - <http://getbootstrap.com/2.3.2/examples/justified-nav.html> ``` /* Customize the navbar links to be fill the entire space of the .navbar */ .navbar .navbar-inner { padding: 0; } .navbar .nav { margin: 0; display: table; width: 100%; } .navbar .nav li { display: table-cell; width: 1%; float: none; } .navbar .nav li a { font-weight: bold; text-align: center; border-left: 1px solid rgba(255,255,255,.75); border-right: 1px solid rgba(0,0,0,.1); } .navbar .nav li:first-child a { border-left: 0; border-radius: 3px 0 0 3px; } .navbar .nav li:last-child a { border-right: 0; border-radius: 0 3px 3px 0; } ``` How can I fix this? I am learning Responsive CSS these days, and have no idea how to fix it. **UPDATE:** Please note that the above problem has been fixed. But I found something wrong when this got fixed though. If I decrease the size of window too much, the navbar gets broken. The User part goes outside the navbar. **The issue is also reflected in the Bootstrap example too**. I'm attaching the screenshots which showcase the issue. To see it yourself, simply decrease the window size in the [Bootstrap navbar example](http://getbootstrap.com/2.3.2/examples/justified-nav.html). ![enter image description here](https://i.stack.imgur.com/tNNvM.png) ![enter image description here](https://i.stack.imgur.com/tasvB.png)
2013/08/18
[ "https://Stackoverflow.com/questions/18297510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355722/" ]
**The problem is that the "Contact Us" link is wrapping.** Notice that, in the [Bootstrap example](http://getbootstrap.com/2.3.2/examples/justified-nav.html), the navbar does not have links with multiple words. Add `white-space: nowrap;` to the `.navbar .nav li a` class. Here is a functioning [demo](http://jsfiddle.net/bsJgR/2/). All you have to do is resize the width of the frame to test. The demo contains 2 navbars: * The first navbar with the issue fixed. * The second reproduces the faulty behavior to isolate the cause at the "Contact us" link, by setting its `style` attribute to `"white-space: normal;"` thus overriding the fix. **Also note** that you have a `</li>` missing before `<% end %>`.
Your bootstrap file loading should look like the following to make the responsive work: ``` <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.css" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="~/Content/bootstrap-responsive.css" /> ```
30,764,166
I want to use [js beautify](https://github.com/beautify-web/js-beautify) on some source but there isn't a way to detect what type of source it is. Is there any way, crude or not, to detect if the source is css, html, javascript or none? Looking at their [site](http://jsbeautifier.org/) they have this that looks like it'll figure out if it's html: ``` function looks_like_html(source) { // <foo> - looks like html // <!--\nalert('foo!');\n--> - doesn't look like html var trimmed = source.replace(/^[ \t\n\r]+/, ''); var comment_mark = '<' + '!-' + '-'; return (trimmed && (trimmed.substring(0, 1) === '<' && trimmed.substring(0, 4) !== comment_mark)); } ``` just need to see if it's css, javascript or neither. This is running in node.js So this code would need to tell me it's JavaScript: ``` var foo = { bar : 'baz' }; ``` where as this code needs to tell me it's CSS: ``` .foo { background : red; } ``` So a function to test this would return the type: ``` function getSourceType(source) { if (isJs) { return 'js'; } if (isHtml) { return 'html'; } if (isCss) { return 'css'; } } ``` There will be cases where other languages are used like Java where I need to ignore but for css/html/js I can use the beautifier on.
2015/06/10
[ "https://Stackoverflow.com/questions/30764166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925782/" ]
Short answer: Almost impossible. ================================ *- Thanks to Katana's input* **The reason**: A valid HTML can contain JS and CSS (and it usually does). JS can contain both css and html (i.e.: var myContent = '< div >< style >CSS-Rules< script >JS Commands';). And even CSS can contain both in comments. So writing a parser for this close to impossible. You just cannot separate them easily. The languages have rules upon how to write them, what you want to do is reverse architect something and check whether those rules apply. That's probably not worth the effort. --- *Approach 1* If the requirement is worth the effort, you could try to run different parsers on the source and see if they throw errors. I.e. Java is likely to not be a valid HTML/JS/CSS but a valid Java-Code (if written properly). --- *Approach 2* *- Thanks to Bram's input* However if you know the source very well and have the assumption that these things don't occur in your code, you could try the following with Regular Expressions. Example ------- ``` <code><div>This div is HTML var i=32;</div></code> <code>#thisiscss { margin: 0; padding: 0; }</code> <code>.thisismorecss { border: 1px solid; background-color: #0044FF;}</code> <code>function jsfunc(){ { var i = 1; i+=1;<br>}</code> ``` ### Parsing ``` $("code").each(function() { code = $(this).text(); if (code.match(/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2/)) { $(this).after("<span>This is HTML</span>"); } else if (code.match(/(([ trn]*)([a-zA-Z-]*)([.#]{1,1})([a-zA-Z-]*)([ trn]*)+)([{]{1,1})((([ trn]*)([a-zA-Z-]*)([:]{1,1})((([ trn]*)([a-zA-Z-0-9#]*))+)[;]{1})*)([ trn]*)([}]{1,1})([ trn]*)/)) { $(this).after("<span>This is CSS</span>"); } else { $(this).after("<span>This is JS</span>"); } }); ``` What does it do: Parse the text. ### HTML If it contains characters like '<' followed by br (or any of the other tags above) and then '>' then it's html. (Include a check as well since you could compare numbers in js as well). ### CSS If it is made out of the pattern name(optional) followed by . or # followed by id or class followed by { you should get it from here... In the pattern above I also included possible spaces and tabs. ### JS Else it is JS. You could also do Regex like: If it contains '= {' or 'function...' or ' then JS. Also check further for Regular Expressions to check more clearly and/or provide white- and blacklists (like 'var' but no < or > around it, 'function(asdsd,asdsad){assads}' ..) Bram's Start with what I continued was: ``` $("code").each(function() { code = $(this).text(); if (code.match(/^<[^>]+>/)) { $(this).after("<span>This is HTML</span>"); } else if (code.match(/^(#|\.)?[^{]+{/)) { $(this).after("<span>This is CSS</span>"); } }); ``` For more Information: ===================== <http://regexone.com> is a good reference. Also check <http://www.sitepoint.com/jquery-basic-regex-selector-examples/> for inspiration.
It depends if you are allowed to mix languages, as mentioned in the comments (i.e. having embedded JS and CSS in your HTML), or if those are separate files that you need to detect for some reason. A rigorous approach would be to build a tree from the file, where each node would be a statement (in Perl, you can use [HTML::TreeBuilder](http://search.cpan.org/~cjm/HTML-Tree-5.03/lib/HTML/TreeBuilder.pm)). Then you could parse it and compare with the original source. Then proceed by applying eliminating regexes to weed out chunks of code and split languages. Another way would be to search for language-specific patterns (I was thinking that CSS only uses " \*= " in some situations, therefore if you have " = " by itself, must be JavaScript, embedded or not). For HTML you for sure can detect the tags with some regex like ``` if($source =~ m/(<.+>)/){} ``` Basically then you would need to take into account some fancy cases like if the JavaScript is used to display some HTML code ``` var code = "<body>"; ``` Then again it really depends on the situation you are facing, and how the codes mix.
8,038,287
In my app I have a UIWebView-based view controller showing info and credits about the app itself. As part of the info, the app version is displayed, as retrieved from the infoDictionary of the mainBundle. So this string is not in the original HTML; it is set programmatically, by replacing a placeholder. Therefore the sequence is: 1) I load the HTML into a NSString 2) I replace the placeholder with the actual version 3) I show the resulting string in UIWebView by invoking method `loadHTMLString:baseURL:` The HTML also has hyperlinks to some web pages in the internet. Everything is fine, but for this problem: If I touch a hyperlink, and therefore navigate to the corresponding web page, I will not be able to go back to my original info page (canGoBack returns NO, goBack does nothing). Any suggestion? Thanks in advance.
2011/11/07
[ "https://Stackoverflow.com/questions/8038287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681877/" ]
In the end, I have found a satisfactory solution, that I would like to share. 1) I changed the HTML code of my info page, by inserting the following code where I want to show the app version: ``` <p>App version: <script type="text/javascript"> var args = document.location.search.substring(1).split("&"); for (var i in args) { var nameValue = args[i].split("="); if (nameValue[0] == "version") var version = nameValue[1]; } if (version) document.write(version); </script> </p> ``` This piece of code will parse the query part of the URL, looking for a "version=<version>" argument, and use its value to show the app version. 2) When preparing the URL to be used by the UIWebView, I retrieve the app version from the main bundle: ``` NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]; ``` Then I append it at the end of my URL string: ``` NSString* urlString = [NSString stringWithFormat:@"<my_info_page>.html?version=%@", version]; ``` 3) Finally, I use the UIWebView to show the page: ``` NSURL* url = [[NSURL alloc] initWithString:urlString]; NSURLRequest* request [[NSURLRequest alloc] initWithUrl:url]; [mWebView loadRequest:urlRequest]; [urlRequest release]; [url release]; ``` where mWebView is an IBOutlet, of type UIWebView, properly connected to the web view in the XIB file. It works correctly on my iPhone 4, including the back/forward functions of the web view when following hyperlinks, while keeping the user inside the app.
I would break out of the app and load Safari in this case: ``` - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { [[UIApplication sharedApplication] openURL:request.URL]; return NO; } ``` The only downside is that the user comes out of your app. You could put an alertview in that method to warn them first... Alternatively, you'll have to code your own back button.
73,757,353
Cross-posting this question: <https://github.com/PrefectHQ/prefect/discussions/6868> I have a minimal project using Prefect v1.3.1, which you can find here: <https://github.com/b-long/aid> . I'm having a little difficulty getting the deployment right, after migrating from native code to dockerized code. I am using the latest version of Prefect v1 and need to solve this before I'm able to migrate to Prefect 2.x I'm using Poetry, but I'm pretty sure there's a pattern here that would apply to Hatch, Pipenv, Flit or other tooling. The problem is observed in registration which logs this toward the end: ``` ModuleNotFoundError: No module named 'aid' The command '/bin/sh -c python /opt/prefect/healthcheck.py '["/opt/prefect/flows/basic-pandas-flow.prefect"]' '(3, 10)'' returned a non-zero code: 1 Traceback (most recent call last): ... ValueError: Your docker image failed to build! Your flow might have failed one of its deployment health checks - please ensure that all necessary files and dependencies have been included. ``` If you're a Prefect Guru, I'm guessing you'll be able to solve this issue by reading the log file (see discussion linked above) and looking at my Dockerfile: <https://github.com/b-long/aid/blob/main/Dockerfile.prefect>
2022/09/17
[ "https://Stackoverflow.com/questions/73757353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320399/" ]
It looks like your package `aid` is relative to `/` root file system ``` COPY README.md aid/ /aid/ ``` I believe it will work if you make it relative to `/aid` dir (your working dir is `/aid` and so init file need to be in `/aid/aid/__init__.py`) ``` COPY README.md /aid/ COPY aid/ /aid/aid ```
I answered directly on the GitHub issue. Let's keep the discussion there to make it easier to follow everything in one place. Btw, great writeup on the GitHub issue, very helpful!
2,724,977
In Facebook how can I post a message onto a user's wall saying "I scored 8/10 on objects game" then a URL? I really don't want to have to use the full API, as I don't want to handle user login details. I don't mind if Facebook needs to authenticate and then post the message. Is it possible using the new Graph API and JavaScript?
2010/04/27
[ "https://Stackoverflow.com/questions/2724977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235146/" ]
**Note 4/16/2011:** stream.publish seems to have been deprecated, There's a new way to do this: <http://developers.facebook.com/docs/reference/dialogs/feed/> You can use something like this to publish to a wall, the user will need to confirm before it get sent. Don't forget that you'll need to use FB.init and include the JS SDK link. ``` function fb_publish() { FB.ui( { method: 'stream.publish', message: 'Message here.', attachment: { name: 'Name here', caption: 'Caption here.', description: ( 'description here' ), href: 'url here' }, action_links: [ { text: 'Code', href: 'action url here' } ], user_prompt_message: 'Personal message here' }, function(response) { if (response && response.post_id) { alert('Post was published.'); } else { alert('Post was not published.'); } } ); } ```
Considering that you have a proxy to make cross domain calls, you can simply do this... In this example, YourProxyMethod takes a jQuery.ajax like hash, makes a server side post & returns the response in success/error callbacks. Any regular proxy should do. The trick is to include app\_id and access\_token in the URL irself. Also, your FB app should have sufficient permissions to make this call. ``` YourProxyMethod({ url : "https://graph.facebook.com/ID/feed?app_id=APP_ID&access_token=ACCESS_TOKEN", method : "post", params : { message : "message", name : "name", caption : "caption", description : "desc" }, success : function(response) { console.log(response); }, error : function(response) { console.log("Error!"); console.log(response); } }); ```
2,724,977
In Facebook how can I post a message onto a user's wall saying "I scored 8/10 on objects game" then a URL? I really don't want to have to use the full API, as I don't want to handle user login details. I don't mind if Facebook needs to authenticate and then post the message. Is it possible using the new Graph API and JavaScript?
2010/04/27
[ "https://Stackoverflow.com/questions/2724977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235146/" ]
**Note 4/16/2011:** stream.publish seems to have been deprecated, There's a new way to do this: <http://developers.facebook.com/docs/reference/dialogs/feed/> You can use something like this to publish to a wall, the user will need to confirm before it get sent. Don't forget that you'll need to use FB.init and include the JS SDK link. ``` function fb_publish() { FB.ui( { method: 'stream.publish', message: 'Message here.', attachment: { name: 'Name here', caption: 'Caption here.', description: ( 'description here' ), href: 'url here' }, action_links: [ { text: 'Code', href: 'action url here' } ], user_prompt_message: 'Personal message here' }, function(response) { if (response && response.post_id) { alert('Post was published.'); } else { alert('Post was not published.'); } } ); } ```
[Post on wall](http://developers.facebook.com/docs/reference/dialogs/feed) will show a dialog box to share the message on wall or not. But I wanted to post the message silently on user's wall, assuming that user had already given "Post on wall" permission. ``` FB.api('/me/feed', 'post', { message:'my_message', link:YOUR_SITE_URL, picture:picture_url name: 'Post name', description: 'description' },function(data) { console.log(data); }); ```
2,724,977
In Facebook how can I post a message onto a user's wall saying "I scored 8/10 on objects game" then a URL? I really don't want to have to use the full API, as I don't want to handle user login details. I don't mind if Facebook needs to authenticate and then post the message. Is it possible using the new Graph API and JavaScript?
2010/04/27
[ "https://Stackoverflow.com/questions/2724977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235146/" ]
[Post on wall](http://developers.facebook.com/docs/reference/dialogs/feed) will show a dialog box to share the message on wall or not. But I wanted to post the message silently on user's wall, assuming that user had already given "Post on wall" permission. ``` FB.api('/me/feed', 'post', { message:'my_message', link:YOUR_SITE_URL, picture:picture_url name: 'Post name', description: 'description' },function(data) { console.log(data); }); ```
Considering that you have a proxy to make cross domain calls, you can simply do this... In this example, YourProxyMethod takes a jQuery.ajax like hash, makes a server side post & returns the response in success/error callbacks. Any regular proxy should do. The trick is to include app\_id and access\_token in the URL irself. Also, your FB app should have sufficient permissions to make this call. ``` YourProxyMethod({ url : "https://graph.facebook.com/ID/feed?app_id=APP_ID&access_token=ACCESS_TOKEN", method : "post", params : { message : "message", name : "name", caption : "caption", description : "desc" }, success : function(response) { console.log(response); }, error : function(response) { console.log("Error!"); console.log(response); } }); ```
22,521,346
I want to do Facebook Login on a mobile web page. This can be done with a [Facebook Login Button](https://developers.facebook.com/docs/plugins/login-button). It works great. I have the following code in my GWT UiBinder page: ``` <g:HTMLPanel> <div class="fb-login-button" data-max-rows="1" data-size="xlarge" data-show-faces="false" data-auto-logout-link="false" data-scope="email,publish_actions,user_birthday,user_likes" onlogin="alert('I am a JavaScript callback');"></div> </g:HTMLPanel> ``` If login is successful, the `onlogin` JavaScript function is called. **How can I use this callback function somehow to get notified when this function is called? Is there a way to use JSNI or something else here?**
2014/03/20
[ "https://Stackoverflow.com/questions/22521346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1055664/" ]
You can extract the RSA public key from RSA keypair using `d2i_RSAPublicKey` and `i2d_RSAPublicKey` [(link)](http://www.openssl.org/docs/crypto/d2i_RSAPublicKey.html). Use `i2d_RSAPublicKey` to encode your keypair to PKCS#1 RSAPublicKey stucture, store it in a bytestring, then use `d2i_RSAPublicKey` to decode it back to RSA key struct.
Reviewing your code, it appears that you successfully separated the `public` and `private` keys into the strings pub\_key and pri\_key, but then used `printf` to output them which pasted them back together. To just print the `public` key change the printf statement to: ``` printf("\n%s\n", pub_key); ```
22,521,346
I want to do Facebook Login on a mobile web page. This can be done with a [Facebook Login Button](https://developers.facebook.com/docs/plugins/login-button). It works great. I have the following code in my GWT UiBinder page: ``` <g:HTMLPanel> <div class="fb-login-button" data-max-rows="1" data-size="xlarge" data-show-faces="false" data-auto-logout-link="false" data-scope="email,publish_actions,user_birthday,user_likes" onlogin="alert('I am a JavaScript callback');"></div> </g:HTMLPanel> ``` If login is successful, the `onlogin` JavaScript function is called. **How can I use this callback function somehow to get notified when this function is called? Is there a way to use JSNI or something else here?**
2014/03/20
[ "https://Stackoverflow.com/questions/22521346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1055664/" ]
I've found a solution to my question among other Stack-Overflow posts and namely [Reading Public/Private Key from Memory with OpenSSL](https://stackoverflow.com/questions/11886262/reading-public-private-key-from-memory-with-openssl) The answer i was looking for is answered by @SquareRootOfTwentyThree is his last line of code, After extracting the Public key into a BIO variable called pub: ``` PEM_write_bio_RSAPublicKey(pub, keypair); ``` i can send the variable pub across the network, and after it reaches the other side create a RSA variable and put pub inside it: SOLUTION: ``` RSA *keypair2 = NULL; PEM_read_bio_RSAPublicKey( pub, &keypair2, NULL, NULL); ``` After i've done this i can successfully encrypt the message as usual, using keypair2: ENCRYPTION: ``` encrypt = (char*)malloc(RSA_size(keypair)); int encrypt_len; err = (char*)malloc(130); if((encrypt_len = RSA_public_encrypt(strlen(msg)+1, (unsigned char*)msg, (unsigned char*)encrypt, keypair2 ,RSA_PKCS1_OAEP_PADDING)) == -1) { ERR_load_crypto_strings(); ERR_error_string(ERR_get_error(), err); fprintf(stderr, "Error encrypting message: %s\n", err); } ``` I can then send this encrypt variable back to the first machine, and decrypt it as usual, using my original `keypair`, without having to send it over the network. DECRYPTION: ``` decrypt = (char*)malloc(encrypt_len); if(RSA_private_decrypt(encrypt_len, (unsigned char*)encrypt, (unsigned char*)decrypt, keypair, RSA_PKCS1_OAEP_PADDING) == -1) { ERR_load_crypto_strings(); ERR_error_string(ERR_get_error(), err); fprintf(stderr, "Error decrypting message: %s\n", err); } ``` Thank you everyone for contributing to this post!!!
Reviewing your code, it appears that you successfully separated the `public` and `private` keys into the strings pub\_key and pri\_key, but then used `printf` to output them which pasted them back together. To just print the `public` key change the printf statement to: ``` printf("\n%s\n", pub_key); ```
22,521,346
I want to do Facebook Login on a mobile web page. This can be done with a [Facebook Login Button](https://developers.facebook.com/docs/plugins/login-button). It works great. I have the following code in my GWT UiBinder page: ``` <g:HTMLPanel> <div class="fb-login-button" data-max-rows="1" data-size="xlarge" data-show-faces="false" data-auto-logout-link="false" data-scope="email,publish_actions,user_birthday,user_likes" onlogin="alert('I am a JavaScript callback');"></div> </g:HTMLPanel> ``` If login is successful, the `onlogin` JavaScript function is called. **How can I use this callback function somehow to get notified when this function is called? Is there a way to use JSNI or something else here?**
2014/03/20
[ "https://Stackoverflow.com/questions/22521346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1055664/" ]
> > I want to split [the keypair] apart and use them individually to encrypt/decrypt > > > ... Any ideas on how to separate the keys, then maybe put them back together in a "keypair" or maybe how to use them separately to encrypt/decrypt some string variables? > > > You can use `RSAPublicKey_dup` and `RSAPrivateKey_dup`, without the need to round trip them by ASN.1/DER or PEM encoding them. Here, round tripping consist of using a functions like `PEM_write_bio_RSAPublicKey` and `PEM_read_bio_RSAPublicKey`. Below is a sample program that uses them. Its written in C++ (thanks for adding that tag). While you can separate them, they both use the `RSA` structure. The public key has some members set to `NULL`, like the private exponent. --- You can also print the keys with `RSA_print`, `RSA_print_fp` and friends. See [`RSA_print (3)`](https://www.openssl.org/docs/crypto/RSA_print.html) or its use below. --- ``` // g++ -Wall -Wextra -std=c++11 -stdlib=libc++ -I/usr/local/ssl/macosx-x64/include \ // t.cpp -o t.exe /usr/local/ssl/macosx-x64/lib/libcrypto.a #include <memory> using std::unique_ptr; #include <openssl/bn.h> #include <openssl/rsa.h> #include <cassert> #define ASSERT assert using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>; using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>; int main(int argc, char* argv[]) { int rc; RSA_ptr rsa(RSA_new(), ::RSA_free); BN_ptr bn(BN_new(), ::BN_free); rc = BN_set_word(bn.get(), RSA_F4); ASSERT(rc == 1); rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL); ASSERT(rc == 1); RSA_ptr rsa_pub(RSAPublicKey_dup(rsa.get()), ::RSA_free); RSA_ptr rsa_priv(RSAPrivateKey_dup(rsa.get()), ::RSA_free); fprintf(stdout, "\n"); RSA_print_fp(stdout, rsa_pub.get(), 0); fprintf(stdout, "\n"); RSA_print_fp(stdout, rsa_priv.get(), 0); return 0; } ``` Here is the output: ```none $ ./t.exe Public-Key: (2048 bit) Modulus: 00:aa:5a:cc:30:52:f1:e9:49:3d:a6:25:00:33:29: a6:fa:f7:53:e0:3c:73:4c:91:41:66:20:ec:62:1f: 27:2a:2a:6c:0f:90:f8:d9:7e:d5:ec:72:7b:38:8c: ca:12:60:f8:d1:fb:f2:65:7c:b1:3a:b6:4e:26:ba: 5b:86:cc:30:f2:fc:be:c3:a2:00:b9:ea:81:fa:1c: 22:4e:f7:be:a1:1a:66:90:13:b6:12:66:26:23:6d: 22:15:7d:3b:a4:99:44:38:fa:1c:70:63:4e:50:6f: 66:38:6c:f6:1a:13:e1:c7:dc:a6:a1:eb:6f:f9:c9: 59:c8:30:dc:c2:1b:dc:6c:9d:ea:0c:3d:52:5a:00: ea:c9:c9:85:51:21:9f:ec:95:b3:dc:c2:50:21:29: c2:64:6c:1e:34:36:d8:61:59:ab:3c:a2:cc:e8:ef: 57:c3:7f:49:86:be:e3:42:88:1b:39:10:b8:2f:fa: 81:ef:a0:94:99:0c:71:ae:1e:82:7f:e3:6e:00:6e: 02:13:66:bb:a9:31:58:ec:90:39:9c:bc:9c:8c:90: e9:20:f7:20:8e:d6:a3:a3:df:a2:4a:0f:0f:39:b5: 57:b9:ef:6a:27:e0:1a:ed:f6:ce:0d:87:cd:43:03: bf:67:ef:ff:fd:da:98:cc:22:ab:5e:8d:7b:43:d3: 90:4d Exponent: 65537 (0x10001) Private-Key: (2048 bit) modulus: 00:aa:5a:cc:30:52:f1:e9:49:3d:a6:25:00:33:29: a6:fa:f7:53:e0:3c:73:4c:91:41:66:20:ec:62:1f: 27:2a:2a:6c:0f:90:f8:d9:7e:d5:ec:72:7b:38:8c: ca:12:60:f8:d1:fb:f2:65:7c:b1:3a:b6:4e:26:ba: 5b:86:cc:30:f2:fc:be:c3:a2:00:b9:ea:81:fa:1c: 22:4e:f7:be:a1:1a:66:90:13:b6:12:66:26:23:6d: 22:15:7d:3b:a4:99:44:38:fa:1c:70:63:4e:50:6f: 66:38:6c:f6:1a:13:e1:c7:dc:a6:a1:eb:6f:f9:c9: 59:c8:30:dc:c2:1b:dc:6c:9d:ea:0c:3d:52:5a:00: ea:c9:c9:85:51:21:9f:ec:95:b3:dc:c2:50:21:29: c2:64:6c:1e:34:36:d8:61:59:ab:3c:a2:cc:e8:ef: 57:c3:7f:49:86:be:e3:42:88:1b:39:10:b8:2f:fa: 81:ef:a0:94:99:0c:71:ae:1e:82:7f:e3:6e:00:6e: 02:13:66:bb:a9:31:58:ec:90:39:9c:bc:9c:8c:90: e9:20:f7:20:8e:d6:a3:a3:df:a2:4a:0f:0f:39:b5: 57:b9:ef:6a:27:e0:1a:ed:f6:ce:0d:87:cd:43:03: bf:67:ef:ff:fd:da:98:cc:22:ab:5e:8d:7b:43:d3: 90:4d publicExponent: 65537 (0x10001) privateExponent: 66:a4:ce:e3:4f:16:f3:b9:6d:ab:ee:1f:70:b4:68: 28:4f:5d:fa:7e:71:fa:70:8b:37:3e:1f:30:00:15: 59:12:b6:89:aa:90:46:7c:65:e9:52:11:6c:c1:68: 00:2a:ed:c1:98:4d:35:59:2c:70:73:e8:22:ed:a6: b8:51:d0:2c:98:9d:58:c3:04:2d:01:5f:cf:93:a4: 18:70:ae:2b:e3:fc:68:53:78:21:1d:eb:5c:ed:24: dc:4d:d8:e2:14:77:46:dd:6c:c5:4b:10:a4:e6:7a: 71:05:36:44:00:36:ca:75:e8:f1:27:2b:11:16:81: 42:5e:2e:a5:c6:a3:c9:cd:60:59:ce:72:71:76:c8: ca:ba:f0:45:c3:86:07:7b:22:20:c4:74:c6:a8:ab: 7c:2c:f8:de:ea:25:95:81:79:33:54:67:7b:61:91: 80:a8:1f:4c:38:32:d4:4d:2e:a8:7d:9b:d4:1a:3e: 6b:ca:50:3c:a0:61:0e:00:ad:f4:5c:0f:26:1a:59: 00:3c:bd:ee:c3:e8:d0:b8:9b:0e:44:89:49:d1:24: a4:39:15:dc:0e:c5:d5:41:a2:4a:f4:e5:e3:23:c7: 98:8a:87:f7:18:a6:e2:7b:27:83:f6:fb:62:42:46: ae:de:ba:48:ad:07:39:40:da:65:17:d1:d2:ed:df: 01 prime1: 00:dd:dc:70:b5:70:ea:10:20:28:40:a0:c3:b8:70: 6d:3d:84:c0:57:2d:69:fc:e9:d4:55:ed:4f:ac:3d: c2:e9:19:49:f0:ab:c6:bd:99:9e:0f:e5:a4:61:d4: b3:c5:c2:b1:e4:3a:10:ff:e6:cd:ce:6e:2d:93:bc: 87:12:92:87:7c:d3:dd:bc:32:54:9e:fa:67:b1:9d: e2:27:53:e6:03:a7:22:17:45:63:0d:42:f3:96:5d: a3:e0:9c:93:f0:42:8b:bb:95:34:e6:f6:0b:f7:b6: c5:59:a0:b5:2a:71:59:c0:f2:7e:bf:95:2d:dd:6d: 94:23:2a:95:4a:4f:f1:d0:93 prime2: 00:c4:91:6a:33:1b:db:24:eb:fd:d3:69:e9:3c:e2: a2:2d:23:7a:92:65:a8:a0:50:1d:0a:2b:b4:f0:64: e4:40:57:f3:dc:f7:65:18:7d:51:75:73:b9:d6:67: 9b:0e:94:5f:37:02:6c:7f:eb:b9:13:4b:bf:8e:65: 22:0b:2c:c6:8d:2a:a2:88:ec:21:e3:f9:0b:78:b4: 1d:d0:44:e6:36:0d:ec:3c:8f:0a:c7:3b:0d:91:65: b7:de:a3:c9:a3:2a:8c:7f:1f:a1:d2:6e:9b:ee:23: 78:c1:30:76:87:af:a8:11:a4:15:b4:54:16:d8:94: 71:5c:64:30:43:58:b5:07:9f exponent1: 2f:91:e8:88:be:e1:30:fb:f4:25:87:52:ef:e5:0b: 47:39:83:94:2d:a4:a0:19:f2:f1:49:a4:df:a5:8e: 79:34:76:ea:27:aa:c1:54:82:d3:9d:c5:95:44:6a: 17:69:1b:83:77:ff:d5:1e:c3:da:13:3d:aa:83:ad: e2:89:90:8b:6f:52:07:dc:32:d0:b3:98:30:39:4e: 18:68:a0:d4:ff:ad:0b:98:51:18:b2:d6:4f:d3:5c: 23:f8:ee:af:81:55:3c:af:4d:5c:88:3d:20:ac:0b: bc:9f:fc:b8:50:fd:91:a5:6d:0f:df:08:aa:85:a8: 51:b1:fb:b8:a7:53:8e:09 exponent2: 7d:46:0b:7f:ad:06:19:de:c8:b2:7e:f2:25:5a:6e: 6f:04:08:6e:da:99:00:2a:6e:87:77:d9:65:c7:76: ec:46:e1:64:f6:ca:18:34:6d:c0:c3:d3:31:00:70: 82:77:2e:c3:59:29:1a:d1:78:ef:02:3c:7f:9c:96: 78:b6:bd:87:64:1f:97:d1:9d:bb:b3:91:8b:08:87: 63:9f:35:74:47:a5:41:e7:0b:c0:73:33:2f:71:bb: 20:0a:14:4c:87:a6:68:b2:19:28:8a:53:98:0e:45: 3c:22:0d:b8:65:cb:60:0a:c9:c6:56:3d:05:24:7d: a6:9b:37:63:04:5a:c3:13 coefficient: 00:cc:d7:5c:e6:0e:7b:79:d4:cb:4f:6d:82:a7:45: 90:67:90:dc:d3:83:62:f1:4b:17:43:5c:4a:ea:bf: 38:25:c3:6f:34:e2:05:91:5e:60:d6:de:6d:07:1a: 73:71:b3:1d:73:f2:3c:60:ed:ec:42:d4:39:f8:a4: ae:d5:aa:40:1e:90:b1:eb:b1:05:a3:2f:03:5f:c6: b7:07:4c:df:0f:c4:a9:80:8c:31:f5:e2:01:00:73: 8a:25:03:84:4e:48:7a:31:8e:e6:b8:04:4c:44:61: 7d:e4:87:1c:57:4f:45:44:33:bb:f3:ae:1c:d2:e1: 99:ed:78:29:76:4d:8c:6d:91 ``` --- Related, you never ask how to encrypt or decrypt with a RSA key, yet you claim the answer to the encryption and decryption problems is shown in the code in your answer. You seem to have made the question a moving target :) You should probably avoid that on Stack Overflow (I think its OK to do in those user thread forums). On Stack Overflow, you should ask a separate question.
Reviewing your code, it appears that you successfully separated the `public` and `private` keys into the strings pub\_key and pri\_key, but then used `printf` to output them which pasted them back together. To just print the `public` key change the printf statement to: ``` printf("\n%s\n", pub_key); ```
48,780,027
I want to download the bytes of an attachment to an email that is itself an email using Microsoft Graph. My only option at the moment appears to be to use the Get `ItemAttachment` method on the API that looks like this: ``` https://graph.microsoft.com/v1.0/users/myAccount/messages/{messageId}/attac hments/{attachmentId}?$expand=microsoft.graph.itemattachment/item ``` and the returned JSON has an `item` node with this value: ```json { "@odata.type": "#microsoft.graph.message", "id": "", "createdDateTime": "2018-01-18T01:51:02Z", "lastModifiedDateTime": "2018-01-18T01:50:36Z", "receivedDateTime": "2018-01-18T00:21:35Z", "sentDateTime": "2018-01-18T00:21:48Z", "hasAttachments": true, "internetMessageId": "<2097905212.0.1516234908909.JavaMail.root@dszsarapps01r>", "subject": "blah", "importance": "normal", "conversationId": "AAQkADQ3YjdiNWUxLTBmYWQtNDMwYy04YzDFjNgAQAFM3Iqwf0gRHqfUyw2AniAQ=", "isReadReceiptRequested": false, "isRead": true, "isDraft": false, "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADQ3YjdiNWUxLTOWQ4NDFjNgAAAA%3D%3D&exvsurl=1&viewmodel=ReadMessageItem", "body": { "contentType": "text", "content": "some content" }, "sender": { "emailAddress": { "name": "me@somewhere", "address": "me@somewhere" } }, "from": { "emailAddress": { "name": "boo@there", "address": "boo@there" } }, "toRecipients": [ { "emailAddress": { "name": "him@where", "address": "him@where" } } ] } ``` Note that the presence of attachments is indicated by the `hasAttachments` field but the attachments are not visible in the JSON. I suspect that nested attachments/emails (possibly to many levels) are not supported by Graph API but even if it were it would be risky and time-consuming trying to reconstruct the original bytes of the `.eml` attachment from JSON. I would rather treat the `ItemAttachment` as a `FileAttachment` and download its bytes. Does anyone know how to do this?
2018/02/14
[ "https://Stackoverflow.com/questions/48780027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/471955/" ]
I must admit this took me a while to figure out but here it is. Get your email list you should include: - HasAttachments Attachments and also configure it .Expand("attachments") iterate around email messages if email.hasattachment iterate around the attachments{ Attachment content = await MSGraphServiceClient.Me.Messages[email.Id].Attachments[fileAttachment.Id].Request().GetAsync(); // this is the important bit which took me awhile to work out byte[] file = ((FileAttachment)content).ContentBytes; } I hope that helps.
> > I would rather treat the ItemAttachment as a FileAttachment and download its bytes. Does anyone know how to do this? > > > Based on my test, you mentioned Rest API the returned json should be the following format. And you could easily get the **contentBytes**. ``` https://graph.microsoft.com/v1.0/me/messages/{messageid}/attachments/{attachmentId}?$expand=microsoft.graph.itemattachment/item ``` I test it with [graph-explorer](https://developer.microsoft.com/en-us/graph/graph-explorer) ``` { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('userId')/messages('messiageid')/attachments/$entity", "@odata.type": "#microsoft.graph.fileAttachment", "id": "AAMkAGY3ZjQxxxxxxxxxxxxxxxxxxxxx6A=", "lastModifiedDateTime": "2018-02-08T09:58:12Z", "name": "xxx.PNG", "contentType": "image/png", "size": 8419, "isInline": false, "contentId": null, "contentLocation": null, "contentBytes": "iVBORw0KGgoxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ``` [![enter image description here](https://i.stack.imgur.com/iJaQ3.png)](https://i.stack.imgur.com/iJaQ3.png)