first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:
var data : {
name: string;
file: File;
} = {
name: "Name",
file: inputValue.files[0]
};
Then you send it to the Server with JSON.stringify(data)
let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);
ACCESS_COARSE_LOCATION
, ACCESS_FINE_LOCATION
, and WRITE_EXTERNAL_STORAGE
are all part of the Android 6.0 runtime permission system. In addition to having them in the manifest as you do, you also have to request them from the user at runtime (using requestPermissions()
) and see if you have them (using checkSelfPermission()
).
One workaround in the short term is to drop your targetSdkVersion
below 23.
But, eventually, you will want to update your app to use the runtime permission system.
For example, this activity works with five permissions. Four are runtime permissions, though it is presently only handling three (I wrote it before WRITE_EXTERNAL_STORAGE
was added to the runtime permission roster).
/***
Copyright (c) 2015 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.permmonger;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String[] INITIAL_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CONTACTS
};
private static final String[] CAMERA_PERMS={
Manifest.permission.CAMERA
};
private static final String[] CONTACTS_PERMS={
Manifest.permission.READ_CONTACTS
};
private static final String[] LOCATION_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION
};
private static final int INITIAL_REQUEST=1337;
private static final int CAMERA_REQUEST=INITIAL_REQUEST+1;
private static final int CONTACTS_REQUEST=INITIAL_REQUEST+2;
private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;
private TextView location;
private TextView camera;
private TextView internet;
private TextView contacts;
private TextView storage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
location=(TextView)findViewById(R.id.location_value);
camera=(TextView)findViewById(R.id.camera_value);
internet=(TextView)findViewById(R.id.internet_value);
contacts=(TextView)findViewById(R.id.contacts_value);
storage=(TextView)findViewById(R.id.storage_value);
if (!canAccessLocation() || !canAccessContacts()) {
requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
}
}
@Override
protected void onResume() {
super.onResume();
updateTable();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.camera:
if (canAccessCamera()) {
doCameraThing();
}
else {
requestPermissions(CAMERA_PERMS, CAMERA_REQUEST);
}
return(true);
case R.id.contacts:
if (canAccessContacts()) {
doContactsThing();
}
else {
requestPermissions(CONTACTS_PERMS, CONTACTS_REQUEST);
}
return(true);
case R.id.location:
if (canAccessLocation()) {
doLocationThing();
}
else {
requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
}
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
updateTable();
switch(requestCode) {
case CAMERA_REQUEST:
if (canAccessCamera()) {
doCameraThing();
}
else {
bzzzt();
}
break;
case CONTACTS_REQUEST:
if (canAccessContacts()) {
doContactsThing();
}
else {
bzzzt();
}
break;
case LOCATION_REQUEST:
if (canAccessLocation()) {
doLocationThing();
}
else {
bzzzt();
}
break;
}
}
private void updateTable() {
location.setText(String.valueOf(canAccessLocation()));
camera.setText(String.valueOf(canAccessCamera()));
internet.setText(String.valueOf(hasPermission(Manifest.permission.INTERNET)));
contacts.setText(String.valueOf(canAccessContacts()));
storage.setText(String.valueOf(hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)));
}
private boolean canAccessLocation() {
return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
private boolean canAccessCamera() {
return(hasPermission(Manifest.permission.CAMERA));
}
private boolean canAccessContacts() {
return(hasPermission(Manifest.permission.READ_CONTACTS));
}
private boolean hasPermission(String perm) {
return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
}
private void bzzzt() {
Toast.makeText(this, R.string.toast_bzzzt, Toast.LENGTH_LONG).show();
}
private void doCameraThing() {
Toast.makeText(this, R.string.toast_camera, Toast.LENGTH_SHORT).show();
}
private void doContactsThing() {
Toast.makeText(this, R.string.toast_contacts, Toast.LENGTH_SHORT).show();
}
private void doLocationThing() {
Toast.makeText(this, R.string.toast_location, Toast.LENGTH_SHORT).show();
}
}
(from this sample project)
For the requestPermissions() function, should the parameters just be "ACCESS_COARSE_LOCATION"? Or should I include the full name "android.permission.ACCESS_COARSE_LOCATION"?
I would use the constants defined on Manifest.permission
, as shown above.
Also, what is the request code?
That will be passed back to you as the first parameter to onRequestPermissionsResult()
, so you can tell one requestPermissions()
call from another.
So easy way :
XML:
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Java code:
private ViewPager viewPager;
private String[] PAGE_TITLES = new String[]{
"text1",
"text1",
"text3"
};
private final Fragment[] PAGES = new Fragment[]{
new fragment1(),
new fragment2(),
new fragment3()
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_a_requests);
/**TODO ***************tebLayout*************************/
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
tabLayout.setSelectedTabIndicatorHeight((int) (4 *
getResources().getDisplayMetrics().density));
tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"),
Color.parseColor("#0d0e10"));
tabLayout.setupWithViewPager(viewPager);
/***************************************************************************/
}
The solution for the issue:
public class yourRecyclerViewAdapter extends RecyclerView.Adapter<yourRecyclerViewAdapter.yourViewHolder> {
private static CheckBox lastChecked = null;
private static int lastCheckedPos = 0;
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mTextView.setText(fonts.get(position).getName());
holder.checkBox.setChecked(fonts.get(position).isSelected());
holder.checkBox.setTag(new Integer(position));
//for default check in first item
if(position == 0 && fonts.get(0).isSelected() && holder.checkBox.isChecked())
{
lastChecked = holder.checkBox;
lastCheckedPos = 0;
}
holder.checkBox.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
CheckBox cb = (CheckBox)v;
int clickedPos = ((Integer)cb.getTag()).intValue();
if(cb.isChecked())
{
if(lastChecked != null)
{
lastChecked.setChecked(false);
fonts.get(lastCheckedPos).setSelected(false);
}
lastChecked = cb;
lastCheckedPos = clickedPos;
}
else
lastChecked = null;
fonts.get(clickedPos).setSelected(cb.isChecked);
}
});
}
}
Hope this help!
If you want to achieve filtering with custom model class in kotlin
then you can implement below code.
Step 1:
Add SearchView
in your xml
file and then in your activity
or fragment
implement SearchView.OnQueryTextListener
class SearchActivity : AppCompatActivity(),SearchView.OnQueryTextListener {
lateinit var sectionModelArrayList: ArrayList<CategorySectionModel>
lateinit var filteredArrayList: ArrayList<CategorySectionModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_updated)
searchView.setOnQueryTextListener(this)
}
//Called this method with you own data to populate the recycler view.
private fun parseJson() {
rv_category_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
adapter = CategoryLabelAdapter(sectionModelArrayList, this)
rv_category_list.adapter = adapter
}
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
adapter.filter!!.filter(newText.toString())
return false
}
My model class
CategorySectionModel
looks like
class CategorySectionModel(val categoryLabel: String, val categoryItemList: ArrayList<CategoryItem>)
Now we have to work on adapter class and there you need to implement Filterable
interface and override getFilter()
method like below
class CategoryLabelAdapter(internal var data: ArrayList<CategorySectionModel>?, internal var activity: Context) : RecyclerView.Adapter<CategoryLabelAdapter.ViewHolder>(), Filterable {
val originalList = data
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item_category_name, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return data!!.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
data?.get(position)?.let { holder.bindItem(it) }
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@SuppressLint("SetTextI18n")
fun bindItem(data: CategorySectionModel) {
itemView.tv_category_name.text = data.categoryLabel
}
}
override fun getFilter(): Filter? {
return object : Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
val results = FilterResults()
if (constraint.isEmpty()) {
//no filter implemented we return full list
results.values = data
results.count = data!!.size
} else {
//Here we perform filtering operation
val list: ArrayList<CategorySectionModel> = ArrayList()
for (p in data!!) {
if (p.categoryLabel.toUpperCase().startsWith(constraint.toString().toUpperCase())) list.add(p)
}
results.values = list
results.count = list.size
}
return results
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0 || constraint == "") {
data = originalList
notifyDataSetChanged()
} else {
data = results.values as ArrayList<CategorySectionModel>?
notifyDataSetChanged()
}
}
}
}
}
There is no option to set a min or max value in seekbar , so you can use a formula here to scale your value.
Desired_value = ( progress * ( Max_value - Min_value) / 100 ) + Min_value
I have tested this formula in many examples. In your example, if the progressBar is the middle(i.e. progress = 50 ) and your Min_val and Max_val are 60 and 180 respectively, then this formula will give you the Desired_value '120'.
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("aaaa")
}
}
This is the simplest hack:
fun getCurrentFragment(): Fragment? {
return if (count == 0) null
else instantiateItem(view_pager, view_pager.currentItem) as? Fragment
}
(kotlin code)
Just call instantiateItem(viewPager, viewPager.getCurrentItem()
and cast it to Fragment
. Your item would already be instantiated. To be sure you can add a check for getCount
.
Works with both FragmentPagerAdapter
and FragmentStatePagerAdapter
!
Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
RadioButton rb= (RadioButton) findViewById(checkedId);
team = rb.getText().toString();
}
});
Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here
Just take note of the Controller, it has an alias of homeCtrl.
module MongoAngular {
var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);
app.config([
'$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
$routeProvider
.when('/Home', {
templateUrl: '/PartialViews/Home/home.html',
controller: 'HomeController as homeCtrl'
})
.otherwise({ redirectTo: '/Home' });
}])
.config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
restangularProvider.setBaseUrl('/api');
}]);
}
And here's the way to use it...
ng-click="homeCtrl.addCustomer(customer)"
Try it.. It might work for you as it worked for me... ;)
Based on previous statements, for better performance, you can also add an if condition
if (player.isPlaying() {
handler.postDelayed(..., 1000);
}
In your XML for the image view, where you have android:background="@drawable/thumbs_down
change this to android:src="@drawable/thumbs_down"
Currently it is placing that image as the background to the view and not the actual image in it.
From Google documentation:
You can hide the navigation bar on Android 4.0 and higher using the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. This snippet hides both the navigation bar and the status bar:
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
http://developer.android.com/training/system-ui/navigation.html
You can also post runnable using the view from any other thread. But be sure that the view is not null:
tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});
According to the Documentation:
"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."
Here is a simple method which can avoid the use of PhonestateListener
and other complications.
So here we are receiving the 3 events from android such as RINGING
,OFFHOOK
and IDLE
. And in order to get the all possible state of call,we need to define our own states like RINGING
, OFFHOOK
, IDLE
, FIRST_CALL_RINGING
, SECOND_CALL_RINGING
.
It can handle every states in a phone call.
Please think in a way that we are receiving events from android and we will define our on call states. See the code.
public class CallListening extends BroadcastReceiver {
private static final String TAG ="broadcast_intent";
public static String incoming_number;
private String current_state,previus_state,event;
public static Boolean dialog= false;
private Context context;
private SharedPreferences sp,sp1;
private SharedPreferences.Editor spEditor,spEditor1;
public void onReceive(Context context, Intent intent) {
//Log.d("intent_log", "Intent" + intent);
dialog=true;
this.context = context;
event = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "The received event : "+event+", incoming_number : " + incoming_number);
previus_state = getCallState(context);
current_state = "IDLE";
if(incoming_number!=null){
updateIncomingNumber(incoming_number,context);
}else {
incoming_number=getIncomingNumber(context);
}
switch (event) {
case "RINGING":
Log.d(TAG, "State : Ringing, incoming_number : " + incoming_number);
if((previus_state.equals("IDLE")) || (previus_state.equals("FIRST_CALL_RINGING"))){
current_state ="FIRST_CALL_RINGING";
}
if((previus_state.equals("OFFHOOK"))||(previus_state.equals("SECOND_CALL_RINGING"))){
current_state = "SECOND_CALL_RINGING";
}
break;
case "OFFHOOK":
Log.d(TAG, "State : offhook, incoming_number : " + incoming_number);
if((previus_state.equals("IDLE")) ||(previus_state.equals("FIRST_CALL_RINGING")) || previus_state.equals("OFFHOOK")){
current_state = "OFFHOOK";
}
if(previus_state.equals("SECOND_CALL_RINGING")){
current_state ="OFFHOOK";
startDialog(context);
}
break;
case "IDLE":
Log.d(TAG, "State : idle and incoming_number : " + incoming_number);
if((previus_state.equals("OFFHOOK")) || (previus_state.equals("SECOND_CALL_RINGING")) || (previus_state.equals("IDLE"))){
current_state="IDLE";
}
if(previus_state.equals("FIRST_CALL_RINGING")){
current_state = "IDLE";
startDialog(context);
}
updateIncomingNumber("no_number",context);
Log.d(TAG,"stored incoming number flushed");
break;
}
if(!current_state.equals(previus_state)){
Log.d(TAG, "Updating state from "+previus_state +" to "+current_state);
updateCallState(current_state,context);
}
}
public void startDialog(Context context) {
Log.d(TAG,"Starting Dialog box");
Intent intent1 = new Intent(context, NotifyHangup.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
}
public void updateCallState(String state,Context context){
sp = PreferenceManager.getDefaultSharedPreferences(context);
spEditor = sp.edit();
spEditor.putString("call_state", state);
spEditor.commit();
Log.d(TAG, "state updated");
}
public void updateIncomingNumber(String inc_num,Context context){
sp = PreferenceManager.getDefaultSharedPreferences(context);
spEditor = sp.edit();
spEditor.putString("inc_num", inc_num);
spEditor.commit();
Log.d(TAG, "incoming number updated");
}
public String getCallState(Context context){
sp1 = PreferenceManager.getDefaultSharedPreferences(context);
String st =sp1.getString("call_state", "IDLE");
Log.d(TAG,"get previous state as :"+st);
return st;
}
public String getIncomingNumber(Context context){
sp1 = PreferenceManager.getDefaultSharedPreferences(context);
String st =sp1.getString("inc_num", "no_num");
Log.d(TAG,"get incoming number as :"+st);
return st;
}
}
The valueChangeListener
is only necessary, if you are interested in both the old and the new value.
If you are only interested in the new value, the use of <p:ajax>
or <f:ajax>
is the better choice.
There are several possible reasons, why the ajax call won't work. First you should change the method signature of the handler method: drop the parameter. Then you can access your managed bean variable directly:
public void handleChange(){
System.out.println("here "+ getEmp().getEmployeeName());
}
At the time, the listener is called, the new value is already set. (Note that I implicitly assume that the el expression mymb.emp.employeeName
is correctly backed by the corresponding getter/setter methods.)
You want getActivity()
inside your class. It's better to use
yourclassname.this.getActivity()
Try this. It's helpful for you.
Darwind code didn't show the keyboard.
This works for me:
_searchText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(_searchText, InputMethodManager.SHOW_IMPLICIT);
in case the keyboard is not showing, try to force:
imm.showSoftInput(_searchText, InputMethodManager.SHOW_FORCED);
In Kotlin you can try this way to handle getActivity() null condition.
activity.let { // activity == getActivity() in java
//your code here
}
It will check activity is null or not and if not null then execute inner code.
Have your Activity
implement OnFocusChangeListener()
if you want a factorized use of this interface,
example:
public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{
In your OnCreate
you can add a listener for example:
editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);
then android studio will prompt you to add the method from the interface, accept it... it will be like:
@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}
and as you've got a factorized code, you'll just have to do that:
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
editTextResearch.setText("");
editTextMyWords.setText("");
editTextPhone.setText("");
}
if (!hasFocus){
editTextResearch.setText("BlaBlaBla");
editTextMyWords.setText(" One Two Tree!");
editTextPhone.setText("\"your phone here:\"");
}
}
anything you code in the !hasFocus
is for the behavior of the item that loses focus, that should do the trick! But beware that in such state, the change of focus might overwrite the user's entries!
Try this answer,
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);
Note: only for API 11+
I hope this will help you:
final TextView t1=new TextView(this);
t1.setText("Hello Android");
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
t1.setTextSize(progress);
Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();
}
});
The below code is the only thing worked for me
1. Use this class to declare a HeightWrappingViewPager:
public class HeightWrappingViewPager extends ViewPager {
public HeightWrappingViewPager(Context context) {
super(context);
}
public HeightWrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
// Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
// At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
// super has to be called in the beginning so the child views can be initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
// super has to be called again so the new specs are treated as exact measurements
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
2. Insert the height wrapping view pager to your xml file:
<com.project.test.HeightWrappingViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.project.test.HeightWrappingViewPager>
3. Declare your view pager:
HeightWrappingViewPager mViewPager;
mViewPager = (HeightWrappingViewPager) itemView.findViewById(R.id.pager);
CustomAdapter adapter = new CustomAdapter(context);
mViewPager.setAdapter(adapter);
mViewPager.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
you may also go for a simple View.OnClickListener
:
satView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(((CompoundButton) view).isChecked()){
System.out.println("Checked");
} else {
System.out.println("Un-Checked");
}
}
});
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
}
});
I used a try - catch block to solve the issue temporarily.
// Unregister Observer - Stop monitoring the underlying data source.
if (mDataSetChangeObserver != null) {
// Sometimes the Fragment onDestroy() unregisters the observer before calling below code
// See <a>http://stackoverflow.com/questions/6165070/receiver-not-registered-exception-error</a>
try {
getContext().unregisterReceiver(mDataSetChangeObserver);
mDataSetChangeObserver = null;
}
catch (IllegalArgumentException e) {
// Check wether we are in debug mode
if (BuildConfig.IS_DEBUG_MODE) {
e.printStackTrace();
}
}
}
There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.
When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.
If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.
AutoService
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
Backout restores or undoes our changes. The way it does this is that, P4 undoes the changes in a changelist (default or new) on our local workspace. We then have to submit/commit this backedout changelist as we do other changeslists. The second part is important here, as it doesn't automatically backout the changelist on the server, we have to submit the backedout changelist (which makes sense after you do it, but i was initially assuming it does that automatically).
As pointed by others, Rollback has greater powers - It can restore changes to a specific date, changelist or a revision#
The accepted answer correctly addresses the OP's question based on his example. However, it only applies when ToList
is applied to a concrete collection; it does not hold when the elements of the source sequence have yet to be instantiated (due to deferred execution). In case of the latter, you might get a new set of items each time you call ToList
(or enumerate the sequence).
Here is an adaptation of the OP's code to demonstrate this behaviour:
public static void RunChangeList()
{
var objs = Enumerable.Range(0, 10).Select(_ => new MyObject() { SimpleInt = 0 });
var whatInt = ChangeToList(objs); // whatInt gets 0
}
public static int ChangeToList(IEnumerable<MyObject> objects)
{
var objectList = objects.ToList();
objectList.First().SimpleInt = 5;
return objects.First().SimpleInt;
}
Whilst the above code may appear contrived, this behaviour can appear as a subtle bug in other scenarios. See my other example for a situation where it causes tasks to get spawned repeatedly.
This was nice solution from here
InputFilter filter= new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
String checkMe = String.valueOf(source.charAt(i));
Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.d("", "invalid");
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
Just restating what Tomasz said.
There are many examples of FOO__in=...
style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:
users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])
# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])
The double underscore (__) syntax is used all over the place when working with querysets.
This is late to the game, but I found the most awesome-est command line command for this problem. Done using bash. Enjoy.
svn status | grep -v excluding | sed 's/^A */"/g; s/$/"/g' | tr '\n' ' ' | xargs svn commit -m "My Message"
Ok, so here's an explanation of the command. Some things will need to be changed based on your use case.
svn status
I get a list of all the files. They'll all start with those status characters (?, !, A, etc). Each is on its own lines
grep -v excluding
I use grep to filter the list. It can either be used normally (to include) or with the -v flag (to exclude). In this case, it's being used to exclude, with a phrase "excluding" being what will be excluded.
sed 's/^. */"/g; s/$/"/g'
Now I remove the status character and whitespace at the beginning of each line, and then quote each line, using sed. Some of my filenames have spaces in them, hence the quoting.
tr '\n' ' '
Using tr, I replace all newlines with spaces. Now my entire list of files to commit is on one line.
xargs svn commit -m "My Message"
Lastly, I use xargs to execute my commit command with the message. It does the commit, and drops my quoted file list as the last argument.
The result is that everything ultimately works the way that I want it to. I still kind of hate svn for forcing me to jump through these goddamn hoops, but I can live with this. I guess.
If they fall into logical groups, I would probably go with the class approach already listed here.
Many people seem to forget that you can actually select several items by id in the same jQuery selector, as well:
$("#div1, #div2, #div3").show();
Where 'div1', 'div2', and 'div3' are all id attributes on various divs you want to show at once.
case when field1>0 then field2/field1 else 0 end as field3
This one works on Bootstrap 4.3.1.
Jsfiddle: https://jsfiddle.net/ko6L31w4/1/
The HTML code might be a little bit messy because I create a slightly complex dropdown menu for comprehensive test, otherwise everything is pretty straight forward.
Js includes fewer ways to collapse opened dropdowns and CSS only includes minimal styles for full functionalities.
$(function() {_x000D_
$("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
_x000D_
//method 1: remove show from sibilings and their children under your first parent_x000D_
_x000D_
/* if (!$(this).next().hasClass('show')) {_x000D_
_x000D_
$(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
} */ _x000D_
_x000D_
_x000D_
//method 2: remove show from all siblings of all your parents_x000D_
$(this).parents('.dropdown-submenu').siblings().find('.show').removeClass("show");_x000D_
_x000D_
$(this).siblings().toggleClass("show");_x000D_
_x000D_
_x000D_
//collapse all after nav is closed_x000D_
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
$('.dropdown-submenu .show').removeClass("show");_x000D_
});_x000D_
_x000D_
});_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu>.dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-white py-3 shadow-sm">_x000D_
<div class="container-fluid">_x000D_
<a href="#" class="navbar-brand font-weight-bold">Multilevel Dropdown</a>_x000D_
_x000D_
<button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
_x000D_
_x000D_
<div id="navbarContent" class="collapse navbar-collapse">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
_x000D_
<!-- nav dropdown -->_x000D_
<li class="nav-item dropdown">_x000D_
_x000D_
<a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle">Dropdown</a>_x000D_
<ul class="dropdown-menu">_x000D_
_x000D_
<li><a href="#" class="dropdown-item">Some action</a></li>_x000D_
_x000D_
<!-- lvl 1 dropdown -->_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
_x000D_
<!-- lvl 2 dropdown -->_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
_x000D_
<!-- lvl 3 dropdown --> _x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 3</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 4</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">Some other action</a></li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
<ul class="dropdown-menu">_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
</ul>_x000D_
</li> _x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="nav-item"><a href="#" class="nav-link">About</a></li>_x000D_
<li class="nav-item"><a href="#" class="nav-link">Services</a></li>_x000D_
<li class="nav-item"><a href="#" class="nav-link">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
The transform CSS property lets you rotate, scale, skew, or translate an element.
So you can easily use the transform: scale(2.5);
option to scale 2.5 times for example.
(The typical method would be to use plot
just once to set up the limits, possibly to include the range of all series combined, and then to use points
and lines
to add the separate series.) To use plot
multiple times with par(new=TRUE)
you need to make sure that your first plot has a proper ylim
to accept the all series (and in another situation, you may need to also use the same strategy for xlim):
# first plot
plot(x, y1, ylim=range(c(y1,y2)))
# second plot EDIT: needs to have same ylim
par(new = TRUE)
plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")
This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":
matplot(x, cbind(y1,y2))
matplot(x, cbind(y1,y2), pch=1)
I got this error because I was mistakenly calling a method to remove a specific row from my recyclerview multiple times. I had a method like:
void removeFriends() {
final int loc = data.indexOf(friendsView);
data.remove(friendsView);
notifyItemRemoved(loc);
}
I was accidentally calling this method three times instead of once, so the second time loc
was -1 and the error was given when it tried to remove it. The two fixes were to ensure the method was only called once, and also to add a sanity check like this:
void removeFriends() {
final int loc = data.indexOf(friendsView);
if (loc > -1) {
data.remove(friendsView);
notifyItemRemoved(loc);
}
}
Ok so I was having this issue where I tried several different options.
The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts
I was able to apply it... eventually here is my working code
I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)
@font-face{
font-family: "Ubuntu-LI";
src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}
*{
font-family:"Ubuntu-LI";
}
If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like
h1{
font-family: Sans-sarif;
}
From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font
Instead of passing reference object passed the saved object, below is explanation which solve my issue:
//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)
//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)
Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).
$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));
$('#checkbox1').change(function() {
$('#textbox1').val($(this).is(':checked'));
});
$('#checkbox1').click(function() {
if (!$(this).is(':checked')) {
if(!confirm("Are you sure?"))
{
$("#checkbox1").prop("checked", true);
$('#textbox1').val($(this).is(':checked'));
}
}
});
});
As stated above, the checked state of the object should be included within object properties. In some cases you may need also to change the object selection state by clicking on the object itself and let the CheckBox inform about the actual state (either selected or unselected). The checkbox will then use the state of the object at the actual position of the given adapter which is (by default/in most cases) the position of the element in the list.
Check the snippet below, it may be useful.
import android.content.Context;_x000D_
import android.graphics.Bitmap;_x000D_
import android.net.Uri;_x000D_
import android.provider.MediaStore;_x000D_
import android.support.v7.widget.RecyclerView;_x000D_
import android.view.LayoutInflater;_x000D_
import android.view.View;_x000D_
import android.view.ViewGroup;_x000D_
import android.widget.CheckBox;_x000D_
import android.widget.CompoundButton;_x000D_
import android.widget.ImageView;_x000D_
_x000D_
import java.io.File;_x000D_
import java.io.IOException;_x000D_
import java.util.List;_x000D_
_x000D_
public class TakePicImageAdapter extends RecyclerView.Adapter<TakePicImageAdapter.ViewHolder>{_x000D_
private Context context;_x000D_
private List<Image> imageList;_x000D_
_x000D_
public TakePicImageAdapter(Context context, List<Image> imageList) {_x000D_
this.context = context;_x000D_
this.imageList = imageList;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public TakePicImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
View view= LayoutInflater.from(context).inflate(R.layout.image_item,parent,false);_x000D_
return new ViewHolder(view);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onBindViewHolder(final TakePicImageAdapter.ViewHolder holder, final int position) {_x000D_
File file=new File(imageList.get(position).getPath());_x000D_
try {_x000D_
Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(file));_x000D_
holder.image.setImageBitmap(bitmap_x000D_
);_x000D_
} catch (IOException e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
holder.selectImage.setOnCheckedChangeListener(null);_x000D_
holder.selectImage.setChecked(imageList.get(position).isSelected());_x000D_
holder.selectImage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {_x000D_
@Override_x000D_
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {_x000D_
holder.selectImage.setChecked(isChecked);_x000D_
imageList.get(position).setSelected(isChecked);_x000D_
}_x000D_
});_x000D_
holder.image.setOnClickListener(new View.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(View v) {_x000D_
if (imageList.get(position).isSelected())_x000D_
{_x000D_
imageList.get(position).setSelected(false);_x000D_
holder.selectImage.setChecked(false);_x000D_
}else_x000D_
{_x000D_
imageList.get(position).setSelected(true);_x000D_
holder.selectImage.setChecked(true);_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public int getItemCount() {_x000D_
return imageList.size();_x000D_
}_x000D_
_x000D_
public class ViewHolder extends RecyclerView.ViewHolder {_x000D_
public ImageView image;public CheckBox selectImage;_x000D_
public ViewHolder(View itemView) {_x000D_
super(itemView);_x000D_
image=(ImageView)itemView.findViewById(R.id.image);_x000D_
selectImage=(CheckBox) itemView.findViewById(R.id.ch);_x000D_
_x000D_
}_x000D_
}_x000D_
}
_x000D_
You are missing a 'b' I think?
sudo service mongod start
should be
sudo service mongodb start
I think this is the case?
Never thought MS could distribute this way, I understand that people downloading Visual Studio should have advanced knowledge of computers and OS but this is like a jump in time to 30 years back.
If you want the executable:
System.Reflection.Assembly.GetEntryAssembly().Location
If you want the assembly that's consuming your library (which could be the same assembly as above, if your code is called directly from a class within your executable):
System.Reflection.Assembly.GetCallingAssembly().Location
If you'd like just the filename and not the path, use:
Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)
A little hacky, but I created an array called "console", and anytime I wanted to output to console I pushed to the array. Then whenever I wanted to see the actual output, I just returned console
instead of whatever I was returning before.
//return 'console' //uncomment to output console
return "actual output";
}
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;
I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.
I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following:
sudo find . -name *.conf
then sudo nano ./data/pg_hba.conf
then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5
and pgAdmin automatically logged me in.
This also worked in pg_hba.conf file
host all all md5
without any IP address and this also worked with my IP address host all all <myip>/32 md5
As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.
The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
Would be better to use a regex here then:
textTitle.replace(/ /g, '%20');
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
Try enabling basic authentication and disabling the other authentications in IIS, then try launching the application. The application will ask for windows credentials. Enter the same and the app should be able to get the name under HttpContext.Current.User.Identity.Name.
You mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration
Two easy ways:
Using hive conf
hive> set USER_NAME='FOO';
hive> select * from foobar where NAME = '${hiveconf:USER_NAME}';
Using hive vars
On your CLI set vars and then use them in hive
set hivevar:USER_NAME='FOO';
hive> select * from foobar where NAME = '${USER_NAME}';
hive> select * from foobar where NAME = '${hivevar:USER_NAME}';
Documentation: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+VariableSubstitution
Thanks Michael Konietzka (https://stackoverflow.com/a/4996583/1019307) for your answer.
I did this in Eclipse / STS:
Preferences > General > Content Types > Selected "Text"
(which contains all types such as CSS, Java Source Files, ...)
Added "UTF-8" to the default encoding box down the bottom and hit 'Add'
Bingo, error gone!
Actually link to .well-know
is on the first tab of your realm settings - but link doesn't look like link, but as value of text box... bad ui design.
Screenshot of Realm's General Tab
Use LINQ .Cast<int>()
to convert 2D array to IEnumerable<int>
.
LINQPad example:
var arr = new int[,] {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);
Output:
Most likely you're looking for something like
var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();
provided that this is not something which happens on page load, in which case it should already be there from the start.
var classname=$('#div1').attr('class')
You could do below:
select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20,
iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30,
iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40,
50 ) ) ) as commission
from table
Use isset
, empty
or array_key_exists
(especially for array keys) before accessing a variable whose existence you are not sure of. So change the order in your second example:
if (!isset($_SESSION['something']) || $_SESSION['something'] == '')
getrusage() can help you in determining the usage of current process or its child
Update: I can't remember an API. But all details will be in /proc/PID/stat, so if we could parse it, we can get the percentage.
EDIT: Since CPU % is not straight forward to calculate, You could use sampling kind of stuff here. Read ctime and utime for a PID at a point in time and read the same values again after 1 sec. Find the difference and divide by hundred. You will get utilization for that process for past one second.
(might get more complex if there are many processors)
if you do the outer join (with the count), and then use this result as a sub-table, you can get 0 as expected (thanks to the nvl function)
Ex:
select P.person_id, nvl(A.nb_apptmts, 0) from
(SELECT person.person_id
FROM person) P
LEFT JOIN
(select person_id, count(*) as nb_apptmts
from appointment
group by person_id) A
ON P.person_id = A.person_id
I am dissatisfied with the previous two answers to create read only properties because the first solution allows the readonly attribute to be deleted and then set and doesn't block the __dict__
. The second solution could be worked around with testing - finding the value that equals what you set it two and changing it eventually.
Now, for the code.
def final(cls):
clss = cls
@classmethod
def __init_subclass__(cls, **kwargs):
raise TypeError("type '{}' is not an acceptable base type".format(clss.__name__))
cls.__init_subclass__ = __init_subclass__
return cls
def methoddefiner(cls, method_name):
for clss in cls.mro():
try:
getattr(clss, method_name)
return clss
except(AttributeError):
pass
return None
def readonlyattributes(*attrs):
"""Method to create readonly attributes in a class
Use as a decorator for a class. This function takes in unlimited
string arguments for names of readonly attributes and returns a
function to make the readonly attributes readonly.
The original class's __getattribute__, __setattr__, and __delattr__ methods
are redefined so avoid defining those methods in the decorated class
You may create setters and deleters for readonly attributes, however
if they are overwritten by the subclass, they lose access to the readonly
attributes.
Any method which sets or deletes a readonly attribute within
the class loses access if overwritten by the subclass besides the __new__
or __init__ constructors.
This decorator doesn't support subclassing of these classes
"""
def classrebuilder(cls):
def __getattribute__(self, name):
if name == '__dict__':
from types import MappingProxyType
return MappingProxyType(super(cls, self).__getattribute__('__dict__'))
return super(cls, self).__getattribute__(name)
def __setattr__(self, name, value):
if name == '__dict__' or name in attrs:
import inspect
stack = inspect.stack()
try:
the_class = stack[1][0].f_locals['self'].__class__
except(KeyError):
the_class = None
the_method = stack[1][0].f_code.co_name
if the_class != cls:
if methoddefiner(type(self), the_method) != cls:
raise AttributeError("Cannot set readonly attribute '{}'".format(name))
return super(cls, self).__setattr__(name, value)
def __delattr__(self, name):
if name == '__dict__' or name in attrs:
import inspect
stack = inspect.stack()
try:
the_class = stack[1][0].f_locals['self'].__class__
except(KeyError):
the_class = None
the_method = stack[1][0].f_code.co_name
if the_class != cls:
if methoddefiner(type(self), the_method) != cls:
raise AttributeError("Cannot delete readonly attribute '{}'".format(name))
return super(cls, self).__delattr__(name)
clss = cls
cls.__getattribute__ = __getattribute__
cls.__setattr__ = __setattr__
cls.__delattr__ = __delattr__
#This line will be moved when this algorithm will be compatible with inheritance
cls = final(cls)
return cls
return classrebuilder
def setreadonlyattributes(cls, *readonlyattrs):
return readonlyattributes(*readonlyattrs)(cls)
if __name__ == '__main__':
#test readonlyattributes only as an indpendent module
@readonlyattributes('readonlyfield')
class ReadonlyFieldClass(object):
def __init__(self, a, b):
#Prevent initalization of the internal, unmodified PrivateFieldClass
#External PrivateFieldClass can be initalized
self.readonlyfield = a
self.publicfield = b
attr = None
def main():
global attr
pfi = ReadonlyFieldClass('forbidden', 'changable')
###---test publicfield, ensure its mutable---###
try:
#get publicfield
print(pfi.publicfield)
print('__getattribute__ works')
#set publicfield
pfi.publicfield = 'mutable'
print('__setattr__ seems to work')
#get previously set publicfield
print(pfi.publicfield)
print('__setattr__ definitely works')
#delete publicfield
del pfi.publicfield
print('__delattr__ seems to work')
#get publicfield which was supposed to be deleted therefore should raise AttributeError
print(pfi.publlicfield)
#publicfield wasn't deleted, raise RuntimeError
raise RuntimeError('__delattr__ doesn\'t work')
except(AttributeError):
print('__delattr__ works')
try:
###---test readonly, make sure its readonly---###
#get readonlyfield
print(pfi.readonlyfield)
print('__getattribute__ works')
#set readonlyfield, should raise AttributeError
pfi.readonlyfield = 'readonly'
#apparently readonlyfield was set, notify user
raise RuntimeError('__setattr__ doesn\'t work')
except(AttributeError):
print('__setattr__ seems to work')
try:
#ensure readonlyfield wasn't set
print(pfi.readonlyfield)
print('__setattr__ works')
#delete readonlyfield
del pfi.readonlyfield
#readonlyfield was deleted, raise RuntimeError
raise RuntimeError('__delattr__ doesn\'t work')
except(AttributeError):
print('__delattr__ works')
try:
print("Dict testing")
print(pfi.__dict__, type(pfi.__dict__))
attr = pfi.readonlyfield
print(attr)
print("__getattribute__ works")
if pfi.readonlyfield != 'forbidden':
print(pfi.readonlyfield)
raise RuntimeError("__getattr__ doesn't work")
try:
pfi.__dict__ = {}
raise RuntimeError("__setattr__ doesn't work")
except(AttributeError):
print("__setattr__ works")
del pfi.__dict__
raise RuntimeError("__delattr__ doesn't work")
except(AttributeError):
print(pfi.__dict__)
print("__delattr__ works")
print("Basic things work")
main()
There is no point to making read only attributes except when your writing library code, code which is being distributed to others as code to use in order to enhance their programs, not code for any other purpose, like app development. The __dict__
problem is solved, because the __dict__
is now of the immutable types.MappingProxyType
, so attributes cannot be changed through the __dict__
. Setting or deleting __dict__
is also blocked. The only way to change read only properties is through changing the methods of the class itself.
Though I believe my solution is better than of the previous two, it could be improved. These are this code's weaknesses:
Doesn't allow adding to a method in a subclass which sets or deletes a readonly attribute. A method defined in a subclass is automatically barred from accessing a readonly attribute, even by calling the superclass' version of the method.
The class' readonly methods can be changed to defeat the read only restrictions.
However, there is not way without editing the class to set or delete a read only attribute. This isn't dependent on naming conventions, which is good because Python isn't so consistent with naming conventions. This provides a way to make read only attributes that cannot be changed with hidden loopholes without editing the class itself. Simply list the attributes to be read only when calling the decorator as arguments and they will become read only.
Credit to Brice's answer for getting the caller classes and methods.
On Java 1.8 default TLS protocol is v1.2. On Java 1.6 and 1.7 default is obsoleted TLS1.0. I get this error on Java 1.8, because url use old TLS1.0 (like Your - You see ClientHello, TLSv1
). To resolve this error You need to use override defaults for Java 1.8.
System.setProperty("https.protocols", "TLSv1");
More info on the Oracle blog.
In Python 2 use the tkFileDialog
module.
import tkFileDialog
tkFileDialog.askopenfilename()
In Python 3 use the tkinter.filedialog
module.
import tkinter.filedialog
tkinter.filedialog.askopenfilename()
It depends on what you need the result for.
If you are sure that there's going to be only 1 row, use implicit cursor:
DECLARE
v_foo foobar.foo%TYPE;
v_bar foobar.bar%TYPE;
BEGIN
SELECT foo,bar FROM foobar INTO v_foo, v_bar;
-- Print the foo and bar values
dbms_output.put_line('foo=' || v_foo || ', bar=' || v_bar);
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- No rows selected, insert your exception handler here
WHEN TOO_MANY_ROWS THEN
-- More than 1 row seleced, insert your exception handler here
END;
If you want to select more than 1 row, you can use either an explicit cursor:
DECLARE
CURSOR cur_foobar IS
SELECT foo, bar FROM foobar;
v_foo foobar.foo%TYPE;
v_bar foobar.bar%TYPE;
BEGIN
-- Open the cursor and loop through the records
OPEN cur_foobar;
LOOP
FETCH cur_foobar INTO v_foo, v_bar;
EXIT WHEN cur_foobar%NOTFOUND;
-- Print the foo and bar values
dbms_output.put_line('foo=' || v_foo || ', bar=' || v_bar);
END LOOP;
CLOSE cur_foobar;
END;
or use another type of cursor:
BEGIN
-- Open the cursor and loop through the records
FOR v_rec IN (SELECT foo, bar FROM foobar) LOOP
-- Print the foo and bar values
dbms_output.put_line('foo=' || v_rec.foo || ', bar=' || v_rec.bar);
END LOOP;
END;
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
you can chain more than 2 conditions too :
if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ]
then
printf "\033[2J";printf "\033[0;0H"
cat << EOF_PRINT_USAGE
$0 - Purpose: upsert qto http json data to postgres db
USAGE EXAMPLE:
$0 -a foo -a bar
EOF_PRINT_USAGE
exit 1
fi
Taking up @ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.
The error appears when you check whether an array was empty or not.
if np.array([1,2]): print(1)
--> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
.
if np.array([1,2])[0]: print(1)
--> no ValueError, but: if np.array([])[0]: print(1)
--> IndexError: index 0 is out of bounds for axis 0 with size 0
.
if np.array([1]): print(1)
--> no ValueError, but again will not help at an array with many elements.
if np.array([]): print(1)
--> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.
Doing so:
if np.array([]).size: print(1)
solved the error.For SpreadSheetGear users (a C# framework for interacting easier with spreadsheets) try this:
workbook.Worksheets[0].Cells["B1:B4"].HorizontalAlignment = HAlign.Center;
.
This will align all the cells in your sheet from B1 to B4 (column 2- row 1 through 4).
Add this in your build.gradle
configurations.all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
exclude group: 'org.springframework.boot', module: 'logback-classic'
}
Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.
Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.
Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.
To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
above line was giving me an error. So I wrote down in below way which is working fine for me.
<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>
Maybe someone else might get same error. Look at this guys!
Using 400
status codes for any other purpose than indicating that the request is malformed is just plain wrong.
If the request payload contains a byte-sequence that could not be parsed as application/json
(if the server expects that dataformat), the appropriate status code is 415
:
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
If the request payload is syntactically correct but semantically incorrect, the non-standard 422
response code may be used, or the standard 403
status code:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.
for i in range(0,len(0,100)):
SOMECALCULATEDARRAY = .......
if(i==0):
finalArrayCollection = SOMECALCULATEDARRAY
else:
finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)
This is mainly useful when the shape of the array is unknown
The previous answers may describe the best understanding about the difference between .NET Core, .NET Standard and .NET Framework, so I just want to share my experience when choosing this over that.
In the project that you need to mix between .NET Framework, .NET Core and .NET Standard. For example, at the time we build the system with .NET Core 1.0, there is no support for Window Services hosting with .NET Core.
The next reason is we were using Active Report which doesn't support .NET Core.
So we want to build an infrastructure library that can be used for both .NET Core (ASP.NET Core) and Windows Service and Reporting (.NET Framework) -> That's why we chose .NET Standard for this kind of library. Choosing .NET standard means you need to carefully consider every class in the library should be simple and cross .NET (Core, Framework, and Standard).
Conclusion:
Microsoft just announced .NET 5: Introducing .NET 5
I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.
One possible solution:
function ConvertFirstCharacterToUpperCase(text) {
return text.substr(0, 1).toUpperCase() + text.substr(1);
}
Use this:
alert(ConvertFirstCharacterToUpperCase("this is string"));
Here is working JS Fiddle
Try this command:
aws s3api list-objects --bucket your-bucket --prefix sub-dir-path --output text --query 'Contents[].{Key: Key}'
Then you can pipe this into a grep to get specific file types to do whatever you want with them.
In Windows 7 and later, this will do the trick for you
The menu item Copy as Path is not available in Windows XP.
Suppose you run your program thus (using sh
syntax):
myprog arg1 arg2 'arg 3'
If you declared your main as int main(int argc, char *argv[])
, then (in most environments), your main()
will be called as if like:
p = { "myprog", "arg1", "arg2", "arg 3", NULL };
exit(main(4, p));
However, if you declared your main as int main()
, it will be called something like
exit(main());
and you don't get the arguments passed.
Two additional things to note:
main
. If a particular platform accepts extra arguments or a different return type, then that's an extension and should not be relied upon in a portable program.*argv[]
and **argv
are exactly equivalent, so you can write int main(int argc, char *argv[])
as int main(int argc, char **argv)
.You are trying to min-max scale the values of audio
between -1 and +1 and image
between 0 and 255.
Using sklearn.preprocessing.minmax_scale
, should easily solve your problem.
e.g.:
audio_scaled = minmax_scale(audio, feature_range=(-1,1))
and
shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)
note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.
Honestly this is bad advice from npm
. An installation can run arbitrary scripts and running it with sudo
can be extremely dangerous! You could do sudo npm install -g less
to install it globally, but instead I would recommend updating your npm settings:
#~/.npmrc
prefix=~/.npm_modules
Then you can update your path:
#~/.bashrc or ~/.zshrc, etc.
export PATH=$PATH:$HOME/.npm_modules/bin
Then you don't require root permissions to perform the installation and you can still use the binary.
This would only apply to your user, however. If you want the entire system to be able to use the module you would have to tell everyone to add your path. More complicated and robust solutions would include adding a folder with node modules / binaries that a group could install to and adding that to everyone's path.
sure,
just have to create a ".gitignore" on the home directory of your project and have to contain
*.swp
that's it
in one command
project-home-directory$ echo '*.swp' >> .gitignore
Although in most general cases the error is quite clearly that file handles have not been closed, I just encountered an instance with JDK7 on Linux that well... is sufficiently ****ed up to explain here.
The program opened a FileOutputStream (fos), a BufferedOutputStream (bos) and a DataOutputStream (dos). After writing to the dataoutputstream, the dos was closed and I thought everything went fine.
Internally however, the dos, tried to flush the bos, which returned a Disk Full error. That exception was eaten by the DataOutputStream, and as a consequence the underlying bos was not closed, hence the fos was still open.
At a later stage that file was then renamed from (something with a .tmp) to its real name. Thereby, the java file descriptor trackers lost track of the original .tmp, yet it was still open !
To solve this, I had to first flush the DataOutputStream myself, retrieve the IOException and close the FileOutputStream myself.
I hope this helps someone.
As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
I hit the same problem on my laptop(win 10) with Wireshark(version 3.2.0), and I tried all the above solutions but unfortunately don't help.
So,
I uninstall the Wireshark bluntly and reinstall it.
After that, this problem solved.
Putting the solution here, and wish it may help someone......
Get data from the URL and then call json.loads
e.g.
Python3 example:
import urllib.request, json
with urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=google") as url:
data = json.loads(url.read().decode())
print(data)
Python2 example:
import urllib, json
url = "http://maps.googleapis.com/maps/api/geocode/json?address=google"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
The output would result in something like this:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Charleston and Huff",
"short_name" : "Charleston and Huff",
"types" : [ "establishment", "point_of_interest" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
...
The steps I needed to perform were:
System.Web.Http.WebHost
.App_Start\WebApiConfig.cs
(see code snippet below).System.Web.Http
in Global.asax.cs
.WebApiConfig.Register(GlobalConfiguration.Configuration)
in MvcApplication.Application_Start()
(in file Global.asax.cs
), before registering the default Web Application route as that would otherwise take precedence.System.Web.Http.ApiController
.I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Update 10.16.2015:
Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.
Weird! You are saying that you want to generate a recursion of 1<<15 depth???!!!!
I'd suggest DON'T try it. The size of the stack will be 2^15 * sizeof(stack-frame)
. I don't know what stack-frame size is, but 2^15 is 32.768. Pretty much... Well, if it stops at 1024 (2^10) you'll have to make it 2^5 times bigger, it is, 32 times bigger than with your actual setting.
All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.
The python equivalent of NULL
is called None
(good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:
class Node:
def __init__(self): #object initializer to set attributes (fields)
self.val = 0
self.right = None
self.left = None
And then it works pretty much like you would expect:
node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()
Note that unlike in NULL
in C, None
is not a "pointer to nowhere": it is actually the only instance of class NoneType
.
Therefore, as None
is a regular object, you can test for it just like any other object:
if node.left == None:
print("The left node is None/Null.")
Although since None
is a singleton instance, it is considered more idiomatic to use is
and compare for reference equality:
if node.left is None:
print("The left node is None/Null.")
In my case I had something like this in my AndroidManifest
,
javaCompileOptions {
annotationProcessorOptions {
arguments = [
'androidManifestFile': 'app\\build\\intermediates\\merged_manifests\\debug\\processDebugManifest\\merged\\AndroidManifest.xml'
]
}
}
here the 'androidManifestFile' location is wrong, changed it to
"androidManifestFile": "$projectDir/src/main/AndroidManifest.xml".toString()
everything worked
Slight tweak to answer from @divbyzero above to fix sonar security warnings
CloseableHttpClient getInsecureHttpClient() throws GeneralSecurityException {
TrustStrategy trustStrategy = (chain, authType) -> true;
HostnameVerifier hostnameVerifier = (hostname, session) -> hostname.equalsIgnoreCase(session.getPeerHost());
return HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(trustStrategy).build(), hostnameVerifier))
.build();
}
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
Yes, but its generally a very bad idea to force another thread to interrupt on a random line of code. You would only do this if you intend to shutdown the process.
What you can do is to use Thread.interrupt()
for a task after a certain amount of time. However, unless the code checks for this it won't work. An ExecutorService can make this easier with Future.cancel(true)
Its much better for the code to time itself and stop when it needs to.
I had this issue when running an app within VS. All I had to do was run the program as Administrator once, then I could run from within VS.
To run as Administrator, just navigate to your debug folder in windows explorer. Right-click on the program and choose Run as administrator.
A new JUnit test method:
@${testType:newType(org.junit.Test)}
public void ${testname}() throws Exception {
${staticImport:importStatic('org.junit.Assert.*')}${cursor}
String expected = "" ;
String actual = "" ;
Assert.assertEquals(expected, actual);
}
instead of this
=IIf((CountRows("ScannerStatisticsData")=0),False,True)
write only the expression when you want to hide
CountRows("ScannerStatisticsData")=0
or change the order of true and false places as below
=IIf((CountRows("ScannerStatisticsData")=0),True,False)
because the Visibility expression set up the Hidden value. that you can find above the text area as
" Set expression for: Hidden "
How about this? Perhaps it's not "the most elegant", but it seems pretty complete and clear:
if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...
For strings like that, for me the most comfortable way to do it is doubling the ' or ", as explained in the MySQL manual:
There are several ways to include quote characters within a string:
A “'” inside a string quoted with “'” may be written as “''”. A “"” inside a string quoted with “"” may be written as “""”. Precede the quote character by an escape character (“\”). A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a
Strings quoted with “'” need no special treatment.
It is from http://dev.mysql.com/doc/refman/5.0/en/string-literals.html.
Use Invoke-RestMethod
to consume REST-APIs. Save the JSON to a string and use that as the body, ex:
$JSON = @'
{"@type":"login",
"username":"[email protected]",
"password":"yyy"
}
'@
$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
If you use Powershell 3, I know there have been some issues with Invoke-RestMethod
, but you should be able to use Invoke-WebRequest
as a replacement:
$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.
$JSON = @{
"@type" = "login"
"username" = "[email protected]"
"password" = "yyy"
} | ConvertTo-Json
thanks php-b-grader !
below the generic function for window.open pass values using POST:
function windowOpenInPost(actionUrl,windowName, windowFeatures, keyParams, valueParams)
{
var mapForm = document.createElement("form");
var milliseconds = new Date().getTime();
windowName = windowName+milliseconds;
mapForm.target = windowName;
mapForm.method = "POST";
mapForm.action = actionUrl;
if (keyParams && valueParams && (keyParams.length == valueParams.length)){
for (var i = 0; i < keyParams.length; i++){
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = keyParams[i];
mapInput.value = valueParams[i];
mapForm.appendChild(mapInput);
}
document.body.appendChild(mapForm);
}
map = window.open('', windowName, windowFeatures);
if (map) {
mapForm.submit();
} else {
alert('You must allow popups for this map to work.');
}}
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
If you were only interested in 'z', you could create a function-based index.
CREATE INDEX users_z_idx ON users (INSTR(last_name,'z'))
Then your query would use WHERE INSTR(last_name,'z') > 0
.
With this approach you would have to create a separate index for each character you might want to search for. I suppose if this is something you do often, it might be worth creating one index for each letter.
Also, keep in mind that if your data has the names capitalized in the standard way (e.g., "Zaxxon"), then both your example and mine would not match names that begin with a Z. You can correct for this by including LOWER in the search expression: INSTR(LOWER(last_name),'z')
.
It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).
Here is a nice CANCEL SIP Call Flow illustration.
The best way is not to write any initializing statements. This is because if you write
int a[]=new int[3]
then by default, in Java all the values of array i.e. a[0]
, a[1]
and a[2]
are initialized to 0
! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.
I ended up doing something like this for AngularJS in case someone stumbles across this question:
const imageElem = angular.element('#awardImg');
if (imageElem[0].files[0])
vm.award.imageElem = imageElem;
vm.award.image = imageElem[0].files[0];
And then:
if (vm.award.imageElem)
$('#awardImg').replaceWith(vm.award.imageElem);
delete vm.award.imageElem;
I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.
IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.
check out the documentation and the demo.
I re-added all of my non-.NET dependencies / references and it did the trick.
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
use Below command in terminal
php artisan cache:clear
php artisan route:cache
php artisan config:cache
php artisan view:clear
Within the push
method of hashHistory
, you can specify your query parameters. For instance,
history.push({
pathname: '/dresses',
search: '?color=blue'
})
or
history.push('/dresses?color=blue')
You can check out this repository for additional examples on using history
I just had the same problem and...
declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)
or even shorter:
declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users
I needed the same thing and found the following working for me:
git log -n1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'
The --date=format
formats the date output where the --pretty
tells what to print.
You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt
Now, Next add this downloaded files into your project:
Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93
You could use Linq.
var prod = from p in prods
where p.ID != 1
select p;
I had the same issue inside an alpine docker container, my solution was to add the boost-dev apk library because libboost-dev was not available.
According to "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, following is the definition of tree height:
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf, and the height of a tree is the height of its root. The height of a tree is also equal to the largest depth of any node in the tree.
Following is my ruby solution. Most of the people forgot about height of empty tree or tree of single node in their implementation.
def height(node, current_height)
return current_height if node.nil? || (node.left.nil? && node.right.nil?)
return [height(node.left, current_height + 1), height(node.right, current_height + 1)].max if node.left && node.right
return height(node.left, current_height + 1) if node.left
return height(node.right, current_height + 1)
end
You could use this one-liner:
data = (data[:75] + '..') if len(data) > 75 else data
pip
is a command line tool, not Python syntax.
In other words, run the command in your console, not in the Python interpreter:
pip install beautifulsoup4
You may have to use the full path:
C:\Python27\Scripts\pip install beautifulsoup4
or even
C:\Python27\Scripts\pip.exe install beautifulsoup4
Windows will then execute the pip
program and that will use Python to install the package.
Another option is to use the Python -m
command-line switch to run the pip
module, which then operates exactly like the pip
command:
python -m pip install beautifulsoup4
or
python.exe -m pip install beautifulsoup4
Do you have the SSH2 extension available?
Docs: http://www.php.net/manual/en/function.ssh2-exec.php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.
Old thread I know.......
Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.
I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).
Before you add any drag or drop operation to an event you have to call this function first:
simulateTouchEvents(<object>);
You can also block all components/children for input or to speed up event handling by using the following syntax:
simulateTouchEvents(<object>, true); // ignore events on childs
Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).
function simulateTouchEvents(oo,bIgnoreChilds)
{
if( !$(oo)[0] )
{ return false; }
if( !window.__touchTypes )
{
window.__touchTypes = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
}
$(oo).bind('touchstart touchmove touchend', function(ev)
{
var bSame = (ev.target == this);
if( bIgnoreChilds && !bSame )
{ return; }
var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
e = ev.originalEvent;
if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type] )
{ return; } //allow multi-touch gestures to work
var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;
if( b || window.__touchInputs[ev.target.tagName] )
{ return; } //allow default clicks to work (and on inputs)
// https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(newEvent);
e.preventDefault();
ev.stopImmediatePropagation();
ev.stopPropagation();
ev.preventDefault();
});
return true;
};
What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.
Result: Every element on a draggable element is still working.
Happy coding, greetz, Erwin Haantjes
Insert a coloured box the full size of the slide, set colour to white with 100% transparency. select all, right-click save as picture, select PNG and save.
copy/paste inserted colour box to each slide and repeat
It's a language abstraction - some languages have both, some one, some neither.
In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new
to allocate memory in a loop without calling delete
to free it it. But make a system backup before doing this.
At the end of each switch case, just add the break
-statement to resolve this problem
switch (manu)
{
case manufacturers.Nokia:
_phanefact = new NokiaFactory();
break;
case manufacturers.Samsung:
_phanefact = new SamsungFactory();
break;
}
for me worked changing the filesystem from Read-Only before running vim:
bash-3.2# mount -o remount rw /
For new gTLDs
/^((?!-)[\p{L}\p{N}-]+(?<!-)\.)+[\p{L}\p{N}]{2,}$/iu
sapply = "!f() { git stash apply \"$(git stash list | awk -F: --posix -vpat=\"$*\" \"$ 0 ~ pat {print $ 1; exit}\")\"; }; f"
git sapply "<regex>"
Edit: I sticked to my original solution, but I see why majority would prefer Etan Reisner's version (above). So just for the record:
sapply = "!f() { git stash apply \"$(git stash list | grep -E \"$*\" | awk \"{ print $ 1; }\" | sed -n \"s/://;1p\")\"; }; f"
You can also do the following:
paste the css code files to file created above
<?php
$minCss=' <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">';
$business = '<link href="bootstrap/css/modern-business.css" rel="stylesheet">';
echo $minCss;
echo $business;
?>
in the html header, include the css files as follows
<?php include_once 'includes/bootstrap_css.php'; ?>
HTML5 supports contenteditable,
<table border="3">
<thead>
<tr>Heading 1</tr>
<tr>Heading 2</tr>
</thead>
<tbody>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
</tbody>
</table>
To quote the mdn entry on contenteditable
The attribute must take one of the following values:
true or the empty string, which indicates that the element must be editable;
false, which indicates that the element must not be editable.
If this attribute is not set, its default value is inherited from its parent element.
This attribute is an enumerated one and not a Boolean one. This means that the explicit usage of one of the values true, false or the empty string is mandatory and that a shorthand ... is not allowed.
// wrong not allowed
<label contenteditable>Example Label</label>
// correct usage
<label contenteditable="true">Example Label</label>.
$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";
if(count($words) == 101){
$words[100] = " ... ";
}
$shown_string = implode(" ", $words);
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
Just adding my suggestion for a resolution, I had a copy of a VM server for developing and testing, I created the database on that with 'sa' having ownership on the db.
I then restored the database onto the live VM server but I was getting the same error mentioned even though the data was still returning correctly. I looked up the 'sa' user mappings and could see it wasn't mapped to the database when I tried to apply the mapping I got a another error "Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405". so I ran this instead
ALTER AUTHORIZATION ON DATABASE::dbname TO sa
I rechecked the user mappings and it was now assigned to my db and it fixed a lot of access issues for me.
If you have a fixed div
just absolute position it at 50% from the top and 50% left and negative margin top and left of half the height and width respectively. Adjust to your needs:
div {
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 300px;
margin-left: -250px;
margin-top: -150px;
}
You could have is_hammer
in terms of row["Open"]
etc. as follows
def is_hammer(rOpen,rLow,rClose,rHigh):
return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
and closed_in_top_half_of_range(rHigh,rLow,rClose)
Then you can use map:
df["isHammer"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])
To create a new screen with the name foo
, use
screen -S foo
Then to reattach it, run
screen -r foo # or use -x, as in
screen -x foo # for "Multi display mode" (see the man page)
$http({
url: 'http://localhost:8080/example/teste',
dataType: 'json',
method: 'POST',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});
Try like this.
Running a function only once after component mounts is such a common pattern that it justifies a hook of it's own that hides implementation details.
const useMountEffect = (fun) => useEffect(fun, [])
Use it in any functional component.
function MyComponent() {
useMountEffect(function) // function will run only once after it has mounted.
return <div>...</div>;
}
About the useMountEffect hook
When using useEffect
with a second array argument, React will run the callback after mounting (initial render) and after values in the array have changed. Since we pass an empty array, it will run only after mounting.
Usually when this happens to me (rare but it does) means that the code being executed is different than the code in the editor. It will happen from time to time for Eclipse that the built classes and the code in editor are out of sync. When that happens I get all sort of weird debugger behavior (debugging empty lines, skipping lines of codes etc).
Restarting Eclipse, clean all projects and rebuild everything usually clears things up. I had also the Maven plugins (older versions... had not had it for a while now) that had a tendency to do that too.
Otherwise it might be a bug, maybe the one Vineet stated,
Hope this helps
This work for me:
$('#data_compra').daterangepicker({
singleDatePicker: true,
locale: {
format: 'DD/MM/YYYY'
},
calender_style: "picker_4", },
function(start, end, label) {
console.log(start.toISOString(), end.toISOString(), label);
});
The problem is that your <label>
is inside of an <h2>
tag, and header tags have a margin
set by the default stylesheet.
Note: ||= does not exist. (logical or) You can use
y= y || expr; // expr is NOT evaluated if y==true
or
y = expr ? true : y; // expr is always evaluated.
I want to just refresh the div, without refreshing the page ... Is this possible?
Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.
If you just want the graphical fade-in effect, simply remove the .html(data)
call:
$("#panel").hide().fadeIn('fast');
Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/
It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.
html:
<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?
javascript:
$("#changePanel").click(function() {
var data = "foobar";
$("#panel").hide().html(data).fadeIn('fast');
});?
css:
div {
padding: 1em;
background-color: #00c000;
}
input {
padding: .25em 1em;
}?
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
I faced similar problem, and I think is valid to be registered how I fixed it:
I have a system built basically over Symfony 3. For self learn and performance purposes I decided to write few scripts using GoLang, also, an API with public access.
My Go API expects Json format params, and also return Json format response
To call those GoApi's I am using, most, $.ajax ( jQuery ) The first test was a deception: the (un)famous "Cross-Origin Request Blocked" pop up ! Then, I tried to set the "Access-Control-Allow-Origin: *" On apache conf, htaccess, php, javascript and anywhere I could find on google !
But, even, same frustrating error !!!
The Solution was simple : I had to make "POST" requests instead "GET" .
To achieve that I had to adjust both, GoLang and JavaScript to use GET ! Once it done, no more Cross-Origin Request Blocked for me !!!
Hope it Helps
PS:
I am using apache and Vhost, on Directory Block I have
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Remember : "*" means that you will accept requests from anyone !!! (Which may be a security lack ) In my case it is ok, because it will be an public API
PS2: My Headers
Response headers
Access-Control-Allow-Credentials true
Access-Control-Allow-Headers Authorization
Access-Control-Allow-Methods GET, POST, PUT
Access-Control-Allow-Origin http://localhost
Content-Length 164
Content-Type application/json; charset=UTF-8
Date Tue, 07 May 2019 20:33:52 GMT
Request headers (469 B)
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Content-Length 81
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Host localhost:9003
Origin http://localhost
Referer http://localhost/fibootkt/MY_app_dev.php/MyTest/GoAPI
User-Agent Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/66.0
As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.
Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.
A possible solution is to wrap the static in a proxy with an interface which can be mocked
public interface IFileProxy {
void Delete(string path);
}
public class FileProxy : IFileProxy {
public void Delete(string path) {
System.IO.File.Delete(path);
}
}
public class MyClass {
private IFileProxy _fileProxy;
public MyClass(IFileProxy fileProxy) {
_fileProxy = fileProxy;
}
public void DoSomethingAndDeleteFile(string path) {
// Do Something with file
// ...
// Delete
System.IO.File.Delete(path);
}
public void DoSomethingAndDeleteFileUsingProxy(string path) {
// Do Something with file
// ...
// Delete
_fileProxy.Delete(path);
}
}
The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)
Another possibility is to have a 'static proxy' with different implementations of the interface behind it
public static class FileServices {
static FileServices() {
Reset();
}
internal static IFileProxy FileProxy { private get; set; }
public static void Reset(){
FileProxy = new FileProxy();
}
public static void Delete(string path) {
FileProxy.Delete(path);
}
}
Our method now becomes
public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
// Do Something with file
// ...
// Delete
FileServices.Delete(path);
}
For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).
You can also delete all tables from database using only MSSMS UI tools (without using SQL script). Sometimes this way can be more comfortable (especially if it is performed occasionally)
I do this step by step as follows:
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.
df.coalesce(1)
.write
.option("header","true")
.option("sep",",")
.mode("overwrite")
.csv("output/path")
If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.
Attention: This method saves the credentials in plaintext on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.
Run
git config --global credential.helper store
then
git pull
provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.
If you want to change the password later
git pull
Will fail, because the password is incorrect, git then removes the offending user+password from the ~/.git-credentials
file, so now re-run
git pull
to provide a new password so it works as earlier.
For ASP.NET Core, create a simple middleware class:
public class NoCacheMiddleware
{
private readonly RequestDelegate m_next;
public NoCacheMiddleware( RequestDelegate next )
{
m_next = next;
}
public async Task Invoke( HttpContext httpContext )
{
httpContext.Response.OnStarting( ( state ) =>
{
// ref: http://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers
httpContext.Response.Headers.Append( "Cache-Control", "no-cache, no-store, must-revalidate" );
httpContext.Response.Headers.Append( "Pragma", "no-cache" );
httpContext.Response.Headers.Append( "Expires", "0" );
return Task.FromResult( 0 );
}, null );
await m_next.Invoke( httpContext );
}
}
then register it with Startup.cs
app.UseMiddleware<NoCacheMiddleware>();
Make sure you add this somewhere after
app.UseStaticFiles();
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
Just Adding Instance Properties
For example, all components can access a global appName
, you just write one line code:
Vue.prototype.$appName = 'My App'
$
isn't magic, it's a convention Vue uses for properties that are available to all instances.
Alternatively, you can write a plugin that includes all global methods or properties.
You just use jquery each() function ;
$(function() {
$( ".selector_class_name" ).each(function(){
$( this ).accordion({
collapsible: true,
active:false,
heightStyle: "content"
});
});
});
You can use the six library to support both Python 2 and 3:
import six
if isinstance(value, six.string_types):
handle_string(value)
I've created this query:
SELECT
db.name AS [Database Name],
mf.name AS [Logical Name],
mf.type_desc AS [File Type],
mf.physical_name AS [Path],
CAST(
(mf.Size * 8
) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)],
'By '+IIF(
mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
(mf.growth * 8
) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth],
IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
(
CAST(mf.max_size AS BIGINT) * 8
) / 1024 AS VARCHAR(30))+' MB')) AS [MaximumSize]
FROM
sys.master_files AS mf
INNER JOIN sys.databases AS db ON
db.database_id = mf.database_id
You'll need a datasource
for working with JdbcTemplate
.
JdbcTemplate template = new JdbcTemplate(yourDataSource);
template.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
PreparedStatement statement = connection.prepareStatement(ourInsertQuery);
//statement.setLong(1, beginning); set parameters you need in your insert
return statement;
}
});
Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.
If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.
In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.
@media (min-width: 992px){
.navbar li {
margin-left : 1em;
margin-right : 1em;
}
}
For me, I encountered this error many times,
Error inflating class android.support.design.widget.NavigationView #28 and #29
The solution that works for me is that you must match your support design library and your support appcompat library.
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
For me they must match. :) It works for me!
Should be:
SELECT registrationDate,
(SELECT CASE
WHEN COUNT(*)< 2 THEN 'Ama'
WHEN COUNT(*)< 5 THEN 'SemiAma'
WHEN COUNT(*)< 7 THEN 'Good'
WHEN COUNT(*)< 9 THEN 'Better'
WHEN COUNT(*)< 12 THEN 'Best'
ELSE 'Outstanding'
END as a FROM Articles
WHERE Articles.userId = Users.userId) as ranking,
(SELECT COUNT(*)
FROM Articles
WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS
Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.
You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.
In your settings.xml you would add something like this to set your internal repository as as mirror for central:
<mirrors>
<mirror>
<id>ibiblio.org</id>
<name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
<url>http://path/to/my/repository</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.
A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.
You would configure the repository (in your pom or a profile in the settings.xml) as follows:
<repository>
<id>central</id>
<url>http://repo1.maven.org/maven2</url>
<updatePolicy>never</updatePolicy>
</repository>
In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.
Based on watching the Maven console in Eclipse (Kepler), sources will be automatically downloaded for a Maven dependency if you attempt to open a class from said Maven dependency in the editor for which you do not have the sources downloaded already. This is handy when you don't want to grab source for all of your dependencies, but you don't know which ones you want ahead of time (and you're using Eclipse).
I ended up using @GabrielRamierez's approach, but will employ @PascalThivent's approach going forward.
This Python snippet will git mv --force
all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force
.
Modify it to your liking. I just figured I'd share :)
import os
import re
searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)
for root, dirs, files in os.walk(searchDir):
dirs[:] = [d for d in dirs if d not in exclude]
for f in files:
if re.match(r'[A-Z]', f):
fullPath = os.path.join(root, f)
fullPathLower = os.path.join(root, f[0].lower() + f[1:])
command = 'git mv --force ' + fullPath + ' ' + fullPathLower
print(command)
os.system(command)
Hera's the function UpdateWindowsList_WindowMenu() that you must call after any operations are performed on Tabs.Here windowToolStripMenuItem is the menu item added to Window Menu to menu strip.
public void UpdateWindowsList_WindowMenu()
{
//get all tab pages from tabControl1
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
//get windowToolStripMenuItem drop down menu items count
int n = windowToolStripMenuItem.DropDownItems.Count;
//remove all menu items from of windowToolStripMenuItem
for (int i = n - 1; i >=2; i--)
{
windowToolStripMenuItem.DropDownItems.RemoveAt(i);
}
//read each tabpage from tabcoll and add each tabpage text to windowToolStripMenuItem
foreach (TabPage tabpage in tabcoll)
{
//create Toolstripmenuitem
ToolStripMenuItem menuitem = new ToolStripMenuItem();
String s = tabpage.Text;
menuitem.Text = s;
if (tabControl1.SelectedTab == tabpage)
{
menuitem.Checked = true;
}
else
{
menuitem.Checked = false;
}
//add menuitem to windowToolStripMenuItem
windowToolStripMenuItem.DropDownItems.Add(menuitem);
//add click events to each added menuitem
menuitem.Click += new System.EventHandler(WindowListEvent_Click);
}
}
private void WindowListEvent_Click(object sender, EventArgs e)
{
//casting ToolStripMenuItem to ToolStripItem
ToolStripItem toolstripitem = (ToolStripItem)sender;
//create collection of tabs of tabContro1
//check every tab text is equal to clicked menuitem then select the tab
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
foreach (TabPage tb in tabcoll)
{
if (toolstripitem.Text == tb.Text)
{
tabControl1.SelectedTab = tb;
//call UpdateWindowsList_WindowMenu() to perform changes on menuitems
UpdateWindowsList_WindowMenu();
}
}
}
Try:
<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>
and then in your controller
@car = Car.find(params[:car])
which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id
hope it helps! happy coding
more than a year later, but if you see it or anyone does, i could use the points ;D
DECLARE @Text VARCHAR(MAX), @First VARCHAR(MAX), @Second VARCHAR(MAX)
SET @Text = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'
SET @First = 'the dog'
SET @Second = 'immediately'
SELECT SUBSTRING(@Text, CHARINDEX(@First, @Text),
CHARINDEX(@Second, @Text) - CHARINDEX(@First, @Text) + LEN(@Second))
Try like this;
Uri.GetLeftPart( UriPartial.Authority )
Defines the parts of a URI for the Uri.GetLeftPart method.
http://www.contoso.com/index.htm?date=today --> http://www.contoso.com
http://www.contoso.com/index.htm#main --> http://www.contoso.com
nntp://news.contoso.com/[email protected] --> nntp://news.contoso.com
file://server/filename.ext --> file://server
Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));
You have mentioned Wrong id
alert(document.getElementById("name").value);
if you want to use name
attribute then
alert(document.getElementsByName("username")[0].value);
Updates:
input type="text" id="name" name="username"
id is different from name
Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.
To create a new branch with a copy of your current state
git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server
Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.
Increasing the font size on a text box will usually expand its size automatically.
<input type="text" style="font-size:16pt;">
If you want to set a height that is not proportional to the font size, I would recommend using something like the following. This prevents browsers like IE from rendering the text inside at the top rather than vertically centered.
.form-text{
padding:15px 0;
}
My educated guess is that the memory use you are seeing is not from the page content, but rather from loading UIWebView and all of it's supporting WebKit libraries. I love the UIWebView control, but it is a 'heavy' control that pulls in a very large block of code.
This code is a large sub-set of the iOS Safari browser, and likely initializes a large body of static structures.
As I posted in the comment you don't need to use both setTimeout()
and setInterval()
, moreover you have a syntax error too (the one extra }
). Correct your code like this:
(edited to add two functions to force the next/previous image to be shown)
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<img id="img" src="startpicture.jpg"/>
<button type="button" onclick="displayPreviousImage()">Previous</button>
<button type="button" onclick="displayNextImage()">Next</button>
</body>
</html>
the reason why it returns < filter object >
is that, filter is class instead of built-in function.
help(filter)
you will get following:
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
There is a vue component for this usecase
https://github.com/TheDynomike/vue-script-component#usage
<template>
<div>
<VueScriptComponent script='<script type="text/javascript"> alert("Peekaboo!"); </script>'/>
<div>
</template>
<script>
import VueScriptComponent from 'vue-script-component'
export default {
...
components: {
...
VueScriptComponent
}
...
}
</script>
iBeacon uses Bluetooth Low Energy(LE) to keep aware of locations, and the distance/range of Bluetooth LE is 160ft (http://en.wikipedia.org/wiki/Bluetooth_low_energy).
Option Explicit
Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook
TitleId = 4
Resultid = 0
Dim FileName1, FileName2 As String
Dim Difference As Long
'TestPassCount = 0
'TestFailCount = 0
'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count
If (TestDataRowCount <= 2) Then
MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
For RecordId = 3 To TestDataRowCount
RefreshResultSheet
'Source File row count
SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
Set sourcewb = Workbooks.Open(SrceFile)
With sourcewb.Worksheets(1)
SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
sourcewb.Close
End With
'Target File row count
TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
Set targetwb = Workbooks.Open(TrgtFile)
With targetwb.Worksheets(1)
TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
targetwb.Close
End With
' Set Row Count Result Test data value
TitleId = TitleId + 3
Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value
'Compare Source and Target Row count
Resultid = TitleId + 1
Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
If (SourceRowCount = TargetRowCount) Then
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestPassCount = TestPassCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestFailCount = TestFailCount + 1
End If
'For comparison of two files
FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
FileName2 = Worksheets("TestData").Range("E" & RecordId).Value
Set myWorkbook1 = Workbooks.Open(FileName1)
Set myWorkbook2 = Workbooks.Open(FileName2)
Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
myWorkbook1.Close
myWorkbook2.Close
'MsgBox Difference
'Set Result of data validation in result sheet
Resultid = Resultid + 1
Worksheets("Result").Activate
Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"
If Difference > 0 Then
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestFailCount = TestFailCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestPassCount = TestPassCount + 1
End If
Next RecordId
End If
UpdateTestExecData TestPassCount, TestFailCount
End Sub
Sub RefreshResultSheet()
Worksheets("Result").Activate
Worksheets("Result").Range("B1:B4").Select
Selection.ClearContents
Worksheets("Result").Range("D1:D4").Select
Selection.ClearContents
Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub
Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
Worksheets("Result").Range("D2").Value = TestPassCount
Worksheets("Result").Range("D3").Value = TestFailCount
Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub
AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).
This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.
For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.
Honestly, I think the official Python docs describe it quite well and provide some examples:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
>>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass: ... pass ...
Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
>>> def initlog(*args): ... pass # Remember to implement this! ...
Further to pensz answer you can get more info using:
DESCRIBE EXTENDED my_table;
or
DESCRIBE EXTENDED my_table PARTITION (my_column='my_value');
For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.
The username is not the username you set up when you've created the sendgrid object in azure. To find your username;
Hope this helps!
Lots of hard ways to do an easy thing:
<form name="foo" onsubmit="return false">
Here is jQuery equivalent:
var $img = $('img');
if ($img.length > 0 && !$img.get(0).complete) {
$img.on('load', triggerAction);
}
function triggerAction() {
alert('img has been loaded');
}
Do maven clean or clean verify and try to run it.The instances has to be cleaned before deploying the another project. It worked for me. I tried it for 2 days to understand this.
You should use window.history
and return a false so that the href
is not navigated by the browser ( the default behavior ).
<a href="www.mypage.com" onclick="window.history.go(-1); return false;"> Link </a>
Try to look at the following link: Python | change text color in shell
Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines
In general solution is to use ANSI codes while printing your string.
There is a solution that performs exactly what you need.
Here input is a string currentUTCTime (in format 08/30/2012 11:11) converts input time in GMT to system set zone time
//UTC time
NSDateFormatter *utcDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[utcDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
[utcDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: 0]];
// utc format
NSDate *dateInUTC = [utcDateFormatter dateFromString: currentUTCTime];
// offset second
NSInteger seconds = [[NSTimeZone systemTimeZone] secondsFromGMT];
// format it and send
NSDateFormatter *localDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[localDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
[localDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: seconds]];
// formatted string
NSString *localDate = [localDateFormatter stringFromDate: dateInUTC];
return localDate;
You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.
for other type of products it will automatically restore it.
Please read following text which will clear your concept about this :
Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.
Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.
If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices
I was getting e.data.indexOf is not a function
error, after debugging it, I found that it was actually a TypeError
, which meant, indexOf()
being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf()
method to make it work
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.
A version of Otto Nascarella's solution that works in strict mode is:
button.addEventListener('click', function handler() {
///this will execute only once
alert('only once!');
this.removeEventListener('click', handler);
});
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
I don't think you can do this. Basic answers will work in many cases, and in others cause data corruptions. A strategy needs to be chosen based on heuristic analysis of your database. That is the reason this feature was implemented, and then removed. [doc]
You'll need to dump all object types in that database, create the newly named one and then import the dump. If this is a live system you'll need to take it down. If you cannot, then you will need to setup replication from this database to the new one.
If you want to see the commands that could do this, @satishD has the details, which conveys some of the challenges around which you'll need to build a strategy that matches your target database.
Let's assume you have a class like this:
public class Staff
{
public int ID { get; set; }
public string Name { get; set; }
}
And assume you have dragged and dropped a DataGridView
to your form, and name it dataGridView1.
You need a BindingSource to hold your data to bind your DataGridView
. This is how you can do it:
private void frmDGV_Load(object sender, EventArgs e)
{
//dummy data
List<Staff> lstStaff = new List<Staff>();
lstStaff.Add(new Staff()
{
ID = 1,
Name = "XX"
});
lstStaff.Add(new Staff()
{
ID = 2,
Name = "YY"
});
//use binding source to hold dummy data
BindingSource binding = new BindingSource();
binding.DataSource = lstStaff;
//bind datagridview to binding source
dataGridView1.DataSource = binding;
}
Just wanted to give a vb.net (as with c language if want to convert..) I was having similar problem for uninstal of one of my programs, dropping the DB was bit tricky, yes could get users to go into server drop it using Express, but thats not clean, after few looks around got a perfect little bit of code together...
Sub DropMyDatabase()
Dim Your_DB_To_Drop_Name As String = "YourDB"
Dim Your_Connection_String_Here As String = "SERVER=MyServer;Integrated Security=True"
Dim Conn As SqlConnection = New SqlConnection(Your_Connection_String_Here)
Dim AlterStr As String = "ALTER DATABASE " & Your_DB_To_Drop_Name & " SET OFFLINE WITH ROLLBACK IMMEDIATE"
Dim AlterCmd = New SqlCommand(AlterStr, Conn)
Dim DropStr As String = "DROP DATABASE " & Your_DB_To_Drop_Name
Dim DropCmd = New SqlCommand(DropStr, Conn)
Try
Conn.Open()
AlterCmd.ExecuteNonQuery()
DropCmd.ExecuteNonQuery()
Conn.Close()
Catch ex As Exception
If (Conn.State = ConnectionState.Open) Then
Conn.Close()
End If
MsgBox("Failed... Sorry!" & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
Hope this helps anyone looking xChickenx
UPDATE Using this converter here is the C# version :
public void DropMyDatabase()
{
var Your_DB_To_Drop_Name = "YourDB";
var Your_Connection_String_Here = "SERVER=MyServer;Integrated Security=True";
var Conn = new SqlConnection(Your_Connection_String_Here);
var AlterStr = "ALTER DATABASE " + Your_DB_To_Drop_Name + " SET OFFLINE WITH ROLLBACK IMMEDIATE";
var AlterCmd = new SqlCommand(AlterStr, Conn);
var DropStr = "DROP DATABASE " + Your_DB_To_Drop_Name;
var DropCmd = new SqlCommand(DropStr, Conn);
try
{
Conn.Open();
AlterCmd.ExecuteNonQuery();
DropCmd.ExecuteNonQuery();
Conn.Close();
}
catch(Exception ex)
{
if((Conn.State == ConnectionState.Open))
{
Conn.Close();
}
Trace.WriteLine("Failed... Sorry!" + Environment.NewLine + ex.Message);
}
}
As mentioned by others Android Toasts can either be LENGTH_LONG or LENGTH_SHORT. There is no way around this, nor should you follow any of the 'hacks' posted.
The purpose of Toasts are to display "non-essential" information and due to their lingering effect, messages may be put far out of context if their duration exceeds a certain threshold. If stock Toasts were modified so that they can display longer than LENGTH_LONG the message would linger on the screen until the application's process is terminated as toast views are added to the WindowManager and not a ViewGroup in your app. I would assume this is why it is hard coded.
If you absolutely need to show a toast style message longer than three and a half seconds I recommend building a view that gets attached to the Activity's content, that way it will disappear when the user exits the application. My SuperToasts library deals with this issue and many others, feel free to use it! You would most likely be interested in using SuperActivityToasts
You can use System.load()
to provide an absolute path which is what you want, rather than a file in the standard library folder for the respective OS.
If you want native applications that already exist, use System.loadLibrary(String filename)
. If you want to provide your own you're probably better with load().
You should also be able to use loadLibrary
with the java.library.path
set correctly. See ClassLoader.java
for implementation source showing both paths being checked (OpenJDK)
In your Fragments onCreateView(...)
you can remove a view by calling container.removeView(view);
.
So if you want to remove the fragment, then view
should be the return value of onCreateView
,
for example
public View onCreateView(...){
final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
//Do something
finishButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
container.removeView(view);
}
});
return view;
}
If you have a list with 53 items, the last one is thelist[52]
because indexing starts at 0.
IndexError
IndexError
The IndexError
is raised when attempting to retrieve an index from a sequence (e.g. list
, tuple
), and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:
Raised when a sequence subscript is out of range. (Source)
Here’s an example that raises the IndexError
:
test = list(range(53))
test[53]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-7879607f7f36> in <module>
1 test = list(range(53))
----> 2 test[53]
IndexError: list index out of range
The error message line for an IndexError
doesn’t provide great information. See that there is a sequence reference that is out of range and what the type of the sequence is, a list
in this case. That information, combined with the rest of the traceback, is usually enough to help quickly identify how to fix the issue.
May this help to someone if they have the same requirement.
This will read a file that contains the Jenkins Job name and run them iteratively from one single job.
Please change below code accordingly in your Jenkins.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '
##To read file from workspace which will contain the Jenkins Job Name ###
def filePath = readFile "${WORKSPACE}/ Your File Location"
##To read file line by line ###
def lines = filePath.readLines()
##To iterate and run Jenkins Jobs one by one ####
for (line in lines) {
build(job: "$line/branchName",
parameters:
[string(name: 'vertical', value: "${params.vert}"),
string(name: 'environment', value: "${params.env}"),
string(name: 'branch', value: "${params.branch}"),
string(name: 'project', value: "${params.project}")
]
)
}
}
}
}
}
}
_x000D_
How about:
table {_x000D_
table-layout: fixed; _x000D_
width: 100%;_x000D_
*margin-left: -100px; /*ie7*/_x000D_
}_x000D_
td, th {_x000D_
vertical-align: top;_x000D_
border-top: 1px solid #ccc;_x000D_
padding: 10px;_x000D_
width: 100px;_x000D_
}_x000D_
.fix {_x000D_
position: absolute;_x000D_
*position: relative; /*ie7*/_x000D_
margin-left: -100px;_x000D_
width: 100px;_x000D_
}_x000D_
.outer {_x000D_
position: relative;_x000D_
}_x000D_
.inner {_x000D_
overflow-x: scroll;_x000D_
overflow-y: visible;_x000D_
width: 400px; _x000D_
margin-left: 100px;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="inner">_x000D_
<table>_x000D_
<tr>_x000D_
<th class=fix></th>_x000D_
<th>Col 1</th>_x000D_
<th>Col 2</th>_x000D_
<th>Col 3</th>_x000D_
<th>Col 4</th>_x000D_
<th class="fix">Col 5</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class=fix>Header A</th>_x000D_
<td>col 1 - A</td>_x000D_
<td>col 2 - A (WITH LONGER CONTENT)</td>_x000D_
<td>col 3 - A</td>_x000D_
<td>col 4 - A</td>_x000D_
<td class=fix>col 5 - A</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class=fix>Header B</th>_x000D_
<td>col 1 - B</td>_x000D_
<td>col 2 - B</td>_x000D_
<td>col 3 - B</td>_x000D_
<td>col 4 - B</td>_x000D_
<td class=fix>col 5 - B</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class=fix>Header C</th>_x000D_
<td>col 1 - C</td>_x000D_
<td>col 2 - C</td>_x000D_
<td>col 3 - C</td>_x000D_
<td>col 4 - C</td>_x000D_
<td class=fix>col 5 - C</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
You can test it out in this jsbin: http://jsbin.com/uxecel/4/edit
If you've to support IE7, a more compatible solution is:
/* only the cells with no cell before (aka the first one) */
td {
padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
padding-left: 0;
}
Also works fine with li
; general sibling selector ~
may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.
There have been som changes to how we define the KeyboardWillHideNotification.
This solution works with Swift 4.2:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
@objc func keyboardWillShow(_ notification:Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
self.view.frame.origin.y -= keyboardSize.height
}
}
@objc func keyboardWillHide(_ notification:Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.view.frame.origin.y += keyboardSize.height
}
}
None of the other answers worked for me.
Make sure both unzipped files are in same folder, but also right click on setup.exe, select properties, compatibility, and then put a checkmark in "Run this program in compatibility mode for..." and select Windows 7.
I successfully launched the installer without the error message on Windows 10 for the 32-bit version of Oracle 11g release 2.
From: http://www-01.ibm.com/support/docview.wss?uid=swg21960606
For anybody interested in Titanium i must say that they don't have a very good documentation some classes, properties, methods are missing. But a lot is "documented" in their sample app the KitchenSink so it is not THAT bad.
You can give this simple jQuery plugin (AnimateScroll) a whirl. It is quite easy to use.
1. Scroll to the top of the page:
$('body').animatescroll();
2. Scroll to an element with ID section-1
:
$('#section-1').animatescroll({easing:'easeInOutBack'});
Disclaimer: I am the author of this plugin.
Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.
It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.
This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.
A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.
To quote the blog entry:
The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.
If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.
TemplateSyntaxError at /
Caught an exception while rendering: too many values to unpack
Original Traceback (most recent call last):
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
result = node.render(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
output = force_unicode(self.filter_expression.resolve(context))
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
obj = self.var.resolve(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
value = self._resolve_lookup(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
current = current()
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack
This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.
You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.
I'm 99% sure that this was the original problem encountered here.
Late to the party. But this might be helpful for someone.
All you need is your script and django-extensions
installed.
Just run the shell_plus
available in django_extensions
and import the script that you've written.
If your script is scpt.py
and it's inside a folder fol
you can run the script as follows.
python manage.py shell_plus
and just import your script inside the shell as follows.
>>> from fol import scpt
Make use of WebkitTransform / -moz-transform: rotate(Xdeg)
. This will not work in IE, but Matt's zachstronaut solution doesn't work in IE either.
If you want to support IE too, you'll have to look into using a canvas
like I believe Raphael does.
Here is a simple jQuery snippet that rotates the elements in a jQuery object. Rotation can be started and stopped:
$(function() {_x000D_
var $elie = $("img"), degree = 0, timer;_x000D_
rotate();_x000D_
function rotate() {_x000D_
_x000D_
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'}); _x000D_
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'}); _x000D_
timer = setTimeout(function() {_x000D_
++degree; rotate();_x000D_
},5);_x000D_
}_x000D_
_x000D_
$("input").toggle(function() {_x000D_
clearTimeout(timer);_x000D_
}, function() {_x000D_
rotate();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>_x000D_
<input type="button" value=" Toggle Spin " />_x000D_
<br/><br/><br/><br/>_x000D_
<img src="http://i.imgur.com/ABktns.jpg" />
_x000D_
If you have to do private key validation; at Command Prompt(cmd), run
First;
set PATH=C:\PuttySetupLocation
Second;
pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu
Also, if you need extra options look at the following link. https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
A click is an event; you can't query an element and ask it whether it's being clicked on or not. How about this:
jQuery('#id').click(function () {
// do some stuff
});
Then if you really wanted to, you could just have a loop that executes every few seconds with your // run function..
What worked for me was adding myWindow.document.close()
after myWindow.document.write()
. Here's my solution with a timeout to wait for the new window to finish loading (if you have a lot to load):
var win = window.open('', 'PrintWindow');
win.document.write('Stuff to print...');
setTimeout(function () {
win.document.close();
win.focus();
win.print();
win.close();
}, 1000);
They're spelled out pretty well in intellisense. Just type System.Collections. or System.Collections.Generics (preferred) and you'll get a list and short description of what's available.
the non-regex way:
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf("["),input.indexOf("]"));
alternatively, for slightly better performance/memory usage (thanks Hosam):
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf('['),input.lastIndexOf(']'));
$('#yourid').prop('disabled', true);
@ModelAttribute simply binds the value from jsp fields to Pojo calss to perform our logic in controller class. If you are familiar with struts, then this is like populating the formbean object upon submission.
You can use the Windows API function ShellExecute
to do so:
Option Explicit
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal Operation As String, _
ByVal Filename As String, _
Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Public Sub OpenUrl()
Dim lSuccess As Long
lSuccess = ShellExecute(0, "Open", "www.google.com")
End Sub
Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute
would execute any command with the user's permissions, also a format c:
would be executed if the user is an administrator.
var path = "index.html"
const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)
using simple readFileSync
works for me.
check the demo - http://jsfiddle.net/S8g4E/6/
use css -
#container { width: 300px; height: 300px; border:1px solid red; display: table;}
#up { background: green; display: table-row; }
#down { background:pink; display: table-row;}
How do i make an:
if str(variable) == [contains text]:
condition?
Perhaps the most direct way is:
if str(variable) != '':
# ...
Note that the if not ...
solutions test the opposite condition.
For Windows there are 2 installers. Did you use the bundle containing VirtualBox installer? It is call Windows 32/64 bits (with VirtualBox).
The solution is:
That's it.
In angular 7.x I used angular-elements for this.
Install @angular-elements npm i @angular/elements -s
Create accessory service.
import { Injectable, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { IStringAnyMap } from 'src/app/core/models';
import { AppUserIconComponent } from 'src/app/shared';
const COMPONENTS = {
'user-icon': AppUserIconComponent
};
@Injectable({
providedIn: 'root'
})
export class DynamicComponentsService {
constructor(private injector: Injector) {
}
public register(): void {
Object.entries(COMPONENTS).forEach(([key, component]: [string, any]) => {
const CustomElement = createCustomElement(component, { injector: this.injector });
customElements.define(key, CustomElement);
});
}
public create(tagName: string, data: IStringAnyMap = {}): HTMLElement {
const customEl = document.createElement(tagName);
Object.entries(data).forEach(([key, value]: [string, any]) => {
customEl[key] = value;
});
return customEl;
}
}
Note that you custom element tag must be different with angular component selector. in AppUserIconComponent:
...
selector: app-user-icon
...
and in this case custom tag name I used "user-icon".
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {
constructor(
dynamicComponents: DynamicComponentsService,
) {
dynamicComponents.register();
}
}
dynamicComponents.create('user-icon', {user:{...}});
or like this:
const html = `<div class="wrapper"><user-icon class="user-icon" user='${JSON.stringify(rec.user)}'></user-icon></div>`;
this.content = this.domSanitizer.bypassSecurityTrustHtml(html);
(in template):
<div class="comment-item d-flex" [innerHTML]="content"></div>
Note that in second case you must pass objects with JSON.stringify and after that parse it again. I can't find better solution.
It is worth noting that @Marius's second answer could be used as pure Javascript solution.
document.getElementById('elementId').tagName
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
The easiest solution is to just run your own counter thus:
int i = 0;
for (String s : stringArray) {
doSomethingWith(s, i);
i++;
}
The reason for this is because there's no actual guarantee that items in a collection (which that variant of for
iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).
See for example, the following code:
import java.util.*;
public class TestApp {
public static void AddAndDump(AbstractSet<String> set, String str) {
System.out.println("Adding [" + str + "]");
set.add(str);
int i = 0;
for(String s : set) {
System.out.println(" " + i + ": " + s);
i++;
}
}
public static void main(String[] args) {
AbstractSet<String> coll = new HashSet<String>();
AddAndDump(coll, "Hello");
AddAndDump(coll, "My");
AddAndDump(coll, "Name");
AddAndDump(coll, "Is");
AddAndDump(coll, "Pax");
}
}
When you run that, you can see something like:
Adding [Hello]
0: Hello
Adding [My]
0: Hello
1: My
Adding [Name]
0: Hello
1: My
2: Name
Adding [Is]
0: Hello
1: Is
2: My
3: Name
Adding [Pax]
0: Hello
1: Pax
2: Is
3: My
4: Name
indicating that, rightly so, order is not considered a salient feature of a set.
There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.
Yes, each package must be defined in its own directory.
The source structure is defined in How to Write Go Code.
A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.