qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
This can be done fairly easily using `migrations.SeparateDatabaseAndState`. Basically, we use a database operation to rename the table concurrently with two state operations to remove the model from one app's history and create it in another's. Remove from old app ------------------- ``` python manage.py makemigrations old_app --empty ``` In the migration: ``` class Migration(migrations.Migration): dependencies = [] database_operations = [ migrations.AlterModelTable('TheModel', 'newapp_themodel') ] state_operations = [ migrations.DeleteModel('TheModel') ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations) ] ``` Add to new app -------------- First, copy the model to the new app's model.py, then: ``` python manage.py makemigrations new_app ``` This will generate a migration with a naive `CreateModel` operation as the sole operation. Wrap that in a `SeparateDatabaseAndState` operation such that we don't try to recreate the table. Also include the prior migration as a dependency: ``` class Migration(migrations.Migration): dependencies = [ ('old_app', 'above_migration') ] state_operations = [ migrations.CreateModel( name='TheModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], options={ 'db_table': 'newapp_themodel', }, bases=(models.Model,), ) ] operations = [ migrations.SeparateDatabaseAndState(state_operations=state_operations) ] ```
I get nervous hand-coding migrations (as is required by [Ozan's](https://stackoverflow.com/a/26472482/1978687) answer) so the following combines Ozan's and [Michael's](https://stackoverflow.com/a/30784483/1978687) strategies to minimize the amount of hand-coding required: 1. Before moving any models, make sure you're working with a clean baseline by running `makemigrations`. 2. Move the code for the Model from `app1` to `app2` 3. As recommended by @Michael, we point the new model to the old database table using the `db_table` Meta option on the "new" model: ``` class Meta: db_table = 'app1_yourmodel' ``` 4. Run `makemigrations`. This will generate `CreateModel` in `app2` and `DeleteModel` in `app1`. Technically, these migrations refer to the exact same table and would remove (including all data) and re-create the table. 5. In reality, we don't want (or need) to do anything to the table. We just need Django to believe that the change has been made. Per @Ozan's answer, the `state_operations` flag in `SeparateDatabaseAndState` does this. So we wrap all of the `migrations` entries **IN BOTH MIGRATIONS FILES** with `SeparateDatabaseAndState(state_operations=[...])`. For example, ``` operations = [ ... migrations.DeleteModel( name='YourModel', ), ... ] ``` becomes ``` operations = [ migrations.SeparateDatabaseAndState(state_operations=[ ... migrations.DeleteModel( name='YourModel', ), ... ]) ] ``` 6. You also need to make sure the new "virtual" `CreateModel` migration depends on any migration that **actually created or altered the original table**. For example, if your new migrations are `app2.migrations.0004_auto_<date>` (for the `Create`) and `app1.migrations.0007_auto_<date>` (for the `Delete`), the simplest thing to do is: * Open `app1.migrations.0007_auto_<date>` and copy its `app1` dependency (e.g. `('app1', '0006...'),`). This is the "immediately prior" migration in `app1` and should include dependencies on all of the actual model building logic. * Open `app2.migrations.0004_auto_<date>` and add the dependency you just copied to its `dependencies` list. If you have `ForeignKey` relationship(s) to the model you're moving, the above may not work. This happens because: * Dependencies are not automatically created for the `ForeignKey` changes * We do not want to wrap the `ForeignKey` changes in `state_operations` so we need to ensure they are separate from the table operations. ***NOTE: Django 2.2 added a warning (`models.E028`) that breaks this method. You may be able to work around it with `managed=False` but I have not tested it.*** The "minimum" set of operations differ depending on the situation, but the following procedure should work for most/all `ForeignKey` migrations: 1. **COPY** the model from `app1` to `app2`, set `db_table`, but DON'T change any FK references. 2. Run `makemigrations` and wrap all `app2` migration in `state_operations` (see above) * As above, add a dependency in the `app2` `CreateTable` to the latest `app1` migration 3. Point all of the FK references to the new model. If you aren't using string references, move the old model to the bottom of `models.py` (DON'T remove it) so it doesn't compete with the imported class. 4. Run `makemigrations` but DON'T wrap anything in `state_operations` (the FK changes should actually happen). Add a dependency in all the `ForeignKey` migrations (i.e. `AlterField`) to the `CreateTable` migration in `app2` (you'll need this list for the next step so keep track of them). For example: * Find the migration that includes the `CreateModel` e.g. `app2.migrations.0002_auto_<date>` and copy the name of that migration. * Find all migrations that have a ForeignKey to that model (e.g. by searching `app2.YourModel` to find migrations like: ``` class Migration(migrations.Migration): dependencies = [ ('otherapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='relatedmodel', name='fieldname', field=models.ForeignKey(... to='app2.YourModel'), ), ] ``` * Add the `CreateModel` migration as as a dependency: ``` class Migration(migrations.Migration): dependencies = [ ('otherapp', '0001_initial'), ('app2', '0002_auto_<date>'), ] ``` 5. Remove the models from `app1` 6. Run `makemigrations` and wrap the `app1` migration in `state_operations`. * Add a dependency to all of the `ForeignKey` migrations (i.e. `AlterField`) from the previous step (may include migrations in `app1` and `app2`). * When I built these migrations, the `DeleteTable` already depended on the `AlterField` migrations so I didn't need to manually enforce it (i.e. `Alter` before `Delete`). At this point, Django is good to go. The new model points to the old table and Django's migrations have convinced it that everything has been relocated appropriately. The big caveat (from @Michael's answer) is that a new `ContentType` is created for the new model. If you link (e.g. by `ForeignKey`) to content types, you'll need to create a migration to update the `ContentType` table. I wanted to cleanup after myself (Meta options and table names) so I used the following procedure (from @Michael): 1. Remove the `db_table` Meta entry 2. Run `makemigrations` again to generate the database rename 3. Edit this last migration and make sure it depends on the `DeleteTable` migration. It doesn't seem like it should be necessary as the `Delete` should be purely logical, but I've run into errors (e.g. `app1_yourmodel` doesn't exist) if I don't.
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
Another hacky alternative if the data is not big or too complicated, but still important to maintain, is to: * Get data fixtures using [manage.py dumpdata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#dumpdata) * Proceed to model changes and migrations properly, without relating the changes * Global replace the fixtures from the old model and app names to the new * Load data using [manage.py loaddata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#loaddata)
Copied from my answer at <https://stackoverflow.com/a/47392970/8971048> In case you need to move the model and you don't have access to the app anymore (or you don't want the access), you can create a new Operation and consider to create a new model only if the migrated model does not exist. In this example I am passing 'MyModel' from old\_app to myapp. ``` class MigrateOrCreateTable(migrations.CreateModel): def __init__(self, source_table, dst_table, *args, **kwargs): super(MigrateOrCreateTable, self).__init__(*args, **kwargs) self.source_table = source_table self.dst_table = dst_table def database_forwards(self, app_label, schema_editor, from_state, to_state): table_exists = self.source_table in schema_editor.connection.introspection.table_names() if table_exists: with schema_editor.connection.cursor() as cursor: cursor.execute("RENAME TABLE {} TO {};".format(self.source_table, self.dst_table)) else: return super(MigrateOrCreateTable, self).database_forwards(app_label, schema_editor, from_state, to_state) class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_some_migration'), ] operations = [ MigrateOrCreateTable( source_table='old_app_mymodel', dst_table='myapp_mymodel', name='MyModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=18)) ], ), ] ```
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
I encountered the same problem. [Ozan's answer](https://stackoverflow.com/a/26472482/2698552) helped me a lot but unfortunately was not enough. Indeed I had several ForeignKey linking to the model I wanted to move. After some headache I found the solution so decided to post it to solve people time. You need 2 more steps: 1. Before doing anything, change all your `ForeignKey` linking to `TheModel` into `Integerfield`. Then run `python manage.py makemigrations` 2. After doing Ozan's steps, re-convert your foreign keys: put back `ForeignKey(TheModel)`instead of `IntegerField()`. Then make the migrations again (`python manage.py makemigrations`). You can then migrate and it should work (`python manage.py migrate`) Hope it helps. Of course test it in local before trying in production to avoid bad suprises :)
Another hacky alternative if the data is not big or too complicated, but still important to maintain, is to: * Get data fixtures using [manage.py dumpdata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#dumpdata) * Proceed to model changes and migrations properly, without relating the changes * Global replace the fixtures from the old model and app names to the new * Load data using [manage.py loaddata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#loaddata)
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
How I did it (tested on Django==1.8, with postgres, so probably also 1.7) Situation **app1.YourModel** but you want it to go to: **app2.YourModel** 1. Copy YourModel (the code) from app1 to app2. 2. add this to app2.YourModel: ``` Class Meta: db_table = 'app1_yourmodel' ``` 3. $ python manage.py makemigrations app2 4. A new migration (e.g. 0009\_auto\_something.py) is made in app2 with a migrations.CreateModel() statement, move this statement to the initial migration of app2 (e.g. 0001\_initial.py) (it will be just like it always have been there). And now remove the created migration = 0009\_auto\_something.py 5. Just as you act, like app2.YourModel always has been there, now remove the existence of app1.YourModel from your migrations. Meaning: comment out the CreateModel statements, and every adjustment or datamigration you used after that. 6. And of course, every reference to app1.YourModel has to be changed to app2.YourModel through your project. Also, don't forget that all possible foreign keys to app1.YourModel in migrations have to be changed to app2.YourModel 7. Now if you do $ python manage.py migrate, nothing has changed, also when you do $ python manage.py makemigrations, nothing new has been detected. 8. Now the finishing touch: remove the Class Meta from app2.YourModel and do $ python manage.py makemigrations app2 && python manage.py migrate app2 (if you look into this migration you'll see something like this:) ``` migrations.AlterModelTable( name='yourmodel', table=None, ), ``` table=None, means it will take the default table-name, which in this case will be app2\_yourmodel. 9. DONE, with data saved. P.S during the migration it will see that that content\_type app1.yourmodel has been removed and can be deleted. You can say yes to that but only if you don't use it. In case you heavily depend on it to have FKs to that content-type be intact, don't answer yes or no yet, but go into the db that time manually, and remove the contentype app2.yourmodel, and rename the contenttype app1.yourmodel to app2.yourmodel, and then continue by answering no.
Another hacky alternative if the data is not big or too complicated, but still important to maintain, is to: * Get data fixtures using [manage.py dumpdata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#dumpdata) * Proceed to model changes and migrations properly, without relating the changes * Global replace the fixtures from the old model and app names to the new * Load data using [manage.py loaddata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#loaddata)
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
Copied from my answer at <https://stackoverflow.com/a/47392970/8971048> In case you need to move the model and you don't have access to the app anymore (or you don't want the access), you can create a new Operation and consider to create a new model only if the migrated model does not exist. In this example I am passing 'MyModel' from old\_app to myapp. ``` class MigrateOrCreateTable(migrations.CreateModel): def __init__(self, source_table, dst_table, *args, **kwargs): super(MigrateOrCreateTable, self).__init__(*args, **kwargs) self.source_table = source_table self.dst_table = dst_table def database_forwards(self, app_label, schema_editor, from_state, to_state): table_exists = self.source_table in schema_editor.connection.introspection.table_names() if table_exists: with schema_editor.connection.cursor() as cursor: cursor.execute("RENAME TABLE {} TO {};".format(self.source_table, self.dst_table)) else: return super(MigrateOrCreateTable, self).database_forwards(app_label, schema_editor, from_state, to_state) class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_some_migration'), ] operations = [ MigrateOrCreateTable( source_table='old_app_mymodel', dst_table='myapp_mymodel', name='MyModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=18)) ], ), ] ```
1. change the names of old models to ‘model\_name\_old’ 2. makemigrations 3. make new models named ‘model\_name\_new’ with identical relationships on the related models (eg. user model now has user.blog\_old and user.blog\_new) 4. makemigrations 5. write a custom migration that migrates all the data to the new model tables 6. test the hell out of these migrations by comparing backups with new db copies before and after running the migrations 7. when all is satisfactory, delete the old models 8. makemigrations 9. change the new models to the correct name ‘model\_name\_new’ -> ‘model\_name’ 10. test the whole slew of migrations on a staging server 11. take your production site down for a few minutes in order to run all migrations without users interfering Do this individually for each model that needs to be moved. I wouldn’t suggest doing what the other answer says by changing to integers and back to foreign keys There is a chance that new foreign keys will be different and rows may have different IDs after the migrations and I didn’t want to run any risk of mismatching ids when switching back to foreign keys.
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
This can be done fairly easily using `migrations.SeparateDatabaseAndState`. Basically, we use a database operation to rename the table concurrently with two state operations to remove the model from one app's history and create it in another's. Remove from old app ------------------- ``` python manage.py makemigrations old_app --empty ``` In the migration: ``` class Migration(migrations.Migration): dependencies = [] database_operations = [ migrations.AlterModelTable('TheModel', 'newapp_themodel') ] state_operations = [ migrations.DeleteModel('TheModel') ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations) ] ``` Add to new app -------------- First, copy the model to the new app's model.py, then: ``` python manage.py makemigrations new_app ``` This will generate a migration with a naive `CreateModel` operation as the sole operation. Wrap that in a `SeparateDatabaseAndState` operation such that we don't try to recreate the table. Also include the prior migration as a dependency: ``` class Migration(migrations.Migration): dependencies = [ ('old_app', 'above_migration') ] state_operations = [ migrations.CreateModel( name='TheModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], options={ 'db_table': 'newapp_themodel', }, bases=(models.Model,), ) ] operations = [ migrations.SeparateDatabaseAndState(state_operations=state_operations) ] ```
1. change the names of old models to ‘model\_name\_old’ 2. makemigrations 3. make new models named ‘model\_name\_new’ with identical relationships on the related models (eg. user model now has user.blog\_old and user.blog\_new) 4. makemigrations 5. write a custom migration that migrates all the data to the new model tables 6. test the hell out of these migrations by comparing backups with new db copies before and after running the migrations 7. when all is satisfactory, delete the old models 8. makemigrations 9. change the new models to the correct name ‘model\_name\_new’ -> ‘model\_name’ 10. test the whole slew of migrations on a staging server 11. take your production site down for a few minutes in order to run all migrations without users interfering Do this individually for each model that needs to be moved. I wouldn’t suggest doing what the other answer says by changing to integers and back to foreign keys There is a chance that new foreign keys will be different and rows may have different IDs after the migrations and I didn’t want to run any risk of mismatching ids when switching back to foreign keys.
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
Copied from my answer at <https://stackoverflow.com/a/47392970/8971048> In case you need to move the model and you don't have access to the app anymore (or you don't want the access), you can create a new Operation and consider to create a new model only if the migrated model does not exist. In this example I am passing 'MyModel' from old\_app to myapp. ``` class MigrateOrCreateTable(migrations.CreateModel): def __init__(self, source_table, dst_table, *args, **kwargs): super(MigrateOrCreateTable, self).__init__(*args, **kwargs) self.source_table = source_table self.dst_table = dst_table def database_forwards(self, app_label, schema_editor, from_state, to_state): table_exists = self.source_table in schema_editor.connection.introspection.table_names() if table_exists: with schema_editor.connection.cursor() as cursor: cursor.execute("RENAME TABLE {} TO {};".format(self.source_table, self.dst_table)) else: return super(MigrateOrCreateTable, self).database_forwards(app_label, schema_editor, from_state, to_state) class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_some_migration'), ] operations = [ MigrateOrCreateTable( source_table='old_app_mymodel', dst_table='myapp_mymodel', name='MyModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=18)) ], ), ] ```
**This is tested roughly, so do not forget to backup your DB!!!** For example, there are two apps: `src_app` and `dst_app`, we want to move model `MoveMe` from `src_app` to `dst_app`. Create empty migrations for both apps: ``` python manage.py makemigrations --empty src_app python manage.py makemigrations --empty dst_app ``` Let's assume, that new migrations are `XXX1_src_app_new` and `XXX1_dst_app_new`, previuos top migrations are `XXX0_src_app_old` and `XXX0_dst_app_old`. Add an operation that renames table for `MoveMe` model and renames its app\_label in ProjectState to `XXX1_dst_app_new`. Do not forget to add dependency on `XXX0_src_app_old` migration. The resulting `XXX1_dst_app_new` migration is: ```python # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations # this operations is almost the same as RenameModel # https://github.com/django/django/blob/1.7/django/db/migrations/operations/models.py#L104 class MoveModelFromOtherApp(migrations.operations.base.Operation): def __init__(self, name, old_app_label): self.name = name self.old_app_label = old_app_label def state_forwards(self, app_label, state): # Get all of the related objects we need to repoint apps = state.render(skip_cache=True) model = apps.get_model(self.old_app_label, self.name) related_objects = model._meta.get_all_related_objects() related_m2m_objects = model._meta.get_all_related_many_to_many_objects() # Rename the model state.models[app_label, self.name.lower()] = state.models.pop( (self.old_app_label, self.name.lower()) ) state.models[app_label, self.name.lower()].app_label = app_label for model_state in state.models.values(): try: i = model_state.bases.index("%s.%s" % (self.old_app_label, self.name.lower())) model_state.bases = model_state.bases[:i] + ("%s.%s" % (app_label, self.name.lower()),) + model_state.bases[i+1:] except ValueError: pass # Repoint the FKs and M2Ms pointing to us for related_object in (related_objects + related_m2m_objects): # Use the new related key for self referential related objects. if related_object.model == model: related_key = (app_label, self.name.lower()) else: related_key = ( related_object.model._meta.app_label, related_object.model._meta.object_name.lower(), ) new_fields = [] for name, field in state.models[related_key].fields: if name == related_object.field.name: field = field.clone() field.rel.to = "%s.%s" % (app_label, self.name) new_fields.append((name, field)) state.models[related_key].fields = new_fields def database_forwards(self, app_label, schema_editor, from_state, to_state): old_apps = from_state.render() new_apps = to_state.render() old_model = old_apps.get_model(self.old_app_label, self.name) new_model = new_apps.get_model(app_label, self.name) if self.allowed_to_migrate(schema_editor.connection.alias, new_model): # Move the main table schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Alter the fields pointing to us related_objects = old_model._meta.get_all_related_objects() related_m2m_objects = old_model._meta.get_all_related_many_to_many_objects() for related_object in (related_objects + related_m2m_objects): if related_object.model == old_model: model = new_model related_key = (app_label, self.name.lower()) else: model = related_object.model related_key = ( related_object.model._meta.app_label, related_object.model._meta.object_name.lower(), ) to_field = new_apps.get_model( *related_key )._meta.get_field_by_name(related_object.field.name)[0] schema_editor.alter_field( model, related_object.field, to_field, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.old_app_label, app_label = app_label, self.old_app_label self.database_forwards(app_label, schema_editor, from_state, to_state) app_label, self.old_app_label = self.old_app_label, app_label def describe(self): return "Move %s from %s" % (self.name, self.old_app_label) class Migration(migrations.Migration): dependencies = [ ('dst_app', 'XXX0_dst_app_old'), ('src_app', 'XXX0_src_app_old'), ] operations = [ MoveModelFromOtherApp('MoveMe', 'src_app'), ] ``` Add dependency on `XXX1_dst_app_new` to `XXX1_src_app_new`. `XXX1_src_app_new` is no-op migration that is needed to make sure that future `src_app` migrations will be executed after `XXX1_dst_app_new`. Move `MoveMe` from `src_app/models.py` to `dst_app/models.py`. Then run: ``` python manage.py migrate ``` That's all!
25,648,393
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure. I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect. However due to Django 1.7 and built in support for migrations is there a better way to do this now?
2014/09/03
[ "https://Stackoverflow.com/questions/25648393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2848524/" ]
I am removing the old answer as may result in data loss. As [ozan mentioned](https://stackoverflow.com/a/26472482/2698552), we can create 2 migrations one in each app. The comments below this post refer to my old answer. First migration to remove model from 1st app. ``` $ python manage.py makemigrations old_app --empty ``` Edit migration file to include these operations. ``` class Migration(migrations.Migration): database_operations = [migrations.AlterModelTable('TheModel', 'newapp_themodel')] state_operations = [migrations.DeleteModel('TheModel')] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations) ] ``` Second migration which depends on first migration and create the new table in 2nd app. After moving model code to 2nd app ``` $ python manage.py makemigrations new_app ``` and edit migration file to something like this. ``` class Migration(migrations.Migration): dependencies = [ ('old_app', 'above_migration') ] state_operations = [ migrations.CreateModel( name='TheModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], options={ 'db_table': 'newapp_themodel', }, bases=(models.Model,), ) ] operations = [ migrations.SeparateDatabaseAndState(state_operations=state_operations) ] ```
How I did it (tested on Django==1.8, with postgres, so probably also 1.7) Situation **app1.YourModel** but you want it to go to: **app2.YourModel** 1. Copy YourModel (the code) from app1 to app2. 2. add this to app2.YourModel: ``` Class Meta: db_table = 'app1_yourmodel' ``` 3. $ python manage.py makemigrations app2 4. A new migration (e.g. 0009\_auto\_something.py) is made in app2 with a migrations.CreateModel() statement, move this statement to the initial migration of app2 (e.g. 0001\_initial.py) (it will be just like it always have been there). And now remove the created migration = 0009\_auto\_something.py 5. Just as you act, like app2.YourModel always has been there, now remove the existence of app1.YourModel from your migrations. Meaning: comment out the CreateModel statements, and every adjustment or datamigration you used after that. 6. And of course, every reference to app1.YourModel has to be changed to app2.YourModel through your project. Also, don't forget that all possible foreign keys to app1.YourModel in migrations have to be changed to app2.YourModel 7. Now if you do $ python manage.py migrate, nothing has changed, also when you do $ python manage.py makemigrations, nothing new has been detected. 8. Now the finishing touch: remove the Class Meta from app2.YourModel and do $ python manage.py makemigrations app2 && python manage.py migrate app2 (if you look into this migration you'll see something like this:) ``` migrations.AlterModelTable( name='yourmodel', table=None, ), ``` table=None, means it will take the default table-name, which in this case will be app2\_yourmodel. 9. DONE, with data saved. P.S during the migration it will see that that content\_type app1.yourmodel has been removed and can be deleted. You can say yes to that but only if you don't use it. In case you heavily depend on it to have FKs to that content-type be intact, don't answer yes or no yet, but go into the db that time manually, and remove the contentype app2.yourmodel, and rename the contenttype app1.yourmodel to app2.yourmodel, and then continue by answering no.
22,427,342
Here is the scenario, I am getting the result-set from the following code and i am running the following below query after getting the result from cfdump, but it shows empty second dump, do not why? can anyone check what is wrong: ``` <cfif StructKeyExists(URL,'submitsearch') AND URL.submitsearch neq ''> <cfset answers = initial.getSearchResults('#URL#')> <cfset flag = 'yes'> </cfif> <cfchart format="png" scalefrom="0" scaleto="#answers.recordcount#" show3d="Yes"> <cfchartseries type="bar" serieslabel="Support Tickets" seriescolor="##009933"> <cfdump var="#answers#"> <cfoutput query="answers"> <cfquery dbtype="query" name="myString"> SELECT count(*) as strvalue FROM answers WHERE status = "#trim(answers.status)#" </cfquery> <cfchartdata item="#Status#" value="#myString.strvalue#"> </cfoutput> <cfdump var="#myString#"> </cfchartseries> </cfchart> ``` This is howing an issue, it does not anything: do not know why: **`<cfdump var="#myString#">`** **Edit** Screenshot below ![enter image description here](https://i.stack.imgur.com/cGbU9.png)
2014/03/15
[ "https://Stackoverflow.com/questions/22427342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2485109/" ]
Based on the screenshot provided, the following is suggested ``` <cfif StructKeyExists(URL,'submitsearch') AND URL.submitsearch neq ''> <cfset answers = initial.getSearchResults(URL)> <cfset flag = 'yes'> </cfif> <cfquery dbtype="query" name="qrySummary"> SELECT status, count(status) as strvalue FROM answers GROUP BY status ORDER BY status </cfquery> <cfdump var="#qrySummary#"> <cfchart format="png" scalefrom="0" scaleto="#answers.recordcount#" show3d="Yes"> <cfchartseries type="bar" serieslabel="Support Tickets" seriescolor="##009933"> <cfoutput query="qrySummary"> <cfchartdata item="#Status#" value="#strvalue#"> </cfoutput> </cfchartseries> </cfchart> ``` Also see Query of query support for aggregate functions <http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec0e4fd-7ff0.html#WSc3ff6d0ea77859461172e0811cbec0e4fd-7fcc>
**Copying structs** First off ``` <cfset answers = initial.getSearchResults('#URL#')> ``` Won't work. If we ignore the dangers with this, you can ``` <cfset answers = initial.getSearchResults(URL)> ``` `<cfdump>` can't generate any output inside of a `<cfchart>`. If you want to a dump, it has to be outside of the chart. To debug your data consider using something like this: ``` <cfdump var="#answers#"> <cfoutput query="answers"> <cfquery dbtype="query" name="myString"> SELECT count(*) as strvalue FROM answers WHERE status = <cfqueryparam value = "trim(answers.status)#" cfsqltype = "cf_sql_varchar"> </cfquery> #myString.strvalue# </cfoutput> <cfdump var="#myString#"> ``` Also consider, changing code so that you don't have have an inner query. You will get better performance and it will be easier to debug. **UPDATE** ``` <cfdump var="#answers#"> <!--- at this point, confirm that you are returning a query ---> <cfoutput query="answers"> <cfquery dbtype="query" name="myString"> SELECT count(status) as strvalue FROM answers WHERE status = <cfqueryparam value = "trim(answers.status)#" cfsqltype = "cf_sql_varchar"> </cfquery> <!--- here you should have a series of queries with one row, one column ---> <cfdump var="#myString#"> </cfoutput> ```
13,432,899
Can you explain what is wrong with this quicksort algorithm implementation in java? ``` static ArrayList<Integer> quickSort(ArrayList<Integer> array){ if (array.size() <=1){ ArrayList<Integer> a = new ArrayList<Integer>(); return a; } int pivotIndex = array.size() / 2; int pivot = array.get(pivotIndex); ArrayList<Integer> left= new ArrayList<Integer>(); ArrayList<Integer> right = new ArrayList<Integer>(); for (int i = 0; i < array.size(); i++) { if (i!=pivotIndex){ if (array.get(i) > pivot) right.add(array.get(i)); else left.add(array.get(i)); } } ArrayList<Integer> l = new ArrayList<Integer>(); l.addAll(quickSort(left)); l.add(pivot); l.addAll(quickSort(right)); return l; } ```
2012/11/17
[ "https://Stackoverflow.com/questions/13432899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/847988/" ]
One glaring error is that arrays of size one are not handled correctly. It's important to get this right since this is one of the base cases for the recursion.
The main issue with this algorithm - you're creating new ArrayLists for each invocation of the function. In this way you nullify the best thing about QuickSort - sorting in place without any additional memory. Try to work only with the first given **array**.
13,432,899
Can you explain what is wrong with this quicksort algorithm implementation in java? ``` static ArrayList<Integer> quickSort(ArrayList<Integer> array){ if (array.size() <=1){ ArrayList<Integer> a = new ArrayList<Integer>(); return a; } int pivotIndex = array.size() / 2; int pivot = array.get(pivotIndex); ArrayList<Integer> left= new ArrayList<Integer>(); ArrayList<Integer> right = new ArrayList<Integer>(); for (int i = 0; i < array.size(); i++) { if (i!=pivotIndex){ if (array.get(i) > pivot) right.add(array.get(i)); else left.add(array.get(i)); } } ArrayList<Integer> l = new ArrayList<Integer>(); l.addAll(quickSort(left)); l.add(pivot); l.addAll(quickSort(right)); return l; } ```
2012/11/17
[ "https://Stackoverflow.com/questions/13432899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/847988/" ]
instead of ``` if (array.size() <=1) { ArrayList<Integer> a = new ArrayList<Integer>(); return a; } ``` use ``` if (array.size() <=1){ return array } ```
The main issue with this algorithm - you're creating new ArrayLists for each invocation of the function. In this way you nullify the best thing about QuickSort - sorting in place without any additional memory. Try to work only with the first given **array**.
51,330,095
I am currently somewhat new to c#/wpf (and coding in general). I decided to start another project, being a custom made "task manager" of sorts. (While I use binding, this is NOT a MVVM project, so all answers welcome) If you have ever opened task manager, you know that one of the main helpful tools it provides is a updating view of CPU/RAM/Whatever usage. Telling the user what percent of the resource they are using. My problem is not getting the CPU percentage. I am unsure on how to refresh the text property for CPU load in the UI efficiently. My first thought was that I should create a Background worker (which is probably correct) to separate the thread loads. However, I can't seem to wrap my mind on the solution to implement the background workers in a useful way. The code is currently set up in this fashion: 1. When page is loaded, public BgWrk creates a new instance of it self. 2. Adds task to be called when ran. 3. BgWrk is ran. 4. New instance of method to be called is made. 5. Dispatcher is invoked on main thread to update UI. 6. Invoke consists of setting public string PerCpu (bound in other class, using INotifyPropertyChanged & all) on the return value of "grabber"'s CpuPerUsed. 7. BgWrk disposed. 8. Program loops (this is most likely the problem). ``` private void Grid_Loaded(object sender, RoutedEventArgs e) { BgWrk = new BackgroundWorker(); BgWrk.DoWork += new DoWorkEventHandler(BackgroundWorker1_DoWork); BgWrk.RunWorkerAsync(); } private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while (true) { CpuInfoGrabber grabber = new CpuInfoGrabber(); Application.Current.Dispatcher.Invoke(new Action (() => Bnd.PerCpu = grabber.CpuPerUsed())); BgWrk.Dispose(); } } ``` Again the code works, but it is WAY to slow due to the load of retrieving all of that data. Any suggestions on how to make this work well are appreciated! Thanks
2018/07/13
[ "https://Stackoverflow.com/questions/51330095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9622460/" ]
Instead of looping you could use a timer to periodically poll for the CPU usage. ``` class Test { private System.Timers.Timer _timer; public Test( ) { _timer = new System.Timers.Timer { // Interval set to 1 millisecond. Interval = 1, AutoReset = true, }; _timer.Elapsed += _timer_Elapsed; _timer.Enabled = true; _timer.Start( ); } private void _timer_Elapsed( object sender, System.Timers.ElapsedEventArgs e ) { // This handler is not executed on the gui thread so // you'll have to marshal the call to the gui thread // and then update your property. var grabber = new CpuInfoGrabber(); var data = grabber.CpuPerUsed(); Application.Current.Dispatcher.Invoke( ( ) => Bnd.PerCpu = data ); } } ```
I'd use `Task.Run` instead of a `BackgroundWorker` in your case: ``` private void Grid_Loaded(object sender, RoutedEventArgs e) { //Keep it running for 5 minutes CancellationTokenSource cts = new CancellationTokenSource(new TimeSpan(hours: 0, minutes: 5, seconds: 0)); //Keep it running until user closes the app //CancellationTokenSource cts = new CancellationTokenSource(); //Go to a different thread Task.Run(() => { //Some dummy variable long millisecondsSlept = 0; //Make sure cancellation not requested while (!cts.Token.IsCancellationRequested) { //Some heavy operation here Thread.Sleep(500); millisecondsSlept += 500; //Update UI with the results of the heavy operation Application.Current.Dispatcher.Invoke(() => txtCpu.Text = millisecondsSlept.ToString()); } }, cts.Token); } ```
7,968,118
I have a feature in visual studio which I have never really understood. I am able to 'right-click' on the App\_Data folder and then I am able to select 'Sql Server Database'. I dont really understand how I can create a db using just an mdf file? I thought the sql service was responsible for manipulating these files? And that you have to create the db using the 'sql management studio' interface? Im confised as to how we can essentially just have a lone file and run a db from it for a website?
2011/11/01
[ "https://Stackoverflow.com/questions/7968118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223863/" ]
You're application is still connecting through the SQL Server service but it can instruct the service to attach to a specific mdf file at runtime through a connection string. e.g.: ``` "Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;" ```
All SQL Server databases are represented as one (or more) .mdf files and usually .ldf files as well (ldf is the log file, mdf is the data file.) An .mdf file is a file but it is highly structured and maintained by SQL Server. The way SQL Server uses this file is very different from serving up CSV data, as a simple example. SQL Server breaks the file into pages and serves the requests for reads and writes via this paging system. It is indeed like a file system within a file system. If you think about it it does all make sense. The data has to get persisted to disk and that disk persistence has to come in the form of a file or files.
7,968,118
I have a feature in visual studio which I have never really understood. I am able to 'right-click' on the App\_Data folder and then I am able to select 'Sql Server Database'. I dont really understand how I can create a db using just an mdf file? I thought the sql service was responsible for manipulating these files? And that you have to create the db using the 'sql management studio' interface? Im confised as to how we can essentially just have a lone file and run a db from it for a website?
2011/11/01
[ "https://Stackoverflow.com/questions/7968118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223863/" ]
You're application is still connecting through the SQL Server service but it can instruct the service to attach to a specific mdf file at runtime through a connection string. e.g.: ``` "Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;" ```
When you installed Visual Studio you also installed SQL Server Express. This gives you the ability to create and use SQL Server databases. If you were to deploy your application you would then also need to have a SQL Server (Express) install on the web-server you were using (at least because you don't want to use your development database server in production).
1,504,326
What is the difference and how can I write these two statements in both forms? > > Not in every hole lives a pigeon. > > > Some pigeon lives in more than one hole. > > > For the first statement I have $∀h∀p [LivesIn(p, h)]$ but I am not sure how to express this in the universal form. I am not sure how to express the second statement, because it says "more than one", so a for all wouldn't make sense (at least from what I understand (which is very little)) Also, if you combine a for all and a there exists then what is it, existential or universal? If anybody can help clear the air on these problems for me I would be extremely grateful.
2015/10/30
[ "https://math.stackexchange.com/questions/1504326", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
For the first, "Not in every hole lives a pigeon", start from the positive assertion, "In every hole lives a pigeon." The one which you're trying to represent is just the negation of that. "In every hole lives a pigeon" is a universal-existential sentence: "for every hole, there's a pigeon that lives in it", or symbolically, $\forall h \exists p\,(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h)))$. Negating this, moving the negation across the quantifiers and transforming the propositional matrix of the sentence gives the following: $$ \begin{align} &\neg \forall h \exists p\,(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,\neg(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,(Hole(h) \wedge \neg (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,(Hole(h) \wedge (Pigeon(p) \to \neg LivesIn(p, h))) \\ \end{align} $$ In other words, "There's a hole in which no pigeon lives." For the second sentence, "Some pigeon lives in more than one hole": "some" should signal "existential quantifier" to you. In order to express "more than one", just (in)equality. Like so: $$ \exists p\,(Pigeon(p) \wedge \exists h\_1 \exists h\_2\, (Hole(h\_1) \wedge Hole(h\_2) \wedge h\_1 \neq h\_2 \wedge LivesIn(p, h\_1) \wedge LivesIn(p, h\_2)) $$ That is, "There is a pigeon $p$, and there are distinct holes $h\_1, h\_2$ such that $p$ lives in both $h\_1$ and $h\_2$." ***Note*** that combining existential and universal quantifiers gives a new thing: the meaning is in general distinct from the meaning of any purely existential or purely universal sentence. Furthermore, order matters: $\forall \exists$ is very different from $\exists \forall$. Three alternating quantifiers is yet another level of complexity, not reducible two-quantifier forms. And so on.
The second statement is saying that 'there exists a pidgeon who lives in more than one hole" unless you actually meant to write pidgeons.
1,504,326
What is the difference and how can I write these two statements in both forms? > > Not in every hole lives a pigeon. > > > Some pigeon lives in more than one hole. > > > For the first statement I have $∀h∀p [LivesIn(p, h)]$ but I am not sure how to express this in the universal form. I am not sure how to express the second statement, because it says "more than one", so a for all wouldn't make sense (at least from what I understand (which is very little)) Also, if you combine a for all and a there exists then what is it, existential or universal? If anybody can help clear the air on these problems for me I would be extremely grateful.
2015/10/30
[ "https://math.stackexchange.com/questions/1504326", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
For the first, "Not in every hole lives a pigeon", start from the positive assertion, "In every hole lives a pigeon." The one which you're trying to represent is just the negation of that. "In every hole lives a pigeon" is a universal-existential sentence: "for every hole, there's a pigeon that lives in it", or symbolically, $\forall h \exists p\,(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h)))$. Negating this, moving the negation across the quantifiers and transforming the propositional matrix of the sentence gives the following: $$ \begin{align} &\neg \forall h \exists p\,(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,\neg(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,(Hole(h) \wedge \neg (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,(Hole(h) \wedge (Pigeon(p) \to \neg LivesIn(p, h))) \\ \end{align} $$ In other words, "There's a hole in which no pigeon lives." For the second sentence, "Some pigeon lives in more than one hole": "some" should signal "existential quantifier" to you. In order to express "more than one", just (in)equality. Like so: $$ \exists p\,(Pigeon(p) \wedge \exists h\_1 \exists h\_2\, (Hole(h\_1) \wedge Hole(h\_2) \wedge h\_1 \neq h\_2 \wedge LivesIn(p, h\_1) \wedge LivesIn(p, h\_2)) $$ That is, "There is a pigeon $p$, and there are distinct holes $h\_1, h\_2$ such that $p$ lives in both $h\_1$ and $h\_2$." ***Note*** that combining existential and universal quantifiers gives a new thing: the meaning is in general distinct from the meaning of any purely existential or purely universal sentence. Furthermore, order matters: $\forall \exists$ is very different from $\exists \forall$. Three alternating quantifiers is yet another level of complexity, not reducible two-quantifier forms. And so on.
> > Not in every hole lives a pigeon. > > > Negate "in every hole lives a pigeon". $$\neg \;\forall x\;\exists y\; \Big(\operatorname{Hole}(x) \,\to\, \big(\operatorname{Pigeon}(y)\wedge\operatorname{LivesIn}(y, x)\big)\Big)$$ *Remember:* use implication to restrict a universe and conjugation to restrict an existence. Then use the law of dual negation to 'flip' the quantifiers to the required state, such as: $$\exists x\;\neg \;\exists y\; \Big(\operatorname{Hole}(x) \,\to\, \big(\operatorname{Pigeon}(y)\wedge\operatorname{LivesIn}(y, x)\big)\Big)$$ > > Some pigeon lives in more than one hole. > > > Declare the existence of (at least) two entities which are not the same thing, … and other stuff. $$\exists x\,\exists y\,\exists z\;\Big(y\neq z\wedge\ldots\Big)$$
1,504,326
What is the difference and how can I write these two statements in both forms? > > Not in every hole lives a pigeon. > > > Some pigeon lives in more than one hole. > > > For the first statement I have $∀h∀p [LivesIn(p, h)]$ but I am not sure how to express this in the universal form. I am not sure how to express the second statement, because it says "more than one", so a for all wouldn't make sense (at least from what I understand (which is very little)) Also, if you combine a for all and a there exists then what is it, existential or universal? If anybody can help clear the air on these problems for me I would be extremely grateful.
2015/10/30
[ "https://math.stackexchange.com/questions/1504326", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
For the first, "Not in every hole lives a pigeon", start from the positive assertion, "In every hole lives a pigeon." The one which you're trying to represent is just the negation of that. "In every hole lives a pigeon" is a universal-existential sentence: "for every hole, there's a pigeon that lives in it", or symbolically, $\forall h \exists p\,(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h)))$. Negating this, moving the negation across the quantifiers and transforming the propositional matrix of the sentence gives the following: $$ \begin{align} &\neg \forall h \exists p\,(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,\neg(Hole(h) \to (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,(Hole(h) \wedge \neg (Pigeon(p) \wedge LivesIn(p, h))) \\ \iff &\exists h \forall p\,(Hole(h) \wedge (Pigeon(p) \to \neg LivesIn(p, h))) \\ \end{align} $$ In other words, "There's a hole in which no pigeon lives." For the second sentence, "Some pigeon lives in more than one hole": "some" should signal "existential quantifier" to you. In order to express "more than one", just (in)equality. Like so: $$ \exists p\,(Pigeon(p) \wedge \exists h\_1 \exists h\_2\, (Hole(h\_1) \wedge Hole(h\_2) \wedge h\_1 \neq h\_2 \wedge LivesIn(p, h\_1) \wedge LivesIn(p, h\_2)) $$ That is, "There is a pigeon $p$, and there are distinct holes $h\_1, h\_2$ such that $p$ lives in both $h\_1$ and $h\_2$." ***Note*** that combining existential and universal quantifiers gives a new thing: the meaning is in general distinct from the meaning of any purely existential or purely universal sentence. Furthermore, order matters: $\forall \exists$ is very different from $\exists \forall$. Three alternating quantifiers is yet another level of complexity, not reducible two-quantifier forms. And so on.
> > Not in every hole lives a pigeon. > > > $\neg \forall x:[Hole(x)\implies \exists y:[Pigeon(y) \land LivesIn(y,x)]]$ Or equivalently: $\exists x: [Hole(x) \land \forall y: [Pigeon(y)\implies \neg LivesIn(y,x)]]$ > > Some pigeon lives in more than one hole. > > > $\exists x,y,z: [Pigeon(x) \land Hole(y) \land Hole(z) \land [LivesIn(x,y) \land Lives(x,z) \land y\neq z]]$
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
Covariance and contravariance are qualities of *the class* not qualities of *the parameters*. (They are qualities that depend on the parameters, but they make statements about the class.) So, `Function1[-A,+B]` means that *a function* that takes superclasses of `A` can be viewed as a subclass of *the original function*. Let's see this in practice: ``` class A class B extends A val printB: B => Unit = { b => println("Blah blah") } val printA: A => Unit = { a => println("Blah blah blah") } ``` Now suppose you require a function that knows how to print a `B`: ``` def needsB(f: B => Unit, b: B) = f(b) ``` You could pass in `printB`. But you could *also* pass in `printA`, since it also knows how to print `B`s (and more!), just as if `A => Unit` was a subclass of `B => Unit`. This is exactly what contravariance means. It doesn't mean you can pass `Option[Double]` into `printB` and get anything but a compile-time error! (Covariance is the other case: `M[B] <: M[A]` if `B <: A`.)
There are two separate ideas at work here. One is using subtyping to allow more specific arguments to be passed to a function (called *subsumption*). The other is how to check subtyping on functions themselves. For type-checking the arguments to a function, you only have to check that the given arguments are subtypes of the declared argument types. The result also has to be a subtype of the declared type. This is where you actually check subtyping. The contra/co-variance of the parameters & result only factor in when you want to check whether a given *function type* is a subtype of another function type. So if a parameter has type `Function[A1, ... ,B]`, then the argument has to be a function type `Function[C1, ..., D]` where `A1 <: C1 ...` and `D <: B`. This reasoning isn't specific to Scala and applies to other statically-typed languages with subtyping.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
There are two separate ideas at work here. One is using subtyping to allow more specific arguments to be passed to a function (called *subsumption*). The other is how to check subtyping on functions themselves. For type-checking the arguments to a function, you only have to check that the given arguments are subtypes of the declared argument types. The result also has to be a subtype of the declared type. This is where you actually check subtyping. The contra/co-variance of the parameters & result only factor in when you want to check whether a given *function type* is a subtype of another function type. So if a parameter has type `Function[A1, ... ,B]`, then the argument has to be a function type `Function[C1, ..., D]` where `A1 <: C1 ...` and `D <: B`. This reasoning isn't specific to Scala and applies to other statically-typed languages with subtyping.
Covariant means converting from wider (super) to narrower (sub). For example, we have two class: one is animal (super) and the other one is cat then using covariant, we can convert animal to cat. Contra-variant is just the opposite of covariant, which means cat to animal. Invariant means it's unable to convert.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
This question is old, but I think a clearer explanation is to invoke the Liskov Substitution Principle: everything that's true about a superclass should be true of all its subclasses. You should be able to do with a SubFoo everything that you can do with a Foo, and maybe more. Suppose we have Calico <: Cat <: Animal, and Husky <: Dog <: Animal. Let's look at a `Function[Cat, Dog]`. What statements are true about this? There are two: (1) You can pass in any Cat (so any subclass of Cat) (2) You can call any Dog method on the returned value So does `Function[Calico, Dog] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (1). You can't pass in any Cat to a Function that only takes Calico cats. But does `Function[Animal, Dog] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass. I can still pass in any Cat -- in fact I can do even more than that, I can pass in any Animal -- and I can call all Dog methods on the returned value. So `A <: B` implies `Function[B, _] <: Function[A, _]` Now, does `Function[Cat, Husky] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass; I can still pass in a Cat, and I can still call all Dog methods on the returned value -- in fact I can do even more than that, I can call all Husky methods on the returned value. But does `Function[Cat, Animal] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (2). I can't call all methods available on Dog on the returned value, only the ones available on Animal. So with a `Function[Animal, Husky]` I can do everything I can do with a `Function[Cat, Dog]`: I can pass in any Cat, and I can call all of the Dog methods on the returned value. And I can do even more: I can pass in other animals, and I can call of the methods available on Husky that aren't available on Dog. So it makes sense: `Function[Animal, Husky] <: Function[Cat, Dog]`. The first type parameter can be replaced with a superclass, the second with a subclass.
There are two separate ideas at work here. One is using subtyping to allow more specific arguments to be passed to a function (called *subsumption*). The other is how to check subtyping on functions themselves. For type-checking the arguments to a function, you only have to check that the given arguments are subtypes of the declared argument types. The result also has to be a subtype of the declared type. This is where you actually check subtyping. The contra/co-variance of the parameters & result only factor in when you want to check whether a given *function type* is a subtype of another function type. So if a parameter has type `Function[A1, ... ,B]`, then the argument has to be a function type `Function[C1, ..., D]` where `A1 <: C1 ...` and `D <: B`. This reasoning isn't specific to Scala and applies to other statically-typed languages with subtyping.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
There are two separate ideas at work here. One is using subtyping to allow more specific arguments to be passed to a function (called *subsumption*). The other is how to check subtyping on functions themselves. For type-checking the arguments to a function, you only have to check that the given arguments are subtypes of the declared argument types. The result also has to be a subtype of the declared type. This is where you actually check subtyping. The contra/co-variance of the parameters & result only factor in when you want to check whether a given *function type* is a subtype of another function type. So if a parameter has type `Function[A1, ... ,B]`, then the argument has to be a function type `Function[C1, ..., D]` where `A1 <: C1 ...` and `D <: B`. This reasoning isn't specific to Scala and applies to other statically-typed languages with subtyping.
A simplified explanation ``` class A class B extends A val printA: A => Unit = { a => println("Blah blah blah") } printA(new A()) //"Blah blah blah" printA(new B()) //"Blah blah blah" ``` contravariance rule: If `B` is a subtype of `A`, then `printA[A]` is a subtype of `printA[B]` Since `printA[B]` is the superclass, we can use `printA(new B())`
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
Covariance and contravariance are qualities of *the class* not qualities of *the parameters*. (They are qualities that depend on the parameters, but they make statements about the class.) So, `Function1[-A,+B]` means that *a function* that takes superclasses of `A` can be viewed as a subclass of *the original function*. Let's see this in practice: ``` class A class B extends A val printB: B => Unit = { b => println("Blah blah") } val printA: A => Unit = { a => println("Blah blah blah") } ``` Now suppose you require a function that knows how to print a `B`: ``` def needsB(f: B => Unit, b: B) = f(b) ``` You could pass in `printB`. But you could *also* pass in `printA`, since it also knows how to print `B`s (and more!), just as if `A => Unit` was a subclass of `B => Unit`. This is exactly what contravariance means. It doesn't mean you can pass `Option[Double]` into `printB` and get anything but a compile-time error! (Covariance is the other case: `M[B] <: M[A]` if `B <: A`.)
Covariant means converting from wider (super) to narrower (sub). For example, we have two class: one is animal (super) and the other one is cat then using covariant, we can convert animal to cat. Contra-variant is just the opposite of covariant, which means cat to animal. Invariant means it's unable to convert.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
Covariance and contravariance are qualities of *the class* not qualities of *the parameters*. (They are qualities that depend on the parameters, but they make statements about the class.) So, `Function1[-A,+B]` means that *a function* that takes superclasses of `A` can be viewed as a subclass of *the original function*. Let's see this in practice: ``` class A class B extends A val printB: B => Unit = { b => println("Blah blah") } val printA: A => Unit = { a => println("Blah blah blah") } ``` Now suppose you require a function that knows how to print a `B`: ``` def needsB(f: B => Unit, b: B) = f(b) ``` You could pass in `printB`. But you could *also* pass in `printA`, since it also knows how to print `B`s (and more!), just as if `A => Unit` was a subclass of `B => Unit`. This is exactly what contravariance means. It doesn't mean you can pass `Option[Double]` into `printB` and get anything but a compile-time error! (Covariance is the other case: `M[B] <: M[A]` if `B <: A`.)
This question is old, but I think a clearer explanation is to invoke the Liskov Substitution Principle: everything that's true about a superclass should be true of all its subclasses. You should be able to do with a SubFoo everything that you can do with a Foo, and maybe more. Suppose we have Calico <: Cat <: Animal, and Husky <: Dog <: Animal. Let's look at a `Function[Cat, Dog]`. What statements are true about this? There are two: (1) You can pass in any Cat (so any subclass of Cat) (2) You can call any Dog method on the returned value So does `Function[Calico, Dog] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (1). You can't pass in any Cat to a Function that only takes Calico cats. But does `Function[Animal, Dog] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass. I can still pass in any Cat -- in fact I can do even more than that, I can pass in any Animal -- and I can call all Dog methods on the returned value. So `A <: B` implies `Function[B, _] <: Function[A, _]` Now, does `Function[Cat, Husky] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass; I can still pass in a Cat, and I can still call all Dog methods on the returned value -- in fact I can do even more than that, I can call all Husky methods on the returned value. But does `Function[Cat, Animal] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (2). I can't call all methods available on Dog on the returned value, only the ones available on Animal. So with a `Function[Animal, Husky]` I can do everything I can do with a `Function[Cat, Dog]`: I can pass in any Cat, and I can call all of the Dog methods on the returned value. And I can do even more: I can pass in other animals, and I can call of the methods available on Husky that aren't available on Dog. So it makes sense: `Function[Animal, Husky] <: Function[Cat, Dog]`. The first type parameter can be replaced with a superclass, the second with a subclass.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
Covariance and contravariance are qualities of *the class* not qualities of *the parameters*. (They are qualities that depend on the parameters, but they make statements about the class.) So, `Function1[-A,+B]` means that *a function* that takes superclasses of `A` can be viewed as a subclass of *the original function*. Let's see this in practice: ``` class A class B extends A val printB: B => Unit = { b => println("Blah blah") } val printA: A => Unit = { a => println("Blah blah blah") } ``` Now suppose you require a function that knows how to print a `B`: ``` def needsB(f: B => Unit, b: B) = f(b) ``` You could pass in `printB`. But you could *also* pass in `printA`, since it also knows how to print `B`s (and more!), just as if `A => Unit` was a subclass of `B => Unit`. This is exactly what contravariance means. It doesn't mean you can pass `Option[Double]` into `printB` and get anything but a compile-time error! (Covariance is the other case: `M[B] <: M[A]` if `B <: A`.)
A simplified explanation ``` class A class B extends A val printA: A => Unit = { a => println("Blah blah blah") } printA(new A()) //"Blah blah blah" printA(new B()) //"Blah blah blah" ``` contravariance rule: If `B` is a subtype of `A`, then `printA[A]` is a subtype of `printA[B]` Since `printA[B]` is the superclass, we can use `printA(new B())`
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
This question is old, but I think a clearer explanation is to invoke the Liskov Substitution Principle: everything that's true about a superclass should be true of all its subclasses. You should be able to do with a SubFoo everything that you can do with a Foo, and maybe more. Suppose we have Calico <: Cat <: Animal, and Husky <: Dog <: Animal. Let's look at a `Function[Cat, Dog]`. What statements are true about this? There are two: (1) You can pass in any Cat (so any subclass of Cat) (2) You can call any Dog method on the returned value So does `Function[Calico, Dog] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (1). You can't pass in any Cat to a Function that only takes Calico cats. But does `Function[Animal, Dog] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass. I can still pass in any Cat -- in fact I can do even more than that, I can pass in any Animal -- and I can call all Dog methods on the returned value. So `A <: B` implies `Function[B, _] <: Function[A, _]` Now, does `Function[Cat, Husky] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass; I can still pass in a Cat, and I can still call all Dog methods on the returned value -- in fact I can do even more than that, I can call all Husky methods on the returned value. But does `Function[Cat, Animal] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (2). I can't call all methods available on Dog on the returned value, only the ones available on Animal. So with a `Function[Animal, Husky]` I can do everything I can do with a `Function[Cat, Dog]`: I can pass in any Cat, and I can call all of the Dog methods on the returned value. And I can do even more: I can pass in other animals, and I can call of the methods available on Husky that aren't available on Dog. So it makes sense: `Function[Animal, Husky] <: Function[Cat, Dog]`. The first type parameter can be replaced with a superclass, the second with a subclass.
Covariant means converting from wider (super) to narrower (sub). For example, we have two class: one is animal (super) and the other one is cat then using covariant, we can convert animal to cat. Contra-variant is just the opposite of covariant, which means cat to animal. Invariant means it's unable to convert.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
A simplified explanation ``` class A class B extends A val printA: A => Unit = { a => println("Blah blah blah") } printA(new A()) //"Blah blah blah" printA(new B()) //"Blah blah blah" ``` contravariance rule: If `B` is a subtype of `A`, then `printA[A]` is a subtype of `printA[B]` Since `printA[B]` is the superclass, we can use `printA(new B())`
Covariant means converting from wider (super) to narrower (sub). For example, we have two class: one is animal (super) and the other one is cat then using covariant, we can convert animal to cat. Contra-variant is just the opposite of covariant, which means cat to animal. Invariant means it's unable to convert.
10,603,982
I believe one can define covariance (at least, for objects) as 'the ability to use a value of a narrower (sub) type in place of a value of some wider (super) type', and that contravariance is the exact opposite of this. Apparently, Scala functions are instances of Function[-A1,...,+B] for contravariant parameter types A1, etc. and covariant return type, B. While this is handy for subtyping on Functions, shouldn't the above definition mean I can pass any supertypes as parameters? Please advise where I'm mistaken.
2012/05/15
[ "https://Stackoverflow.com/questions/10603982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396545/" ]
This question is old, but I think a clearer explanation is to invoke the Liskov Substitution Principle: everything that's true about a superclass should be true of all its subclasses. You should be able to do with a SubFoo everything that you can do with a Foo, and maybe more. Suppose we have Calico <: Cat <: Animal, and Husky <: Dog <: Animal. Let's look at a `Function[Cat, Dog]`. What statements are true about this? There are two: (1) You can pass in any Cat (so any subclass of Cat) (2) You can call any Dog method on the returned value So does `Function[Calico, Dog] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (1). You can't pass in any Cat to a Function that only takes Calico cats. But does `Function[Animal, Dog] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass. I can still pass in any Cat -- in fact I can do even more than that, I can pass in any Animal -- and I can call all Dog methods on the returned value. So `A <: B` implies `Function[B, _] <: Function[A, _]` Now, does `Function[Cat, Husky] <: Function[Cat, Dog]` make sense? Yes, all statements about the superclass are true of the subclass; I can still pass in a Cat, and I can still call all Dog methods on the returned value -- in fact I can do even more than that, I can call all Husky methods on the returned value. But does `Function[Cat, Animal] <: Function[Cat, Dog]` make sense? No, statements that are true of the superclass are not true of the subclass, namely statement (2). I can't call all methods available on Dog on the returned value, only the ones available on Animal. So with a `Function[Animal, Husky]` I can do everything I can do with a `Function[Cat, Dog]`: I can pass in any Cat, and I can call all of the Dog methods on the returned value. And I can do even more: I can pass in other animals, and I can call of the methods available on Husky that aren't available on Dog. So it makes sense: `Function[Animal, Husky] <: Function[Cat, Dog]`. The first type parameter can be replaced with a superclass, the second with a subclass.
A simplified explanation ``` class A class B extends A val printA: A => Unit = { a => println("Blah blah blah") } printA(new A()) //"Blah blah blah" printA(new B()) //"Blah blah blah" ``` contravariance rule: If `B` is a subtype of `A`, then `printA[A]` is a subtype of `printA[B]` Since `printA[B]` is the superclass, we can use `printA(new B())`
46,616,156
In my iOS app, I have 2 `WKWebView` controls to simulate parent/child relationship of 2 tab/window in our web app so that we can reuse all those javascripts. Problem is that there is no generic communication channel between these 2 `WKWebView`s. **Web Architecture**: - The first/master window loads our internal javascript functions with links opening in second/child window. - The second/child window loads third party web content. - The third party content communicates with our system using javascript form source window (using window.opener / window.parent API bridge). Now, in the **native app**, this is what I'm doing to reuse existing javascripts and simulate web archtecture - a. Below js call from the webpage in **1st WKWebView** - ``` window.open("http://localhost/child.html", "myWindow", "width=200,height=100"); ``` b. The WKUIDelegate intercepts this call (a) and opens **2nd WKWebView** - ``` - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { // Here, window.open js calls are handled by loading the request in another/new web view UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; WebViewController *webViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"WebViewController"]; webViewController.loadURLString = navigationAction.request.URL.absoluteString; // Show controller without interfering the current flow of API call, thus dispatch after a fraction of second dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self.navigationController pushViewController:webViewController animated:YES]; }); return nil; } ``` c. In web/computer browser, the child window of web app is able to access source js functions using `window.opener` and `window.parent` How to achieve the same functionality in `WKWebView`s? In other words, js functions in 2nd `WKWebView` could call js functions from parent/source `WKWebView`?
2017/10/07
[ "https://Stackoverflow.com/questions/46616156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654016/" ]
You definitely should not return `nil` from `webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:`, but an instance of your `WKWebView`. Unfortunately, I have no way to verify this right now. But as far as I remember, the trick is also to not ignore `WKWebViewConfiguration` argument from `webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:` delegate method, but create a second `WKWebView` instance, passing this argument as one of the `initWithFrame:configuration:` parameters. Also, according Apple documentation, looks like you don't need to load the request yourself if you're returning correct web view instance. WebKit should handle this for you. Overall your code should look similar to: ``` - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { WKWebView *childWebView = [[WKWebView alloc] initWithFrame:CGFrameZero configuration:configuration]; WebViewController *webViewController = [[WebViewController alloc] initWithWebView: childWebView]; // looks like this is no longer required, but I can't check it now :( // [childWebView loadRequest:navigationAction.request]; // Show controller without interfering the current flow of API call, thus dispatch after a fraction of second dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self.navigationController pushViewController:webViewController animated:YES]; }); return childWebView; } ```
A simpler way to accomplish your task will be to have one WKWebView, and use HTML to separate header and detail. The simplest solution is to have one HTML document with the header and all of the details, but if you need to add details dynamically that can also be done use the DOM. Reusing Javascript for both the header and detail will be easiest with this approach.
51,845,399
**Langauge** Java **Application:** Patient Viewer/Creator **Question** 1. How should I handle the objects being created? 2. What are the negatives of saving Patient objects to a structure as they are being created? Any positives? **Current Implementation:** My initial thought was to create an ArrayList or Map and save Patient objects to the data structure as they are being created. Doing a little bit of research I found that doing something like this might not be the most secure thing to do, with things like memory leakage.(What are the other negatives?) ``` public class PatientApp { public static void main(String[] args) { ArrayList<Patient> patientList = new ArrayList<>(); Patient patient = new Patient(); patientList.add(patient); } } ``` Then I figured I could saved the patient objects to a file and load that file when I need to retrieve patient information. Would that be a better implementation?
2018/08/14
[ "https://Stackoverflow.com/questions/51845399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Sounds like what you need is string formatting, something like this: ``` def get_sentence(author,pud_date): return "This article was written by {}, who is solely responsible for its content. This article was published on {}.".format(author,pub_date) ``` Assuming you are parsing the variables that make up the string iteratively, you can call this function with the arguments needed and get the string returned. That str.format() function can be placed anywhere and can take any number of arguments as long as there is a place for it in the string indicated by the {}. I suggest you play around with this function on the interpreter or ipython notebook to get familiar with it.
If you have control over the templates I would use `str.format` and a `dict` containing the variables: ``` >>> template = "This {publication} was written by {author}, who is solely responsible for its content." >>> variables = {"publication": "article", "author": "Me"} template.format(**variables) 'This article was written by Me, who is solely responsible for its content.' ``` It is easy to extend this to a list of strings: ``` templates = [ "String with {var1}", "String with {var2}", ] variables = { "var1": "value for var1", "var2": "value for var2", } replaced = [template.format(**variables) for template in templates] ```
51,845,399
**Langauge** Java **Application:** Patient Viewer/Creator **Question** 1. How should I handle the objects being created? 2. What are the negatives of saving Patient objects to a structure as they are being created? Any positives? **Current Implementation:** My initial thought was to create an ArrayList or Map and save Patient objects to the data structure as they are being created. Doing a little bit of research I found that doing something like this might not be the most secure thing to do, with things like memory leakage.(What are the other negatives?) ``` public class PatientApp { public static void main(String[] args) { ArrayList<Patient> patientList = new ArrayList<>(); Patient patient = new Patient(); patientList.add(patient); } } ``` Then I figured I could saved the patient objects to a file and load that file when I need to retrieve patient information. Would that be a better implementation?
2018/08/14
[ "https://Stackoverflow.com/questions/51845399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
With Python 3.6+, you may find formatted string literals ([PEP 498](https://www.python.org/dev/peps/pep-0498/)) efficient: ``` # data from @bohrax d = {"publication": "article", "author": "Me"} template = f"This {d['publication']} was written by {d['author']}, who is solely responsible for its content." print(template) This article was written by Me, who is solely responsible for its content. ```
If you have control over the templates I would use `str.format` and a `dict` containing the variables: ``` >>> template = "This {publication} was written by {author}, who is solely responsible for its content." >>> variables = {"publication": "article", "author": "Me"} template.format(**variables) 'This article was written by Me, who is solely responsible for its content.' ``` It is easy to extend this to a list of strings: ``` templates = [ "String with {var1}", "String with {var2}", ] variables = { "var1": "value for var1", "var2": "value for var2", } replaced = [template.format(**variables) for template in templates] ```
51,509,317
How can I generate a authorization request header ? I have read about [authorization request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) and I generated one using username and password in base 64, but when I pass it on request header it doesn't work (`"error": "invalid_client`). Using Postman to make the request everything works : ``` POST /oauth/token content-type: application/x-www-form-urlencoded authorization: Basic M1g4Vlk2QllHOFFJTDA3amt1cWpsUnNKOmhoWkNlSEg0SzFuVVJ2VTZmNUs5MmFiTlNSN3h3ZlBCYVN6OXI1WG1pcDNZOGJCbA== user-agent: PostmanRuntime/7.1.5 accept: */* host: 127.0.0.1:5000 accept-encoding: gzip, deflate content-length: 97 ``` **Obs** ¹ : The api uses the password grant type and return a bearer token **Obs** ² : When I generate a authorization request header using username and password (`base64.b64encode(b'')`) the lenght of the output is 20 characters
2018/07/25
[ "https://Stackoverflow.com/questions/51509317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can do ``` new THREE.SphereGeometry(1, 32, 32, 0, 2*Math.PI, 0, Math.PI/2); ```
``` //Here's some code to modify a sphere into a hemisphere var sphereGeom = new THREE.SphereBufferGeometry(1,16,16); let verts = sphereGeom.attributes.position.array for(var i=0;i<verts.length;i+=3){ if(verts[i+1]<0) verts[i+1]=0; } sphereGeom.computeFaceNormals(); sphereGeom.computeVertexNormals(); //sphereGeom.verticesNeedUpdate = true; //Working snippet is below... ``` ```js var renderer = new THREE.WebGLRenderer(); var w = 300; var h = 200; renderer.setSize( w,h ); document.body.appendChild( renderer.domElement ); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 45, // Field of view w/h, // Aspect ratio 0.1, // Near 10000 // Far ); camera.position.set( 15, 10, 15 ); camera.lookAt( scene.position ); controls = new THREE.OrbitControls(camera, renderer.domElement); var light = new THREE.PointLight( 0xFFFF00 ); light.position.set( 20, 20, 20 ); scene.add( light ); var light1 = new THREE.AmbientLight( 0x808080 ); light1.position.set( 20, 20, 20 ); scene.add( light1 ); var light2 = new THREE.PointLight( 0x00FFFF ); light2.position.set( -20, 20, -20 ); scene.add( light2 ); var light3 = new THREE.PointLight( 0xFF00FF ); light3.position.set( -20, -20, -20 ); scene.add( light3 ); var sphereGeom = new THREE.SphereBufferGeometry(5,16,16); let verts = sphereGeom.attributes.position.array for(var i=0;i<verts.length;i+=3){ if(verts[i+1]<0) verts[i+1]=0; } sphereGeom.computeFaceNormals(); sphereGeom.computeVertexNormals(); var material = new THREE.MeshLambertMaterial( { color: 0x808080 } ); var mesh = new THREE.Mesh( sphereGeom, material ); scene.add( mesh ); renderer.setClearColor( 0xdddddd, 1); (function animate() { requestAnimationFrame(animate); controls.update(); renderer.render(scene, camera); })(); ``` ```html <script src="https://threejs.org/build/three.min.js"></script> <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script> ```
51,509,317
How can I generate a authorization request header ? I have read about [authorization request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) and I generated one using username and password in base 64, but when I pass it on request header it doesn't work (`"error": "invalid_client`). Using Postman to make the request everything works : ``` POST /oauth/token content-type: application/x-www-form-urlencoded authorization: Basic M1g4Vlk2QllHOFFJTDA3amt1cWpsUnNKOmhoWkNlSEg0SzFuVVJ2VTZmNUs5MmFiTlNSN3h3ZlBCYVN6OXI1WG1pcDNZOGJCbA== user-agent: PostmanRuntime/7.1.5 accept: */* host: 127.0.0.1:5000 accept-encoding: gzip, deflate content-length: 97 ``` **Obs** ¹ : The api uses the password grant type and return a bearer token **Obs** ² : When I generate a authorization request header using username and password (`base64.b64encode(b'')`) the lenght of the output is 20 characters
2018/07/25
[ "https://Stackoverflow.com/questions/51509317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My 5 kopeikas. Hemisphere + circle: ```js var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000); camera.position.set(0, 5, 8); var renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var controls = new THREE.OrbitControls(camera, renderer.domElement); var light = new THREE.DirectionalLight(0xffffff, 0.5); light.position.setScalar(10); scene.add(light); scene.add(new THREE.AmbientLight(0xffffff, 0.5)); scene.add(new THREE.AxesHelper(5)); var radius = 3; var radialSegments = 32; var material = new THREE.MeshStandardMaterial({ color: "blue" }); var hemiSphereGeom = new THREE.SphereBufferGeometry(radius, radialSegments, Math.round(radialSegments / 4), 0, Math.PI * 2, 0, Math.PI * 0.5); var hemiSphere = new THREE.Mesh(hemiSphereGeom, material); var capGeom = new THREE.CircleBufferGeometry(radius, radialSegments); capGeom.rotateX(Math.PI * 0.5); var cap = new THREE.Mesh(capGeom, material); hemiSphere.add(cap); scene.add(hemiSphere); render(); function render() { requestAnimationFrame(render); renderer.render(scene, camera); } ``` ```css body { overflow: hidden; margin: 0; } ``` ```html <script src="https://cdn.jsdelivr.net/npm/three@0.94.0/build/three.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/three@0.94.0/examples/js/controls/OrbitControls.js"></script> ```
``` //Here's some code to modify a sphere into a hemisphere var sphereGeom = new THREE.SphereBufferGeometry(1,16,16); let verts = sphereGeom.attributes.position.array for(var i=0;i<verts.length;i+=3){ if(verts[i+1]<0) verts[i+1]=0; } sphereGeom.computeFaceNormals(); sphereGeom.computeVertexNormals(); //sphereGeom.verticesNeedUpdate = true; //Working snippet is below... ``` ```js var renderer = new THREE.WebGLRenderer(); var w = 300; var h = 200; renderer.setSize( w,h ); document.body.appendChild( renderer.domElement ); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 45, // Field of view w/h, // Aspect ratio 0.1, // Near 10000 // Far ); camera.position.set( 15, 10, 15 ); camera.lookAt( scene.position ); controls = new THREE.OrbitControls(camera, renderer.domElement); var light = new THREE.PointLight( 0xFFFF00 ); light.position.set( 20, 20, 20 ); scene.add( light ); var light1 = new THREE.AmbientLight( 0x808080 ); light1.position.set( 20, 20, 20 ); scene.add( light1 ); var light2 = new THREE.PointLight( 0x00FFFF ); light2.position.set( -20, 20, -20 ); scene.add( light2 ); var light3 = new THREE.PointLight( 0xFF00FF ); light3.position.set( -20, -20, -20 ); scene.add( light3 ); var sphereGeom = new THREE.SphereBufferGeometry(5,16,16); let verts = sphereGeom.attributes.position.array for(var i=0;i<verts.length;i+=3){ if(verts[i+1]<0) verts[i+1]=0; } sphereGeom.computeFaceNormals(); sphereGeom.computeVertexNormals(); var material = new THREE.MeshLambertMaterial( { color: 0x808080 } ); var mesh = new THREE.Mesh( sphereGeom, material ); scene.add( mesh ); renderer.setClearColor( 0xdddddd, 1); (function animate() { requestAnimationFrame(animate); controls.update(); renderer.render(scene, camera); })(); ``` ```html <script src="https://threejs.org/build/three.min.js"></script> <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script> ```
24,149,047
I have an issue with WPF `DataGrid`, which drives me crazy. Let's consider this view model: ``` public class ViewModel : INotifyPropertyChanged { public int Id { get; set; } public string Name { get; set; } public bool IsSelected { get { return isSelected; } set { System.Diagnostics.Debug.WriteLine("{0}'s IsSelected new value is: {1}", Name, value); if (isSelected != value) { isSelected = value; OnPropertyChanged("IsSelected"); } } } private bool isSelected; // INPC implementation } ``` ... this XAML: ``` <Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid ItemsSource="{Binding}" IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Extended" SelectionUnit="FullRow"> <DataGrid.ItemContainerStyle> <Style TargetType="{x:Type DataGridRow}"> <Setter Property="IsSelected" Value="{Binding IsSelected}"/> </Style> </DataGrid.ItemContainerStyle> <DataGrid.Columns> <DataGridCheckBoxColumn Header="Is selected" Binding="{Binding IsSelected}"/> <DataGridTextColumn Header="Id" Binding="{Binding Id}"/> <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window> ``` ...and this code-behind: ``` public partial class MainWindow : Window { private IList<ViewModel> GenerateViewModels() { var viewModels = new List<ViewModel>(); for (var i = 0; i < 100; i++) { viewModels.Add(new ViewModel { Id = i, Name = string.Format("Item {0}", i) }); } return viewModels; } public MainWindow() { InitializeComponent(); DataContext = GenerateViewModels(); } } ``` **Case 1.** * Select Item 0. Item 0 is selected, check box is checked. * Scroll grid's content to hide Item 0. Let the Item 6 be on top of visible area. * Select Item 10. Item 10 is selected, check box is checked. * Scroll up to Item 0. * Select Item 0. Item 10 is selected, check box is **not** checked. Debug output: ``` Item 0's IsSelected new value is: True Item 0's IsSelected new value is: False Item 10's IsSelected new value is: True Item 10's IsSelected new value is: False ``` ![Screenshot:](https://i.stack.imgur.com/HIYfp.png) **Case 2.** * Restart application. * Select several items on top of grid (e.g., three first items). Items are selected, check boxes are checked. * Scroll grid's content to hide Item 0. Let the Item 6 be on top of visible area. * Select Item 10. Item 10 is selected, check box is checked. * Scroll up to Item 0. * Item 0 and Item 1 **are still checked**. Item 2 isn't checked. All of three first items aren't selected. Debug output: ``` Item 0's IsSelected new value is: True Item 1's IsSelected new value is: True Item 2's IsSelected new value is: True Item 2's IsSelected new value is: False Item 10's IsSelected new value is: True ``` ![Screenshot:](https://i.stack.imgur.com/Xr8i1.png) The problem is reproducing, when the selection mode is extended. When it is single, everything works fine. **Questions:** 1. Am I missing something? 2. Anybody knows a workaround? **UPDATE**. I've added `SelectionChanged` event handler for the grid: ``` private void MyGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems != null) { foreach (var item in e.AddedItems.Cast<ViewModel>()) { System.Diagnostics.Debug.WriteLine("** Item {0} is added to selection.", item.Id); } } if (e.RemovedItems != null) { foreach (var item in e.RemovedItems.Cast<ViewModel>()) { System.Diagnostics.Debug.WriteLine("** Item {0} is removed from selection.", item.Id); } } e.Handled = true; } ``` Debug output says, that `SelectedItems` collection is updated **properly**. E.g., for the first case output will be: ``` Item 0's IsSelected new value is: True ** Item 0 is added to selection. Item 0's IsSelected new value is: False Item 10's IsSelected new value is: True ** Item 10 is added to selection. ** Item 0 is removed from selection. Item 10's IsSelected new value is: False ** Item 0 is added to selection. ** Item 10 is removed from selection. ``` But the bound data property `IsSelected` isn't updated!
2014/06/10
[ "https://Stackoverflow.com/questions/24149047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580053/" ]
You need to understand how a HashMap works. When you put a key in a HashMap, containing N buckets, the hashCode of the key is used to find the appropriate bucket. Then each key contained in the bucket is compared, using equals(), with the added key, to know if the key is already in the map. Similarly, when getting the value for a key, the hashCode() is first used to find the appropriate bucket, then each key in this bucket is compared with equals() to the key passed to get(). You're doing two things which you should never do when using HashMaps: 1. Modifying the key after it has been stored in the map. This modifies its hashCode, and causes thekey to not be searched for in the appropriate bucket. A bit as if you put all red coins in a red drawer, and then repainted one of the keys to blue. Obviously, if you then search for the blue coins, you'll search them in the blue drawer, and not in the red drawer where it has been stored, since it was red initially. 2. Implementing hashCode() using an algorithm that makes many keys have the same value. It's the case for "clover" and "arthur", which have the same length, and thus the same hashCode() given your implementation. "magnolia", on the other hand, doesn't have the same hashCode(). Given the above, you should be able to understand why your code works the way it does. Just draw what happens on paper for each operation, and you'll understand.
First: What do you want to do? Second: The `equals()` is the first problem as it only compares references. See [Here](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) Third: The `hashCode()` function for `dog` is missing. you should never overwrite only one of `equals()` and `hashCode()` See [Here](http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/)
24,149,047
I have an issue with WPF `DataGrid`, which drives me crazy. Let's consider this view model: ``` public class ViewModel : INotifyPropertyChanged { public int Id { get; set; } public string Name { get; set; } public bool IsSelected { get { return isSelected; } set { System.Diagnostics.Debug.WriteLine("{0}'s IsSelected new value is: {1}", Name, value); if (isSelected != value) { isSelected = value; OnPropertyChanged("IsSelected"); } } } private bool isSelected; // INPC implementation } ``` ... this XAML: ``` <Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid ItemsSource="{Binding}" IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Extended" SelectionUnit="FullRow"> <DataGrid.ItemContainerStyle> <Style TargetType="{x:Type DataGridRow}"> <Setter Property="IsSelected" Value="{Binding IsSelected}"/> </Style> </DataGrid.ItemContainerStyle> <DataGrid.Columns> <DataGridCheckBoxColumn Header="Is selected" Binding="{Binding IsSelected}"/> <DataGridTextColumn Header="Id" Binding="{Binding Id}"/> <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window> ``` ...and this code-behind: ``` public partial class MainWindow : Window { private IList<ViewModel> GenerateViewModels() { var viewModels = new List<ViewModel>(); for (var i = 0; i < 100; i++) { viewModels.Add(new ViewModel { Id = i, Name = string.Format("Item {0}", i) }); } return viewModels; } public MainWindow() { InitializeComponent(); DataContext = GenerateViewModels(); } } ``` **Case 1.** * Select Item 0. Item 0 is selected, check box is checked. * Scroll grid's content to hide Item 0. Let the Item 6 be on top of visible area. * Select Item 10. Item 10 is selected, check box is checked. * Scroll up to Item 0. * Select Item 0. Item 10 is selected, check box is **not** checked. Debug output: ``` Item 0's IsSelected new value is: True Item 0's IsSelected new value is: False Item 10's IsSelected new value is: True Item 10's IsSelected new value is: False ``` ![Screenshot:](https://i.stack.imgur.com/HIYfp.png) **Case 2.** * Restart application. * Select several items on top of grid (e.g., three first items). Items are selected, check boxes are checked. * Scroll grid's content to hide Item 0. Let the Item 6 be on top of visible area. * Select Item 10. Item 10 is selected, check box is checked. * Scroll up to Item 0. * Item 0 and Item 1 **are still checked**. Item 2 isn't checked. All of three first items aren't selected. Debug output: ``` Item 0's IsSelected new value is: True Item 1's IsSelected new value is: True Item 2's IsSelected new value is: True Item 2's IsSelected new value is: False Item 10's IsSelected new value is: True ``` ![Screenshot:](https://i.stack.imgur.com/Xr8i1.png) The problem is reproducing, when the selection mode is extended. When it is single, everything works fine. **Questions:** 1. Am I missing something? 2. Anybody knows a workaround? **UPDATE**. I've added `SelectionChanged` event handler for the grid: ``` private void MyGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems != null) { foreach (var item in e.AddedItems.Cast<ViewModel>()) { System.Diagnostics.Debug.WriteLine("** Item {0} is added to selection.", item.Id); } } if (e.RemovedItems != null) { foreach (var item in e.RemovedItems.Cast<ViewModel>()) { System.Diagnostics.Debug.WriteLine("** Item {0} is removed from selection.", item.Id); } } e.Handled = true; } ``` Debug output says, that `SelectedItems` collection is updated **properly**. E.g., for the first case output will be: ``` Item 0's IsSelected new value is: True ** Item 0 is added to selection. Item 0's IsSelected new value is: False Item 10's IsSelected new value is: True ** Item 10 is added to selection. ** Item 0 is removed from selection. Item 10's IsSelected new value is: False ** Item 0 is added to selection. ** Item 10 is removed from selection. ``` But the bound data property `IsSelected` isn't updated!
2014/06/10
[ "https://Stackoverflow.com/questions/24149047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580053/" ]
You need to understand how a HashMap works. When you put a key in a HashMap, containing N buckets, the hashCode of the key is used to find the appropriate bucket. Then each key contained in the bucket is compared, using equals(), with the added key, to know if the key is already in the map. Similarly, when getting the value for a key, the hashCode() is first used to find the appropriate bucket, then each key in this bucket is compared with equals() to the key passed to get(). You're doing two things which you should never do when using HashMaps: 1. Modifying the key after it has been stored in the map. This modifies its hashCode, and causes thekey to not be searched for in the appropriate bucket. A bit as if you put all red coins in a red drawer, and then repainted one of the keys to blue. Obviously, if you then search for the blue coins, you'll search them in the blue drawer, and not in the red drawer where it has been stored, since it was red initially. 2. Implementing hashCode() using an algorithm that makes many keys have the same value. It's the case for "clover" and "arthur", which have the same length, and thus the same hashCode() given your implementation. "magnolia", on the other hand, doesn't have the same hashCode(). Given the above, you should be able to understand why your code works the way it does. Just draw what happens on paper for each operation, and you'll understand.
I would strongly suggest you to begin with reading [how hashmap works in java](http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/) There are multiple issues here. 1. When you invoke `m.put(d1, "Dog key");`, the hashCode is calculated and a bucket in the hashMap where the object will be stored is determined. The hashCode value is 6 in this case. 2. Then you're changing the name to `magnolia` (and thus the hashCode to 8). HashMap tries to search for matching object, but based on hashCode, it finds out, that there is no object stored in the bucket corresponding to hashCode value = 8. 3. Then you're changing the name back to `clover`, and, long story short, the object can be found. 4. Then you're changing the name to `arthur`. The hashCode is 6 again and HashMap manages to find the right bucket and using equals method - find the object. Read more about `hashCode` and `equals`: <http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode%28%29>. BTW You should use `equals` method for comparing Strings (read <http://www.javapractices.com/topic/TopicAction.do?Id=18>).
24,149,047
I have an issue with WPF `DataGrid`, which drives me crazy. Let's consider this view model: ``` public class ViewModel : INotifyPropertyChanged { public int Id { get; set; } public string Name { get; set; } public bool IsSelected { get { return isSelected; } set { System.Diagnostics.Debug.WriteLine("{0}'s IsSelected new value is: {1}", Name, value); if (isSelected != value) { isSelected = value; OnPropertyChanged("IsSelected"); } } } private bool isSelected; // INPC implementation } ``` ... this XAML: ``` <Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid ItemsSource="{Binding}" IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Extended" SelectionUnit="FullRow"> <DataGrid.ItemContainerStyle> <Style TargetType="{x:Type DataGridRow}"> <Setter Property="IsSelected" Value="{Binding IsSelected}"/> </Style> </DataGrid.ItemContainerStyle> <DataGrid.Columns> <DataGridCheckBoxColumn Header="Is selected" Binding="{Binding IsSelected}"/> <DataGridTextColumn Header="Id" Binding="{Binding Id}"/> <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window> ``` ...and this code-behind: ``` public partial class MainWindow : Window { private IList<ViewModel> GenerateViewModels() { var viewModels = new List<ViewModel>(); for (var i = 0; i < 100; i++) { viewModels.Add(new ViewModel { Id = i, Name = string.Format("Item {0}", i) }); } return viewModels; } public MainWindow() { InitializeComponent(); DataContext = GenerateViewModels(); } } ``` **Case 1.** * Select Item 0. Item 0 is selected, check box is checked. * Scroll grid's content to hide Item 0. Let the Item 6 be on top of visible area. * Select Item 10. Item 10 is selected, check box is checked. * Scroll up to Item 0. * Select Item 0. Item 10 is selected, check box is **not** checked. Debug output: ``` Item 0's IsSelected new value is: True Item 0's IsSelected new value is: False Item 10's IsSelected new value is: True Item 10's IsSelected new value is: False ``` ![Screenshot:](https://i.stack.imgur.com/HIYfp.png) **Case 2.** * Restart application. * Select several items on top of grid (e.g., three first items). Items are selected, check boxes are checked. * Scroll grid's content to hide Item 0. Let the Item 6 be on top of visible area. * Select Item 10. Item 10 is selected, check box is checked. * Scroll up to Item 0. * Item 0 and Item 1 **are still checked**. Item 2 isn't checked. All of three first items aren't selected. Debug output: ``` Item 0's IsSelected new value is: True Item 1's IsSelected new value is: True Item 2's IsSelected new value is: True Item 2's IsSelected new value is: False Item 10's IsSelected new value is: True ``` ![Screenshot:](https://i.stack.imgur.com/Xr8i1.png) The problem is reproducing, when the selection mode is extended. When it is single, everything works fine. **Questions:** 1. Am I missing something? 2. Anybody knows a workaround? **UPDATE**. I've added `SelectionChanged` event handler for the grid: ``` private void MyGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems != null) { foreach (var item in e.AddedItems.Cast<ViewModel>()) { System.Diagnostics.Debug.WriteLine("** Item {0} is added to selection.", item.Id); } } if (e.RemovedItems != null) { foreach (var item in e.RemovedItems.Cast<ViewModel>()) { System.Diagnostics.Debug.WriteLine("** Item {0} is removed from selection.", item.Id); } } e.Handled = true; } ``` Debug output says, that `SelectedItems` collection is updated **properly**. E.g., for the first case output will be: ``` Item 0's IsSelected new value is: True ** Item 0 is added to selection. Item 0's IsSelected new value is: False Item 10's IsSelected new value is: True ** Item 10 is added to selection. ** Item 0 is removed from selection. Item 10's IsSelected new value is: False ** Item 0 is added to selection. ** Item 10 is removed from selection. ``` But the bound data property `IsSelected` isn't updated!
2014/06/10
[ "https://Stackoverflow.com/questions/24149047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580053/" ]
I would strongly suggest you to begin with reading [how hashmap works in java](http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/) There are multiple issues here. 1. When you invoke `m.put(d1, "Dog key");`, the hashCode is calculated and a bucket in the hashMap where the object will be stored is determined. The hashCode value is 6 in this case. 2. Then you're changing the name to `magnolia` (and thus the hashCode to 8). HashMap tries to search for matching object, but based on hashCode, it finds out, that there is no object stored in the bucket corresponding to hashCode value = 8. 3. Then you're changing the name back to `clover`, and, long story short, the object can be found. 4. Then you're changing the name to `arthur`. The hashCode is 6 again and HashMap manages to find the right bucket and using equals method - find the object. Read more about `hashCode` and `equals`: <http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode%28%29>. BTW You should use `equals` method for comparing Strings (read <http://www.javapractices.com/topic/TopicAction.do?Id=18>).
First: What do you want to do? Second: The `equals()` is the first problem as it only compares references. See [Here](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) Third: The `hashCode()` function for `dog` is missing. you should never overwrite only one of `equals()` and `hashCode()` See [Here](http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/)
4,406,191
i make a dynamic textbox through javascript now i want to post the data of all dynamically generated textboxes to php script and then insert into a table. how can i do this... ``` <head> <title>Dynamic Form</title> <script language="javascript"> function changeIt() { var i = 1; my_div.innerHTML = my_div.innerHTML +"&ltbr><input type='text' name='mytext'+ i>" } </script> </head> <body> <form name="form" action="post" method=""> <input type="button" value="add another textbox" onClick="changeIt()"> <div id="my_div"> <input type="submit" value="save"> </body> ```
2010/12/10
[ "https://Stackoverflow.com/questions/4406191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501751/" ]
In spite of what everyone says, `Silverlight` (and even `Flash`) is not everywhere. There are still a lot of users and browsers that don't have or support `Silverlight`. Of course it will be a great application if built using `Silverlight`, but you cannot just ignore the ones who don't have it installed. If you go with `Silverlight`, you will still need to implement a simple HTML version of your `Admin Panel`. Having said all of this, it really depends on your user base, scope of your application and the type of environment it is going to run in.
I'm not really familiar with Silverlight so I can't judge anything about it. With regards to html I guess Its a better choice if you want it available in many browser. If you heard about html5 I think you'll have a second thought about it. Well it still base on your needs.
4,406,191
i make a dynamic textbox through javascript now i want to post the data of all dynamically generated textboxes to php script and then insert into a table. how can i do this... ``` <head> <title>Dynamic Form</title> <script language="javascript"> function changeIt() { var i = 1; my_div.innerHTML = my_div.innerHTML +"&ltbr><input type='text' name='mytext'+ i>" } </script> </head> <body> <form name="form" action="post" method=""> <input type="button" value="add another textbox" onClick="changeIt()"> <div id="my_div"> <input type="submit" value="save"> </body> ```
2010/12/10
[ "https://Stackoverflow.com/questions/4406191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501751/" ]
Guess it depends on your audience. For an admin panel, unless you need the maximum reach to various devices and operating systems, Silverlight is probably fine and will probably allow you to whip something together very quickly using RIA services or WCF Data Services. As far as security goes - you'll want to secure your services the same way regardless of whether you're using a HTML or Silverlight client to access them. Basically, just never assume that your client is the only one accessing your services. Don't send any data down to the client that you wouldn't want exposed and don't trust any input from the client without validating it first. This is where RIA services can help as it can coordinate validation rules on the client and server.
I'm not really familiar with Silverlight so I can't judge anything about it. With regards to html I guess Its a better choice if you want it available in many browser. If you heard about html5 I think you'll have a second thought about it. Well it still base on your needs.
32,963,159
So far what I have is: ``` base = int(input("Enter a value")) for row in range(base): for colomb in range(row+1): print('*', end='') print() ```
2015/10/06
[ "https://Stackoverflow.com/questions/32963159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5412716/" ]
You were nearly there. You just need to unindent the last `print()`. Example - ``` for row in range(base): for colomb in range(row+1): print('*', end='') print() ```
Sharon's answer is the quickest solution to make the code you have work, but you could also do fewer runs through `for` loops by just printing (once) the entire string. `"a" * 3` is `"aaa"`, for instance, so you could do: ``` for row in range(1, base+1): # now the range runs [1-base] instead of [0-base-1] print("*" * row) ```
37,506,172
I am trying to load images from a url and I have used Picasso, however I'd like to know how to do it without an external library if possible. I know I have to get an Asynctask going but I'm not sure how to implement it. This is my getview code ``` @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if(position==0){ NewsObj currNews = news.get(position); DataHandler dh; if(convertView==null){ LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.firstnews,parent,false); dh = new DataHandler(); dh.newsTitle = (TextView)row.findViewById(R.id.newsTitle); dh.newsDate = (TextView)row.findViewById(R.id.newsDate); dh.newsIcon = (ImageView)row.findViewById(R.id.newsIcon); row.setTag(dh); }else{ dh = (DataHandler)row.getTag(); } NewsObj no = (NewsObj)this.getItem(position); new AsyncDownloadTask().execute(row,no.getImgurl()); dh.newsTitle.setText(no.getTitle()); dh.newsDate.setText(no.getDate()); }else{ NewsObj currNews = news.get(position); DataHandler dh; if(convertView==null){ LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.newslist,parent,false); dh = new DataHandler(); dh.newsTitle = (TextView)row.findViewById(R.id.newsTitle); dh.newsDate = (TextView)row.findViewById(R.id.newsDate); dh.newsIcon = (ImageView)row.findViewById(R.id.newsIcon); row.setTag(dh); }else{ dh = (DataHandler)row.getTag(); } NewsObj no = (NewsObj)this.getItem(position); new AsyncDownloadTask().execute(row,no.getImgurl()); dh.newsTitle.setText(no.getTitle()); dh.newsDate.setText(no.getDate()); } return row; } private class AsyncDownloadTask extends AsyncTask<Object, String, Bitmap>{ private View view; private Bitmap bitmap = null; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Bitmap bitmap) { if(bitmap!=null&&view!=null){ ImageView newsIcon = (ImageView)view.getTag(R.id.newsIcon); newsIcon.setImageBitmap(bitmap); } } @Override protected Bitmap doInBackground(Object... params) { view = (View)params[0]; String uri = (String)params[1]; try{ InputStream inputStream = new URL(uri).openStream(); bitmap = BitmapFactory.decodeStream(inputStream); }catch (Exception e){ e.printStackTrace(); } return bitmap; } } ``` This is my async task UPDATE : Encountering null pointer exceptions ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference ```
2016/05/29
[ "https://Stackoverflow.com/questions/37506172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4907861/" ]
Simply you can use [`java.net.URL`](https://docs.oracle.com/javase/7/docs/api/java/net/URL.html) for loading an image into ImageView like ``` ImageView loadedImage; @override protected Bitmap doInBackground(String... url) { String URL_OF_IMAGE = url[0]; Bitmap bitmap = null; try { InputStream in = new java.net.URL(URL_OF_IMAGE).openStream(); bitmap= BitmapFactory.decodeStream(in); } catch (Exception e) { } return bitmap; } protected void onPostExecute(Bitmap result) { loadedImage.setImageBitmap(result); } ``` But notice that you should have extend `AsyncTask` that should have first parameter as `String` and last as `Bitmap` like ``` private class DowmloadImage extends AsyncTask<String, Void, Bitmap> ```
You can Use Network Image View instead of Imageview. It surely makes your life easier. ``` <com.android.volley.toolbox.NetworkImageView android:id="@+id/networkImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="#000000"/> ``` This should be replaced in place of Image view in the required XML File. ``` public ImageLoader getImageLoader() { getRequestQueue(); if (mImageLoader == null) { mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache()); } return this.mImageLoader; } ``` The class above also creates an ImageCache which works with normal volley cache, but only caching images for requests. To Set the Image URL. ``` advImage.setImageUrl("Your Image URL", AppController.getInstance().getImageLoader()); ``` Call the Image Loader Function accordingly. You can also set the defalult placeholder image as well.
37,506,172
I am trying to load images from a url and I have used Picasso, however I'd like to know how to do it without an external library if possible. I know I have to get an Asynctask going but I'm not sure how to implement it. This is my getview code ``` @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if(position==0){ NewsObj currNews = news.get(position); DataHandler dh; if(convertView==null){ LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.firstnews,parent,false); dh = new DataHandler(); dh.newsTitle = (TextView)row.findViewById(R.id.newsTitle); dh.newsDate = (TextView)row.findViewById(R.id.newsDate); dh.newsIcon = (ImageView)row.findViewById(R.id.newsIcon); row.setTag(dh); }else{ dh = (DataHandler)row.getTag(); } NewsObj no = (NewsObj)this.getItem(position); new AsyncDownloadTask().execute(row,no.getImgurl()); dh.newsTitle.setText(no.getTitle()); dh.newsDate.setText(no.getDate()); }else{ NewsObj currNews = news.get(position); DataHandler dh; if(convertView==null){ LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.newslist,parent,false); dh = new DataHandler(); dh.newsTitle = (TextView)row.findViewById(R.id.newsTitle); dh.newsDate = (TextView)row.findViewById(R.id.newsDate); dh.newsIcon = (ImageView)row.findViewById(R.id.newsIcon); row.setTag(dh); }else{ dh = (DataHandler)row.getTag(); } NewsObj no = (NewsObj)this.getItem(position); new AsyncDownloadTask().execute(row,no.getImgurl()); dh.newsTitle.setText(no.getTitle()); dh.newsDate.setText(no.getDate()); } return row; } private class AsyncDownloadTask extends AsyncTask<Object, String, Bitmap>{ private View view; private Bitmap bitmap = null; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Bitmap bitmap) { if(bitmap!=null&&view!=null){ ImageView newsIcon = (ImageView)view.getTag(R.id.newsIcon); newsIcon.setImageBitmap(bitmap); } } @Override protected Bitmap doInBackground(Object... params) { view = (View)params[0]; String uri = (String)params[1]; try{ InputStream inputStream = new URL(uri).openStream(); bitmap = BitmapFactory.decodeStream(inputStream); }catch (Exception e){ e.printStackTrace(); } return bitmap; } } ``` This is my async task UPDATE : Encountering null pointer exceptions ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference ```
2016/05/29
[ "https://Stackoverflow.com/questions/37506172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4907861/" ]
You can write your own code. But using a library handles all the boilerplate code which is associated with a library. Unless otherwise, I also recommend that you use a library. Here are some of the boilerplate things that you need to consider when writing your own code. 1. **Memory management:** External libraries take care of making sure the images doesn't take up all of the memory available for your app. Android Bitmaps are very memory conscious to deal with and therefore better to give this part to a library. 2. **Handling activity destruction:** If you rotate your phone while an image download is in progress, it will recreate the activity and then you will need to handle cancellation of the previous requests and start them again. 3. **Cancelling previous requests:** Image libraries are written such that list view items which are no longer visible do not continue downloading. Suppose you scroll down. Then there is no point in downloading the images which are part of the first rows. You should cancel such downloads and start downloading the new images. Image downloader libraries are written to take care of these. 4. **Caching:** The image libraries use both a memory cache and a disk cache to store the downloaded bitmaps. Therefore, they only download new images unless they are not available. 5. **Loading large bitmaps off the UI Thread:** Suppose your app includes large Bitmaps. In order to load them into your view, you must first load them from disk. You need to write code so that loading them do not block the main UI thread. 6. **Loading relevant image sizes:** Your application may run either a new Android device with high screen density or an old device with low screen density. Depending on your target device, you won't need to load a full resolution image if your device does not support such screen density. Usually libraries handle this for you, These are just a few of the boilerplate stuff to consider. Therefore, I highly recommend that you use a good library for the image loading part unless it's so so required!!!
Simply you can use [`java.net.URL`](https://docs.oracle.com/javase/7/docs/api/java/net/URL.html) for loading an image into ImageView like ``` ImageView loadedImage; @override protected Bitmap doInBackground(String... url) { String URL_OF_IMAGE = url[0]; Bitmap bitmap = null; try { InputStream in = new java.net.URL(URL_OF_IMAGE).openStream(); bitmap= BitmapFactory.decodeStream(in); } catch (Exception e) { } return bitmap; } protected void onPostExecute(Bitmap result) { loadedImage.setImageBitmap(result); } ``` But notice that you should have extend `AsyncTask` that should have first parameter as `String` and last as `Bitmap` like ``` private class DowmloadImage extends AsyncTask<String, Void, Bitmap> ```
37,506,172
I am trying to load images from a url and I have used Picasso, however I'd like to know how to do it without an external library if possible. I know I have to get an Asynctask going but I'm not sure how to implement it. This is my getview code ``` @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if(position==0){ NewsObj currNews = news.get(position); DataHandler dh; if(convertView==null){ LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.firstnews,parent,false); dh = new DataHandler(); dh.newsTitle = (TextView)row.findViewById(R.id.newsTitle); dh.newsDate = (TextView)row.findViewById(R.id.newsDate); dh.newsIcon = (ImageView)row.findViewById(R.id.newsIcon); row.setTag(dh); }else{ dh = (DataHandler)row.getTag(); } NewsObj no = (NewsObj)this.getItem(position); new AsyncDownloadTask().execute(row,no.getImgurl()); dh.newsTitle.setText(no.getTitle()); dh.newsDate.setText(no.getDate()); }else{ NewsObj currNews = news.get(position); DataHandler dh; if(convertView==null){ LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.newslist,parent,false); dh = new DataHandler(); dh.newsTitle = (TextView)row.findViewById(R.id.newsTitle); dh.newsDate = (TextView)row.findViewById(R.id.newsDate); dh.newsIcon = (ImageView)row.findViewById(R.id.newsIcon); row.setTag(dh); }else{ dh = (DataHandler)row.getTag(); } NewsObj no = (NewsObj)this.getItem(position); new AsyncDownloadTask().execute(row,no.getImgurl()); dh.newsTitle.setText(no.getTitle()); dh.newsDate.setText(no.getDate()); } return row; } private class AsyncDownloadTask extends AsyncTask<Object, String, Bitmap>{ private View view; private Bitmap bitmap = null; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Bitmap bitmap) { if(bitmap!=null&&view!=null){ ImageView newsIcon = (ImageView)view.getTag(R.id.newsIcon); newsIcon.setImageBitmap(bitmap); } } @Override protected Bitmap doInBackground(Object... params) { view = (View)params[0]; String uri = (String)params[1]; try{ InputStream inputStream = new URL(uri).openStream(); bitmap = BitmapFactory.decodeStream(inputStream); }catch (Exception e){ e.printStackTrace(); } return bitmap; } } ``` This is my async task UPDATE : Encountering null pointer exceptions ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference ```
2016/05/29
[ "https://Stackoverflow.com/questions/37506172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4907861/" ]
You can write your own code. But using a library handles all the boilerplate code which is associated with a library. Unless otherwise, I also recommend that you use a library. Here are some of the boilerplate things that you need to consider when writing your own code. 1. **Memory management:** External libraries take care of making sure the images doesn't take up all of the memory available for your app. Android Bitmaps are very memory conscious to deal with and therefore better to give this part to a library. 2. **Handling activity destruction:** If you rotate your phone while an image download is in progress, it will recreate the activity and then you will need to handle cancellation of the previous requests and start them again. 3. **Cancelling previous requests:** Image libraries are written such that list view items which are no longer visible do not continue downloading. Suppose you scroll down. Then there is no point in downloading the images which are part of the first rows. You should cancel such downloads and start downloading the new images. Image downloader libraries are written to take care of these. 4. **Caching:** The image libraries use both a memory cache and a disk cache to store the downloaded bitmaps. Therefore, they only download new images unless they are not available. 5. **Loading large bitmaps off the UI Thread:** Suppose your app includes large Bitmaps. In order to load them into your view, you must first load them from disk. You need to write code so that loading them do not block the main UI thread. 6. **Loading relevant image sizes:** Your application may run either a new Android device with high screen density or an old device with low screen density. Depending on your target device, you won't need to load a full resolution image if your device does not support such screen density. Usually libraries handle this for you, These are just a few of the boilerplate stuff to consider. Therefore, I highly recommend that you use a good library for the image loading part unless it's so so required!!!
You can Use Network Image View instead of Imageview. It surely makes your life easier. ``` <com.android.volley.toolbox.NetworkImageView android:id="@+id/networkImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="#000000"/> ``` This should be replaced in place of Image view in the required XML File. ``` public ImageLoader getImageLoader() { getRequestQueue(); if (mImageLoader == null) { mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache()); } return this.mImageLoader; } ``` The class above also creates an ImageCache which works with normal volley cache, but only caching images for requests. To Set the Image URL. ``` advImage.setImageUrl("Your Image URL", AppController.getInstance().getImageLoader()); ``` Call the Image Loader Function accordingly. You can also set the defalult placeholder image as well.
38,185,334
I have a REST service on a server A. The service is doing some stuff and logging some messages thanks to log4j. Aside, I have a web page on server B that is calling the service thanks to AJAX and getting the response. Apart from receiving the response (which works fine to me), I would like to print on the page the log messages from the server side. In other words, I would like that every time there is a new log message on server A side, the view display it. Any ideas to achieve that ? **EDIT:** How to use a websocket to retrieve logs from a log4j socket appender?
2016/07/04
[ "https://Stackoverflow.com/questions/38185334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6439357/" ]
You don't need to include OpenCV in .cu file. You need a Caller API with raw pointers and basic data types as parameters. main.cpp ``` #include "opencv2/opencv.hpp" #include "medianFilter.h" int main() { cv::Mat inputMat = cv::imread(); ..... cudaMedianCaller (d_inputMat, d_kernelMat); ..... return 0; } ``` medianFilter.h ``` cudaMedianCaller (uchar3* d_inputMat, uchar* d_kernelMat); ``` medianFilter.cu ``` cudaMedianCaller (uchar3* d_inputMat, uchar* d_kernelMat) { kernelMedianFilter<<< , >>> (uchar3* d_inputMat, uchar* d_kernelMat) } __global__ void kernelMedianFilter (uchar3* d_inputMat, uchar* _kernelMat) { } ```
Despite the other good answer that suggests separation between C++ and CUDA, there is an alternative way to include OpenCV containers in `.cu` files: CMakeLists.txt ``` cmake_minimum_required(VERSION 3.8) project(test LANGUAGES CXX CUDA) find_package(OpenCV 3.0 REQUIRED) # compile the target add_executable(test_app main.cpp medianFilter.cu) target_link_libraries(test_app PRIVATE cudart ${OpenCV_LIBS}) ``` main.cpp ``` #include "opencv2/opencv.hpp" #include "medianFilter.h" int main() { // input data cv::Mat inputMat(cv::Size(128, 128), CV_8UC3, cv::Scalar(100)); cv::Mat kernelMat(cv::Size(16, 16), CV_8UC1, cv::Scalar(1)); // call CUDA cudaMedianCaller(inputMat, kernelMat); return 0; } ``` medianFilter.cu ``` #include "medianFilter.h" __global__ void kernelMedianFilter(uchar3* d_inputMat, uchar* d_kernelMat) { return; } void cudaMedianCaller(const cv::Mat& inputMat, cv::Mat& kernelMat) { // allocate device pointers uchar3 *d_inputMat; uchar *d_kernelMat; cudaMalloc(&d_inputMat, inputMat.total() * sizeof(uchar3)); cudaMalloc(&d_kernelMat, kernelMat.total() * sizeof(uchar)); // copy from host to device cudaMemcpy(d_inputMat, inputMat.ptr<uchar3>(0), inputMat.total() * sizeof(uchar3), cudaMemcpyHostToDevice); cudaMemcpy(d_kernelMat, kernelMat.ptr<uchar>(0), kernelMat.total() * sizeof(uchar), cudaMemcpyHostToDevice); // call CUDA kernel kernelMedianFilter <<<1, 1>>> (d_inputMat, d_kernelMat); // free cudaFree(d_inputMat); cudaFree(d_kernelMat); } ``` medianFilter.h ``` #include "opencv2/opencv.hpp" void cudaMedianCaller (const cv::Mat& inputMat, cv::Mat& kernelMat); ``` For the binary application to run, you may need to copy some of the required `.dll` to the binary folder. For me, I copied `opencv_core343.dll` from `C:\Program Files\OpenCV\x64\vc15\bin` to the folder where `test_app.exe` exists.
66,378,462
**UPDATE** I have printed the page's pathname on to the page and discovered it is not reading past the requests. ``` let path = document.querySelector("#path"); path.innerHTML = "Page pathname is: " + location.pathname; ``` so for link `private.php?folderid=0` the pathname is `private.php` discovering this did disappoint me, but the topic of this question remains the same. **END UPDATE** I am trying to add a class to the parent element if if a link is the current page. My links are structured in the following way: ``` <li role="presentation" class="pane-link pane-folder $navclass[deletedthreads]" nowrap="nowrap"> <a class="smallfont" href="moderation.php?$session[sessionurl]do=viewthreads&amp;type=deleted">$vbphrase[threads]</a> </li> <li role="presentation" class="pane-link pane-folder $navclass[deletedposts]" nowrap="nowrap"> <a class="smallfont" href="moderation.php?$session[sessionurl]do=viewposts&amp;type=deleted">$vbphrase[posts]</a> </li> ``` There are many more but they all share the class `pane-link` The JS is were I am struggling, I am trying to add the class `active` to the `li` element if the current page is the page of the link. The method I was attempting `location.pathname` I discovered would not read my full link. (I believe) This is what I did have (not working) ``` if("a[href*='" + location.pathname + "']") { $("a[href*='" + location.pathname + "']").parent().addClass("active"); } ``` **NOTE** Not all links in my list contain variables like in the example above. Some links are as simple as `private.php?do=newpm` I'm not sure if having the variables in the links are effecting the Javascript location. I want to know, how can I add a class to my `li` if my link is the current page?
2021/02/26
[ "https://Stackoverflow.com/questions/66378462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13388553/" ]
`location.href` : `http://yourwebsite.com/private.php?folderid=0` `location.origin` : `http://yourwebsite.com/` `location.pathname` : `private.php` So to simply get the pathname with params you can use `.replace` ``` <script> var loc = location.href.replace(location.origin , ''); console.log(location); </script> ``` To check for element use `.length` ``` <script> if($(element).length){ } </script> ``` So both code combined should looks like this ``` <script> $(document).ready(function(){ var loc = location.href.replace(location.origin , ''); console.log(loc); if($("a.smallfond[href*='"+loc+"']").length){ $("a.smallfond[href*='"+loc+"']").parent().addClass('active'); } } </script> ``` Note: be sure the jquery library is included
I am using `location.pathname` where I should be using `window.location` replacing just that gave me my desired outcome. My end script became: ``` if("a[href*='" + window.location + "']") { $("a[href*='" + window.location + "']").parent().addClass("active"); } ```
61,936,484
How can I get the content between two substrings? For example in `"Hello, I have a very expensive car"` I want to find the content between `"Hello, I have"` and `"car"`, no matter what it is. How can I find the substring between the two strings?
2020/05/21
[ "https://Stackoverflow.com/questions/61936484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can try this:- ``` s = 'Hello, I have a very expensive car' s = s.split(' ') print(' '.join(s[s.index('have')+1:s.index('car')])) ``` Output:- ``` 'a very expensive' ```
You could just remove the 2 strings in case there is no other text around ``` value = "Hello, I have a very expensive car" res = re.sub("(Hello, I have|car)", "", value).strip() print(res) # a very expensive ```
61,936,484
How can I get the content between two substrings? For example in `"Hello, I have a very expensive car"` I want to find the content between `"Hello, I have"` and `"car"`, no matter what it is. How can I find the substring between the two strings?
2020/05/21
[ "https://Stackoverflow.com/questions/61936484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Regular expressions to the rescue: ``` import re text = "Hello, I have a very expensive car" pattern = re.compile(r'(?P<start>Hello, I have)(?P<middle>.+?)(?P<end>car)') match = pattern.search(text) if match: print(match.group('start')) print(match.group('middle')) print(match.group('end')) ``` Which yields (the spaces are intended): ``` Hello, I have a very expensive car ``` See [**a demo on regex101.com**](https://regex101.com/r/LnM8QZ/1). --- To have a variable text, you could make use of f-strings as in: ``` myVariable = "Hello, I have" pattern = re.compile(rf'(?P<start>{myVariable})(?P<middle>.+?)(?P<end>car)') ```
You can try this:- ``` s = 'Hello, I have a very expensive car' s = s.split(' ') print(' '.join(s[s.index('have')+1:s.index('car')])) ``` Output:- ``` 'a very expensive' ```
61,936,484
How can I get the content between two substrings? For example in `"Hello, I have a very expensive car"` I want to find the content between `"Hello, I have"` and `"car"`, no matter what it is. How can I find the substring between the two strings?
2020/05/21
[ "https://Stackoverflow.com/questions/61936484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Regular expressions to the rescue: ``` import re text = "Hello, I have a very expensive car" pattern = re.compile(r'(?P<start>Hello, I have)(?P<middle>.+?)(?P<end>car)') match = pattern.search(text) if match: print(match.group('start')) print(match.group('middle')) print(match.group('end')) ``` Which yields (the spaces are intended): ``` Hello, I have a very expensive car ``` See [**a demo on regex101.com**](https://regex101.com/r/LnM8QZ/1). --- To have a variable text, you could make use of f-strings as in: ``` myVariable = "Hello, I have" pattern = re.compile(rf'(?P<start>{myVariable})(?P<middle>.+?)(?P<end>car)') ```
You could just remove the 2 strings in case there is no other text around ``` value = "Hello, I have a very expensive car" res = re.sub("(Hello, I have|car)", "", value).strip() print(res) # a very expensive ```
61,936,484
How can I get the content between two substrings? For example in `"Hello, I have a very expensive car"` I want to find the content between `"Hello, I have"` and `"car"`, no matter what it is. How can I find the substring between the two strings?
2020/05/21
[ "https://Stackoverflow.com/questions/61936484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
try 're' module of Python for regular expressions: ``` import re my_string = 'Hello, I have a very expensive car' res = re.search('Hello, I have(.*)car', my_string) print(res.group(1)) ```
You could just remove the 2 strings in case there is no other text around ``` value = "Hello, I have a very expensive car" res = re.sub("(Hello, I have|car)", "", value).strip() print(res) # a very expensive ```
61,936,484
How can I get the content between two substrings? For example in `"Hello, I have a very expensive car"` I want to find the content between `"Hello, I have"` and `"car"`, no matter what it is. How can I find the substring between the two strings?
2020/05/21
[ "https://Stackoverflow.com/questions/61936484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Regular expressions to the rescue: ``` import re text = "Hello, I have a very expensive car" pattern = re.compile(r'(?P<start>Hello, I have)(?P<middle>.+?)(?P<end>car)') match = pattern.search(text) if match: print(match.group('start')) print(match.group('middle')) print(match.group('end')) ``` Which yields (the spaces are intended): ``` Hello, I have a very expensive car ``` See [**a demo on regex101.com**](https://regex101.com/r/LnM8QZ/1). --- To have a variable text, you could make use of f-strings as in: ``` myVariable = "Hello, I have" pattern = re.compile(rf'(?P<start>{myVariable})(?P<middle>.+?)(?P<end>car)') ```
try 're' module of Python for regular expressions: ``` import re my_string = 'Hello, I have a very expensive car' res = re.search('Hello, I have(.*)car', my_string) print(res.group(1)) ```
366,614
I have been able to figure out the the distinct equivalence classes. Now I am having difficulties proving the relation IS an equivalence relation. $F$ is the relation defined on $\Bbb Z$ as follows: > > For all $(m, n) \in \Bbb Z^2,\ m F n \iff 4 | (m-n)$ > > > equivalence classes: $\{-8,-4,0,4,8\}, \{-7,-3,1,5,9\} \{-6,-2,2,6,10\}$ and $\{-5, -1, 3, 7, 11\}$
2013/04/19
[ "https://math.stackexchange.com/questions/366614", "https://math.stackexchange.com", "https://math.stackexchange.com/users/72287/" ]
The partition of a set into its equivalence classes *determines* an equivalence relation defined on a set. That is, *equivalence classes partition a set* $\iff \exists$ an equivalence relation determining the partition. In this case, you found the classes (or rather, representatives of those classes)...and hence, the given relation you used which determine those classes must be an equivalence relation. You can easily confirm that the relation is, indeed, reflexive, symmetric, and transitive on the set of integers: * reflexive: For all $m \in \mathbb Z$, we have $m\,F\,m $ since $4\mid (m - m) = 0$ * symmetric: For all $m, n \in \mathbb Z$, if $m\,F\,n$ then $4\mid (m-n) \iff 4 \mid (n - m) \iff n\,F\,m$. * transitive: For $m, n, p \in \mathbb Z$, if $4\mid(m-n)$ and $4\mid(n-p)$ then $4\mid \left((m-n)+(n-p)\right)\iff 4\mid (m-p)$ Your stated equivalence classes are good for integers in $[-8, 11]$ but you want to represent these classes so they encompass ALL integers, and indeed the equivalence classes as represented below ***partition*** the integers: every integer belongs to one and only one equivalence class. Your *relation* defines *congruence modulo* $4$ on the set of integers: > > Two integers $m, n$ are congruent modulo $4$ if and only if $4\mid (m - n) \iff m \equiv n \pmod 4$. > > > Congruence modulo $4$ is indeed an equivalence relation. Indeed, the ***[congruence classes](http://en.wikipedia.org/wiki/Modular_arithmetic#Congruence_classes)*** corresponding to your given equivalence relation *are* the equivalence classes determined by your equivalence relation, and they which are sometimes called the residue classes $\pmod 4$: Class $[0] = \{4k\mid k \in \mathbb Z\}$ Class $[1] = \{4k + 1 \mid k \in \mathbb Z\}$ Class $[2] = \{4k + 2\mid k \in \mathbb Z\}$ Class $[3] = \{4k + 3 \mid k \in \mathbb Z\}$.
1) reflexivity: $mFm $ since $4|0$ 2) simmetry: $mFn \Rightarrow nFm$ since $4|\pm (m-n)$ 3) transitivity: if $4|(m-n)$ and $4|(n-r)$ then $4|\big((m-n)+(n-r)\big)$ or $4|(m-r)$
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
From your edit, it sounds like you are just trying to sum the *values* of all the sub-dicts, by the parent dict: ``` In [9]: counts = Counter() In [10]: for dd in data: ...: for k,v in dd.items(): ...: counts[k] += sum(v.values()) ...: In [11]: counts Out[11]: Counter({'25-34': 30, '45-54': 12}) ``` Fundamentally, this is an unwieldy data-structure. OK, given your last update, I think the easiest thing would be to go with a `defaultdict` with a `Counter` factory: ``` In [17]: from collections import Counter, defaultdict In [18]: counts = defaultdict(Counter) In [19]: for dd in data: ...: for k, d in dd.items(): ...: counts[k].update(d) ...: In [20]: counts Out[20]: defaultdict(collections.Counter, {'25-34': Counter({'Clicks': 30, 'Visits': 4}), '45-54': Counter({'Clicks': 12, 'Visits': 6})}) ```
I would use [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) with default of `int`(which is 0): ``` from collections import defaultdict counter = defaultdict(int) for current_dict in data: for key, value in current_dict.items(): counter[key] += sum(value.values()) ``` This is the most readable way to count the values in my opinion.
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
I would use [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) with default of `int`(which is 0): ``` from collections import defaultdict counter = defaultdict(int) for current_dict in data: for key, value in current_dict.items(): counter[key] += sum(value.values()) ``` This is the most readable way to count the values in my opinion.
For your first questions, here's a one-liner. It's not really pretty but it does use `Counter`: ``` sum((Counter({k:v['Clicks'] for k,v in d.items()}) for d in data), Counter()) ``` As an example : ``` data = [ { "25-34": { "Clicks": 10 }, "45-54": { "Clicks": 2 }, }, { "25-34": { "Clicks": 20 }, "45-54": { "Clicks": 10 }, } ] from collections import Counter c = sum((Counter({k:v['Clicks'] for k,v in d.items()}) for d in data), Counter()) print(c) ``` It outputs: ``` Counter({'25-34': 30, '45-54': 12}) ```
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
I would use [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) with default of `int`(which is 0): ``` from collections import defaultdict counter = defaultdict(int) for current_dict in data: for key, value in current_dict.items(): counter[key] += sum(value.values()) ``` This is the most readable way to count the values in my opinion.
I did like this: ``` with gzip.open("data/small_fasta.fa.gz", "rt") as handle: aac_count = defaultdict(Counter) for record in SeqIO.parse(handle, "fasta"): aac_count[record.id].update(record.seq) ``` I used biopython for open the fasta file (<https://pt.wikipedia.org/wiki/Formato_FASTA>) that are the type of file I use a lot. It has a header('>proteinx' and in the next line a sequence (string of dna or proteins). And biopython is one easy way to deal with fasta files. Then I used defaultdic and Counter for collections. Record.id is the header and is the key and I update the counter with the sequence for count the number of given character inside the strings. The output is somenthing like this in my case: ``` defaultdict(collections.Counter, {'UniRef100_Q6GZX4': Counter({'M': 6, 'A': 13, 'F': 8, 'S': 13, 'E': 15, 'D': 17, 'V': 21, 'L': 25, 'K': 29, 'Y': 14, 'R': 15, 'P': 11, 'N': 8, 'W': 4, 'Q': 9, 'C': 4, 'G': 15, 'I': 12, 'H': 9, 'T': 8}), 'UniRef100_Q6GZX3': Counter({'M': 7, 'S': 22, 'I': 10, 'G': 23, 'A': 26, 'T': 26, 'R': 16, 'L': 14, 'Q': 13, 'N': 9, 'D': 24, 'K': 17, 'Y': 11, 'P': 37, 'C': 18, 'F': 9, 'W': 6, 'E': 6, 'V': 23, 'H': 3}),...} ```
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
From your edit, it sounds like you are just trying to sum the *values* of all the sub-dicts, by the parent dict: ``` In [9]: counts = Counter() In [10]: for dd in data: ...: for k,v in dd.items(): ...: counts[k] += sum(v.values()) ...: In [11]: counts Out[11]: Counter({'25-34': 30, '45-54': 12}) ``` Fundamentally, this is an unwieldy data-structure. OK, given your last update, I think the easiest thing would be to go with a `defaultdict` with a `Counter` factory: ``` In [17]: from collections import Counter, defaultdict In [18]: counts = defaultdict(Counter) In [19]: for dd in data: ...: for k, d in dd.items(): ...: counts[k].update(d) ...: In [20]: counts Out[20]: defaultdict(collections.Counter, {'25-34': Counter({'Clicks': 30, 'Visits': 4}), '45-54': Counter({'Clicks': 12, 'Visits': 6})}) ```
For your first questions, here's a one-liner. It's not really pretty but it does use `Counter`: ``` sum((Counter({k:v['Clicks'] for k,v in d.items()}) for d in data), Counter()) ``` As an example : ``` data = [ { "25-34": { "Clicks": 10 }, "45-54": { "Clicks": 2 }, }, { "25-34": { "Clicks": 20 }, "45-54": { "Clicks": 10 }, } ] from collections import Counter c = sum((Counter({k:v['Clicks'] for k,v in d.items()}) for d in data), Counter()) print(c) ``` It outputs: ``` Counter({'25-34': 30, '45-54': 12}) ```
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
From your edit, it sounds like you are just trying to sum the *values* of all the sub-dicts, by the parent dict: ``` In [9]: counts = Counter() In [10]: for dd in data: ...: for k,v in dd.items(): ...: counts[k] += sum(v.values()) ...: In [11]: counts Out[11]: Counter({'25-34': 30, '45-54': 12}) ``` Fundamentally, this is an unwieldy data-structure. OK, given your last update, I think the easiest thing would be to go with a `defaultdict` with a `Counter` factory: ``` In [17]: from collections import Counter, defaultdict In [18]: counts = defaultdict(Counter) In [19]: for dd in data: ...: for k, d in dd.items(): ...: counts[k].update(d) ...: In [20]: counts Out[20]: defaultdict(collections.Counter, {'25-34': Counter({'Clicks': 30, 'Visits': 4}), '45-54': Counter({'Clicks': 12, 'Visits': 6})}) ```
My variation without list comprehensions: ``` def my_dict_sum(data): """ >>> test_data = [{"25-34": {"Clicks": 10, "Visits": 1}, "45-54": {"Clicks": 2, "Visits": 2}, },{"25-34": {"Clicks": 20, "Visits": 3}, "45-54": {"Clicks": 10, "Visits": 4}, }] >>> my_dict_sum(test_data) {'45-54': {'Clicks': 12, 'Visits': 6}, '25-34': {'Clicks': 30, 'Visits': 4}} """ result_key = data[0] for x in data[1:]: for y in x: if y in result_key: for z in x[y]: if z in result_key[y]: result_key[y][z] = result_key[y][z] + x[y][z] return result_key ```
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
From your edit, it sounds like you are just trying to sum the *values* of all the sub-dicts, by the parent dict: ``` In [9]: counts = Counter() In [10]: for dd in data: ...: for k,v in dd.items(): ...: counts[k] += sum(v.values()) ...: In [11]: counts Out[11]: Counter({'25-34': 30, '45-54': 12}) ``` Fundamentally, this is an unwieldy data-structure. OK, given your last update, I think the easiest thing would be to go with a `defaultdict` with a `Counter` factory: ``` In [17]: from collections import Counter, defaultdict In [18]: counts = defaultdict(Counter) In [19]: for dd in data: ...: for k, d in dd.items(): ...: counts[k].update(d) ...: In [20]: counts Out[20]: defaultdict(collections.Counter, {'25-34': Counter({'Clicks': 30, 'Visits': 4}), '45-54': Counter({'Clicks': 12, 'Visits': 6})}) ```
I did like this: ``` with gzip.open("data/small_fasta.fa.gz", "rt") as handle: aac_count = defaultdict(Counter) for record in SeqIO.parse(handle, "fasta"): aac_count[record.id].update(record.seq) ``` I used biopython for open the fasta file (<https://pt.wikipedia.org/wiki/Formato_FASTA>) that are the type of file I use a lot. It has a header('>proteinx' and in the next line a sequence (string of dna or proteins). And biopython is one easy way to deal with fasta files. Then I used defaultdic and Counter for collections. Record.id is the header and is the key and I update the counter with the sequence for count the number of given character inside the strings. The output is somenthing like this in my case: ``` defaultdict(collections.Counter, {'UniRef100_Q6GZX4': Counter({'M': 6, 'A': 13, 'F': 8, 'S': 13, 'E': 15, 'D': 17, 'V': 21, 'L': 25, 'K': 29, 'Y': 14, 'R': 15, 'P': 11, 'N': 8, 'W': 4, 'Q': 9, 'C': 4, 'G': 15, 'I': 12, 'H': 9, 'T': 8}), 'UniRef100_Q6GZX3': Counter({'M': 7, 'S': 22, 'I': 10, 'G': 23, 'A': 26, 'T': 26, 'R': 16, 'L': 14, 'Q': 13, 'N': 9, 'D': 24, 'K': 17, 'Y': 11, 'P': 37, 'C': 18, 'F': 9, 'W': 6, 'E': 6, 'V': 23, 'H': 3}),...} ```
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
My variation without list comprehensions: ``` def my_dict_sum(data): """ >>> test_data = [{"25-34": {"Clicks": 10, "Visits": 1}, "45-54": {"Clicks": 2, "Visits": 2}, },{"25-34": {"Clicks": 20, "Visits": 3}, "45-54": {"Clicks": 10, "Visits": 4}, }] >>> my_dict_sum(test_data) {'45-54': {'Clicks': 12, 'Visits': 6}, '25-34': {'Clicks': 30, 'Visits': 4}} """ result_key = data[0] for x in data[1:]: for y in x: if y in result_key: for z in x[y]: if z in result_key[y]: result_key[y][z] = result_key[y][z] + x[y][z] return result_key ```
For your first questions, here's a one-liner. It's not really pretty but it does use `Counter`: ``` sum((Counter({k:v['Clicks'] for k,v in d.items()}) for d in data), Counter()) ``` As an example : ``` data = [ { "25-34": { "Clicks": 10 }, "45-54": { "Clicks": 2 }, }, { "25-34": { "Clicks": 20 }, "45-54": { "Clicks": 10 }, } ] from collections import Counter c = sum((Counter({k:v['Clicks'] for k,v in d.items()}) for d in data), Counter()) print(c) ``` It outputs: ``` Counter({'25-34': 30, '45-54': 12}) ```
46,233,259
Is it ok to use additional url query params to prevent cahing or force update css/js? ``` /style.css?v=1 ``` Or it will be better to change name of file/dir? ``` /style.1.css ``` I heard this something affects the ability of proxy servers to download styles/scripts.
2017/09/15
[ "https://Stackoverflow.com/questions/46233259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7504461/" ]
My variation without list comprehensions: ``` def my_dict_sum(data): """ >>> test_data = [{"25-34": {"Clicks": 10, "Visits": 1}, "45-54": {"Clicks": 2, "Visits": 2}, },{"25-34": {"Clicks": 20, "Visits": 3}, "45-54": {"Clicks": 10, "Visits": 4}, }] >>> my_dict_sum(test_data) {'45-54': {'Clicks': 12, 'Visits': 6}, '25-34': {'Clicks': 30, 'Visits': 4}} """ result_key = data[0] for x in data[1:]: for y in x: if y in result_key: for z in x[y]: if z in result_key[y]: result_key[y][z] = result_key[y][z] + x[y][z] return result_key ```
I did like this: ``` with gzip.open("data/small_fasta.fa.gz", "rt") as handle: aac_count = defaultdict(Counter) for record in SeqIO.parse(handle, "fasta"): aac_count[record.id].update(record.seq) ``` I used biopython for open the fasta file (<https://pt.wikipedia.org/wiki/Formato_FASTA>) that are the type of file I use a lot. It has a header('>proteinx' and in the next line a sequence (string of dna or proteins). And biopython is one easy way to deal with fasta files. Then I used defaultdic and Counter for collections. Record.id is the header and is the key and I update the counter with the sequence for count the number of given character inside the strings. The output is somenthing like this in my case: ``` defaultdict(collections.Counter, {'UniRef100_Q6GZX4': Counter({'M': 6, 'A': 13, 'F': 8, 'S': 13, 'E': 15, 'D': 17, 'V': 21, 'L': 25, 'K': 29, 'Y': 14, 'R': 15, 'P': 11, 'N': 8, 'W': 4, 'Q': 9, 'C': 4, 'G': 15, 'I': 12, 'H': 9, 'T': 8}), 'UniRef100_Q6GZX3': Counter({'M': 7, 'S': 22, 'I': 10, 'G': 23, 'A': 26, 'T': 26, 'R': 16, 'L': 14, 'Q': 13, 'N': 9, 'D': 24, 'K': 17, 'Y': 11, 'P': 37, 'C': 18, 'F': 9, 'W': 6, 'E': 6, 'V': 23, 'H': 3}),...} ```
49,701,730
I want to run official example (<http://propelml.org/>), but browser console warns: > > `plot: no output handler.` > > > ``` <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello, propel!</title> <script src="https://unpkg.com/propel@3.3.1"></script> </head> <body> <script> const { grad, linspace, plot } = propel; f = x => x.tanh(); x = linspace(-4, 4, 200); plot(x, f(x), x, grad(f)(x), x, grad(grad(f))(x), x, grad(grad(grad(f)))(x), x, grad(grad(grad(grad(f))))(x)); </script> </body> </html> ``` What is output handler?
2018/04/06
[ "https://Stackoverflow.com/questions/49701730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9325131/" ]
Remove the blank line before `<?php` at the beginning of the `check_address.php` script.
``` jQuery.ajax({ url :url, type : 'post', data : data, success : function (data) { // location.reload(); if (data != 'passed') { jQuery('#payment_errors').html(data); } if (data == 'passed') { // alert('passed'); //clear errors jQuery('#payment_errors').html(""); jQuery('#step1').css("display","none"); jQuery('#step2').css("display","block"); jQuery('#next_button').css("display","none"); jQuery('#back_button').css("display","inline-block"); jQuery('#check_out_button').css("display","inline-block"); } }, error : function () { alert("Something wrong with the child options."); } }); ```
14,121,150
I have two different applications deployed in Tomcat server. The purpose of one application is to call another application which processes data using rule engines. Basically, it calls a static method of another application through reflection. This works perfectly fine in Jboss. But now for some reason, I need to deploy same applications on Tomcat. And here it fails. It seems that one application classes are not able to find another application classes. Doesn't Tomcat supports reflection? Or reflection is not possible between different applications? Thanks, Nipun
2013/01/02
[ "https://Stackoverflow.com/questions/14121150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942669/" ]
I think you're relying on the classloading structure of each app server. The classloader structure/hierarchy is configurable, but generally the 2 apps will occupy different classloaders, and using reflection across classloaders could well be problematic. Why are you using reflection to communicate between these apps ? This doesn't sound practical or, indeed, suitable. You have 2 web apps, so why not communicate using their HTTP API ? If you can/don't want to do this, I would investigate other solutions, such as RMI.
I doubt the cause of this problem is reflection, but the [classloader hierarchy](http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html). One webapp should **not** call methods of another, this is a major design flaw.
42,169,488
This is my first Stack Overflow question so please bear with me. I have read [this](https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver/41904453#41904453) SO question, which lead me to wondering, is it possible to make chromedriver completely undetectable? For my own curiosity's sake I have tested the method described and found that it was unsuccessful in creating a completely anonymous browser. I read through the driver's documentation and found this: > > `partial interface Navigator { > readonly attribute boolean webdriver; > };` > > > The webdriver IDL attribute of the Navigator interface must return the value of the webdriver-active flag, which is initially false. > > > This property allows websites to determine that the user agent is under control by WebDriver, and can be used to help mitigate denial-of-service attacks. > > > However, I cannot find where these tags are even located through the browser console or in the source code. I would imagine this is responsible for the detection of chromedriver, however, after combing through the source code, I could not find this interface. As a result, it has left me wondering whether or not this feature is included in the current chromedriver. If not, I still know that the current chromedriver is detectable by websites and other services such as [distill](https://www.distilnetworks.com/).
2017/02/10
[ "https://Stackoverflow.com/questions/42169488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7003958/" ]
In order to use ChromeDriver undetectable to Distil checkpoints (which are described nicely in this [stackoverflow post](https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver)), you will need to ensure that your browser does not contain any variable in its window or document prototypes that reveal that you are using a webdriver, as the one you mention. You can use software as Selenium along with ChromeDriver and Chrome as long as you take some precautions and make some fixes to the binaries. This method will apply only to headed version, if you wish to use headless, you would need to take additional measurements to pass window/rendering tests, [described here](https://intoli.com/blog/making-chrome-headless-undetectable/). --- **1. Fix Chrome binary, or use an old version** First, lets deal with that `navigator.webdriver` set to True. This is defined by W3C protocol [here](https://www.w3.org/TR/webdriver/#dom-navigatorautomationinformation) as part of 'NavigatorAutomationInformation' of browsers, which extends the Navigator interface. How to remove it? That project has a lot of files, third party stuff, blink web runtimes, etc. So, instead of becoming crazy trying to figure out how this works, as Chromium is open-source, just be clever and search google for the commit which incorporated that. [Here is the link](https://chromium-review.googlesource.com/c/chromium/src/+/665978). Pay attention to these files: * `third_party/WebKit/Source/core/frame/Navigator.h`, which holds the line of code: ``` `bool webdriver() const { return true; }` This method is supossed to always return true, as you can see. ``` * `third_party/WebKit/Source/core/frame/Navigator.idl`, which contains the extensions of Navigators, included our ``` `Navigator implements NavigatorAutomationInformation;` which is being commited. Interesting, isn't it? ``` * `third_party/WebKit/Source/core/frame/NavigatorAutomationInformation.idl` contains the extension itself, with a read-only variable, which is `webdriver`: ``` `[ NoInterfaceObject, // Always used on target of 'implements' Exposed=(Window), RuntimeEnabled=AutomationControlled ] interface NavigatorAutomationInformation { readonly attribute boolean webdriver; };` ``` To get rid of this functionality, it should be enough commenting the line in `Navigator.idl` which extends `Navigator` with this functionality, and compile the source ([compiling in linux here](https://chromium.googlesource.com/chromium/src/+/lkcr/docs/linux_build_instructions.md)). However, this is a laborious task for almost any computer and can take several hours. If you look the date of the commit, it was on **Oct 2017**, so an option is to download **any version of Chrome released before that date**. To search for mirrors, you can google for `inurl:/deb/pool/main/g/google-chrome-stable/`. --- **2. Fix ChromeDriver** Distil checks the regex rule '/\$[a-z]dc\_/' against window variables, and ChromeDriver adds one as mentioned [here](https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver) which satisfies that condition. As they mention, you have to edit `call_function.js` amongst the source code, and redefine the variable `var key = '$cdc_asdjflasutopfhvcZLmcfl_';`. with something else. Also, probably easier, you can use an hex editor to update the existing binary. If you decided to use an older version of Chrome -I guess you did-, you will need to use an appropiate version of ChromeDriver. You can know which one is fine for your Chrome version in the [ChromeDriver downloads webpage](http://chromedriver.chromium.org/downloads). For example, for Chrome v61 (which fits your needs), you could use [ChromeDriver 2.34](https://chromedriver.storage.googleapis.com/index.html?path=2.34/). Once done, just put the ChromeDriver binary on '/usr/bin/local'. --- **3. Take other precautions** * Pay attention to your user-agent. * Don't perform too many repeated requests. * Use a (random) delay between requests. * Use the Chrome arguments used [here](https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver) to mimic a normal user profile.
You can't use Selenium's WebDriver itself to change UserAgent, which sounds like what you're really trying to do here. However, that doesn't mean it can't be changed. *Enter PhantomJS.* Check out [this answer](https://stackoverflow.com/a/41678604/2172566). You can use that to disguise Selenium as a different browser, or pretty much anything else. Of course, if a website is determined to figure you out, there are plenty of clues that Selenium leaves behind (like clicking with perfect precision).
22,630,864
I have n number of text box (n may be any number) with same name. And I want to access the value of all the text box of that name. Ex-: ``` <form method="post" id="create"> <input type="text" name="user[]" /> <input type="text" name="user[]" /> <input type="text" name="user[]" /> <input type="button" id="newFieldBtn"/> <input type="submit" name="save" value="save"/> </form> ``` jQuery ``` <script> jQuery(document).ready(function($) { $('#newFieldBtn').click(function(){ var code='<input type="text" name="user[]" />'; jQuery('#create').append(code); </script> ``` or is there any other way to access the value of the text box. Either by class or any other property..
2014/03/25
[ "https://Stackoverflow.com/questions/22630864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2428406/" ]
``` <script> jQuery(document).ready(function($) { $('#newFieldBtn').click(function(){ var count = document.getElementById('count').value; count++; var code = '<input type="text" name="user'+count+'" />'; jQuery('#create').append(code); document.getElementById('count').value = count; </script> ``` and your html like... ``` <form method="post" id="create"> <input type="hidden" id="count" value="0" name="count"> <input type="button" id="newFieldBtn"/> <input type="submit" name="save" value="save"/> </form> ``` and in your php code... ``` <?php if(isset($_POST)) { $count = $_POST['count']; for($i=1;$i<=$count;$i++) { $user.$i = $_POST['user'.$i]; } } ?> ```
Try this one, it will show you the values : ``` <form action="#" method="post"> <input type="text" name="user[]" /> <input type="text" name="user[]" /> <input type="text" name="user[]" /> <input type="submit" value="submit" > </form> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { foreach($_POST['user'] as $key => $value) { echo $key." has the value = ". $value."<br>"; } } ?> ``` See this in action: <http://wistudat.be/try/array.php>
38,019,530
I'm new to coding so sorry if this seems like an obvious question. When using bootstrap 1) can I have more than 1 container? if so how do I go about styling them separately if they both have to be called container ? Thanks!
2016/06/24
[ "https://Stackoverflow.com/questions/38019530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6509775/" ]
Yes, you can have as many `container` or `container-fluid` as needed. Add a custom CSS class to the containers to stylize.. ``` <div class="container-fluid">...</div> <div class="container-fluid someclass">...</div> .someclass { background-color:#eee; } ``` <http://www.codeply.com/go/8vDhaX4kKV>
The Bootstrap website says this > > Easily center a page's contents by wrapping its contents in a .container. Containers set width at various media query breakpoints to match our grid system. > > > Note that, due to padding and fixed widths, containers are not nestable by default. > > > You can have multiple containers, but you should not nest them. Now assuming you do have more than one, there are multiple ways you could style them. 1. You could assign an id to a container like so `<div class="container" id="container1">`. You can then reference this with the id selector (`#container1`) 2. You could use pseudoselectors. `.container:first-of-type`, `.container:nth-child(3)` etc
57,118,151
I have an optimization problem modelled and written in IBM ILOG CPLEX Optimization Studio. I want to call .mod and .dat from Java. I found some example to do it. However, I got some error. My code is shown below. I also added all cplex and opl library ``` package cplexJava; import ilog.concert.*; import ilog.cplex.*; import ilog.opl.*; public class main { public static void main(String[] args) { // TODO Auto-generated method stub model(); } public static void model() { int status = 127; IloOplFactory.setDebugMode(true); IloOplFactory oplF = new IloOplFactory(); IloOplErrorHandler errHandler = oplF.createOplErrorHandler(); IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod"); IloOplSettings settings = oplF.createOplSettings(errHandler); IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings); IloCplex cplex = oplF.createCplex(); cplex.setOut(null); IloOplModel opl = oplF.createOplModel(def, cplex); IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat"); opl.addDataSource(dataSource); opl.generate(); if (cplex.solve()) { System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue()); opl.postProcess(); opl.printSolution(System.out); } else { System.out.println("No solution!"); } oplF.end(); status = 0; System.exit(status); } } ``` In my code, the errors came from from `oplF.createCplex()` and `cplex.solve()`. When I tried to run it, this is the error I got. [![enter image description here](https://i.stack.imgur.com/6faMe.png)](https://i.stack.imgur.com/6faMe.png) I could not figure out why I got the errors from `oplF.createCplex()` and `cplex.solve()` although I already added the `cplex` and `opl` library
2019/07/19
[ "https://Stackoverflow.com/questions/57118151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947626/" ]
Actually your IDE tells you what the problem is: There are possible IloExceptions thrown and you do not handle them. You need to either surround your code with a try catch block, or your main-method should have a "throws IloException" in the signature: ``` package cplexJava; import ilog.concert.*; import ilog.cplex.*; import ilog.opl.*; public class main { public static void main(String[] args) { // TODO Auto-generated method stub model(); } public static void model() { int status = 127; try { IloOplFactory.setDebugMode(true); IloOplFactory oplF = new IloOplFactory(); IloOplErrorHandler errHandler = oplF.createOplErrorHandler(); IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod"); IloOplSettings settings = oplF.createOplSettings(errHandler); IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings); IloCplex cplex = oplF.createCplex(); cplex.setOut(null); IloOplModel opl = oplF.createOplModel(def, cplex); IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat"); opl.addDataSource(dataSource); opl.generate(); if (cplex.solve()) { System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue()); opl.postProcess(); opl.printSolution(System.out); } else { System.out.println("No solution!"); } oplF.end(); } catch (IloException ilx) { // log error message or something like that } status = 0; System.exit(status); } } ``` And please use class names with upper case first letter and package names with all lower case.
For the OPL Java API, you should only need [oplall.jar](https://www.ibm.com/support/knowledgecenter/SSSA5P_12.9.0/ilog.odms.ide.help/OPL_Studio/usroplinterfaces/topics/opl_interf_intro_java_deploy.html). **SETUP** On my x86-64 Linux machine with Eclipse 3.6, this is done, like so (hopefully it's similar for you): 1. Right click on your Java Project and select Properties 2. Select "Java Build Path" on the left and the Libraries tab on the right 3. Click on the "Add External JARs..." button and select `COS_INSTALL_DIR/opl/lib/oplall.jar` (where `COS_INSTALL_DIR` is the location where you installed CPLEX Optimization Studio) 4. Click OK One more thing to do is make sure that your `LD_LIBRARY_PATH` environment variable is set to `COS_INSTALL_DIR/opl/bin/x86-64_linux`. (**NOTE**: On Windows, I think you should set the `PATH` environment variable instead.) You can set this in Eclipse, like so: 1. Select "Run > Run Configurations..." in the menu 2. On the left, select your java application 3. On the right, select the Environment tab and click on the "New..." button 4. Enter `LD_LIBRARY_PATH` in the Name field (try `PATH` on Windows) 5. Enter `COS_INSTALL_DIR/opl/bin/x86-64_linux` in the Value field (again, where `COS_INSTALL_DIR` is the location where you installed CPLEX Optimization Studio) 6. Click OK **FIX COMPILER ERRORS** Once you have that set up, you'll probably notice that you are still getting compiler errors (the little red squiggle lines indicate this). Hover your mouse over the those and you'll be presented with a list of quick fixes: 1) add throws declaration; 2) Surround with try/catch. Pick one of those to fix the issue. After all of the red squiggly lines are gone you should be able to run your program. If you're not familiar with fixing compiler errors in Eclipse, maybe [this](https://courses.cs.washington.edu/courses/cse143/15wi/eclipse_tutorial/compiling.shtml) Eclipse tutorial with help. Sometimes you have to select "Project > Clean" to force a recompile.
57,118,151
I have an optimization problem modelled and written in IBM ILOG CPLEX Optimization Studio. I want to call .mod and .dat from Java. I found some example to do it. However, I got some error. My code is shown below. I also added all cplex and opl library ``` package cplexJava; import ilog.concert.*; import ilog.cplex.*; import ilog.opl.*; public class main { public static void main(String[] args) { // TODO Auto-generated method stub model(); } public static void model() { int status = 127; IloOplFactory.setDebugMode(true); IloOplFactory oplF = new IloOplFactory(); IloOplErrorHandler errHandler = oplF.createOplErrorHandler(); IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod"); IloOplSettings settings = oplF.createOplSettings(errHandler); IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings); IloCplex cplex = oplF.createCplex(); cplex.setOut(null); IloOplModel opl = oplF.createOplModel(def, cplex); IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat"); opl.addDataSource(dataSource); opl.generate(); if (cplex.solve()) { System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue()); opl.postProcess(); opl.printSolution(System.out); } else { System.out.println("No solution!"); } oplF.end(); status = 0; System.exit(status); } } ``` In my code, the errors came from from `oplF.createCplex()` and `cplex.solve()`. When I tried to run it, this is the error I got. [![enter image description here](https://i.stack.imgur.com/6faMe.png)](https://i.stack.imgur.com/6faMe.png) I could not figure out why I got the errors from `oplF.createCplex()` and `cplex.solve()` although I already added the `cplex` and `opl` library
2019/07/19
[ "https://Stackoverflow.com/questions/57118151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947626/" ]
Actually your IDE tells you what the problem is: There are possible IloExceptions thrown and you do not handle them. You need to either surround your code with a try catch block, or your main-method should have a "throws IloException" in the signature: ``` package cplexJava; import ilog.concert.*; import ilog.cplex.*; import ilog.opl.*; public class main { public static void main(String[] args) { // TODO Auto-generated method stub model(); } public static void model() { int status = 127; try { IloOplFactory.setDebugMode(true); IloOplFactory oplF = new IloOplFactory(); IloOplErrorHandler errHandler = oplF.createOplErrorHandler(); IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod"); IloOplSettings settings = oplF.createOplSettings(errHandler); IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings); IloCplex cplex = oplF.createCplex(); cplex.setOut(null); IloOplModel opl = oplF.createOplModel(def, cplex); IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat"); opl.addDataSource(dataSource); opl.generate(); if (cplex.solve()) { System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue()); opl.postProcess(); opl.printSolution(System.out); } else { System.out.println("No solution!"); } oplF.end(); } catch (IloException ilx) { // log error message or something like that } status = 0; System.exit(status); } } ``` And please use class names with upper case first letter and package names with all lower case.
I also faced the the same problem. After some trial and error I realized that the correct name is `DYLD_LIBRARY_PATH` for macos. [Referral link](https://www.ibm.com/support/knowledgecenter/SSSA5P_12.8.0/ilog.odms.ide.help/OPL_Studio/working_environment/topics/opl_working_env_variables_unix.html)
29,932,896
Hi I have been trying to add a button into my program that when you click the button it displays text in a label, waits so the user can read it, then exits the program. but if I run it and try it it only waits then exits without displaying text. sorry if that was a bad explanation I just got into coding. This is what I have. ``` private void button3_Click(object sender, EventArgs e) { label1.Text = "Text Here"; Thread.Sleep(500); this.Close(); } ```
2015/04/29
[ "https://Stackoverflow.com/questions/29932896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844345/" ]
Call `label1.Invalidate()` to force the control to be redrawn. When you call `Thread.Sleep`, the UI thread will be blocked and not update. If this doesn't work, try `label1.Refresh()` or `Application.DoEvents();` ``` private void button3_Click(object sender, EventArgs e) { label1.Text = "Text Here"; label1.Invalidate(); Thread.Sleep(500); this.Close(); } ``` A more ideal solution would be to use a timer, another thread, or some kind of async event to run the code separately from your UI: ``` timer = new Timer(); timer.Interval = 500; timer.Tick += (sender, e) => Close(); timer.Start(); ``` or ``` new Thread(delegate() { Thread.Sleep(500); this.Close(); }).Start(); ``` Also note that 500 milliseconds is a pretty short time, did you mean 5000 milliseconds, which is equivalent to 5 seconds? You may want to also take a look at [Winforms: Application.Exit vs Enviroment.Exit vs Form.Close](https://stackoverflow.com/q/13046019/1218281), as `Close()` *closes* the *current* window.
Instead of using `Thread.Sleep` which blocks the UI thread (and keeps it from updating with your text), its better to keep the UI responsive. This will keep the UI working and delay then close the application. ``` private void button3_Click(object sender, EventArgs e) { label1.Text = "Text Here"; Task.Delay(5000).ContinueWith((arg) => Application.Exit()); } ``` The `Task` is run in another thread, delays for the specified milliseconds (5000 or 5 seconds in this case) then continues with a call to close the application. By the way, `this.Close()` works to close the application only if the form you are running it from is the "initial" form of the application. If you ran the same code from another child form, it would only close the form. The better thing to do if you want to actually close the application is to use the `Application.Close()` method. This gracefully closes the application. If you want to down-right terminate, you can use `Environment.Exit(int)`.
49,770,331
I'm building a Shiny App in R and I'm trying to scrub off the web information about the user's selected Pokemon, but I keep running into the problem of 'Error: SLL certificate problem' when trying to use read\_html() ui: ```html sidebarPanel( ui <- fluidPage( selectInput(inputId = "pokemon1", 'Choose a Pokémon:', c(Pokemon$Name)))), mainPanel( verbatimTextOutput("value")) ``` And then the Server: ```html server <- function(input, output) { output$value <- renderPrint({ pokemon <- input$pokemon1 URLpokemon <- paste(c("https://bulbapedia.bulbagarden.net/wiki/", pokemon,"_(Pok%C3%A9mon)"), collapse="") # Read and parse HTML file pokemonSummary1 <- URLpokemon%>% read_html() %>% # R please help me read this HTML code html_nodes("p")%>% # type of HTML object .[[1]]%>% html_text() pokemonSummary2 <- URLpokemon%>% read_html() %>% # R please help me read this HTML code html_nodes("p")%>% # type of HTML object .[[2]]%>% html_text() pokemonSummary3 <- URLpokemon%>% read_html() %>% # R please help me read this HTML code html_nodes("p")%>% # type of HTML object .[[3]]%>% html_text() textAlmanac <- paste(c(pokemonSummary1,pokemonSummary2,pokemonSummary3), collapse=" ") paste(textAlmanac) }) ``` I'm using this data set: <https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6> and I have no idea where this error is coming from?
2018/04/11
[ "https://Stackoverflow.com/questions/49770331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9626728/" ]
You are looking for `id=False`. Use this: ``` for ul in content_container.find_all('ul', id=False): for li in ul.find_all('li'): list.append(li.text) print(li.text) ``` This will ignore all tags that have `id` as an attribute. Also, your approach was nearly correct. You just need to check whether `id` is present in tag attributes, and not in tag itself (as you are doing). So, use `if 'id' in ul.attrs()` instead of `if 'id' in ul`
try this ``` all_uls = content_container.find_all('ul') #assuming that the ul with id is the first ul for i in range(1, len(all_uls)): print(all_uls[i]) ```
2,695,990
How to test website compatibility for iPAD without having iPAD , in both condition Portrait and landscape? on Windows PC -------------
2010/04/23
[ "https://Stackoverflow.com/questions/2695990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84201/" ]
You'll probably have to use a windows browser to fake the browser-agent header. [This page](http://www.jeffdepascale.com/index.php/general/why-the-ipads-user-agent-string-presents-a-problem/) gives more information as well as the browser agent string. You could use [Chris Pederick's User Agent Switcher](http://chrispederick.com/work/user-agent-switcher/) in Firefox, but you won't get webkit rendering. The best option is probably to use the developer tools in Safari and change the browser agent in the Develop menu. You should also make sure your screen size matches the iPad (1024x768 if I'm not mistaken). To test landscape, just change the screen size. What you won't get is multitouch and gesture testing... What are you actually trying to test? If it's just a website, that should be sufficient.
also, there is another web-site: <http://ipadpeek.com/> but, if you have a special css file for ipad, this site cannot show it. you should change your main css file with ipad specific one... also, you can rotate your ipad in ipadpeek.com edit: there is an app for looking your layout on ios device [here](http://thinkvitamin.com/design/awesome-free-tool-for-ios-app-design-and-prototyping/).
8,217,938
How can I set a default url/server for all my requests from collections and models in Backbone? Example collection: ``` define([ 'backbone', '../models/communityModel' ], function(Backbone, CommunityModel){ return Backbone.Collection.extend({ url: '/communities', // localhost/communities should be api.local/communities model: CommunityModel, initialize: function () { // something } }); }); ``` I make an initial AJAX call to get my settings including the url of the API (api.local). How can I reroute the requests without passing it to all my models or hardcoding the url in the models and collections?
2011/11/21
[ "https://Stackoverflow.com/questions/8217938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824850/" ]
your url takes a string or a function. with your settings ajax call you can store it in a proper location, and go fetch that from the function to use your example: suppose your ajax call, saved the url in a `myApp.Settings.DefaultURL` ``` define([ 'backbone', '../models/communityModel' ], function(Backbone, CommunityModel){ return Backbone.Collection.extend({ url: function(){ return myApp.Settings.DefaultURL + '/communities'; }, model: CommunityModel, initialize: function () { // something } }); }); ``` **remark** make sure this url is somehow caught or handled when it would be fired before your settings are set, if your initial ajax call fails or takes its time, your app might already be started without it's settings set, should one use a `model.save()` at that point, you would need to handle this.
By over-riding (but not *over-writing*) the `Backbone.sync` method you can achieve the same result without having to add the same code to every single model/collection. ``` define(['underscore', 'backbone', 'myApp'], function (_, Backbone, myApp) { 'use strict'; // Store the original version of Backbone.sync var backboneSync = Backbone.sync; // Create a new version of Backbone.sync which calls the stored version after a few changes Backbone.sync = function (method, model, options) { /* * Change the `url` property of options to begin with the URL from settings * This works because the options object gets sent as the jQuery ajax options, which * includes the `url` property */ options.url = myApp.Settings.DefaultURL + _.isFunction(model.url) ? model.url() : model.url; // Call the stored original Backbone.sync method with the new url property backboneSync(method, model, options); }; }); ``` Then in your model/collection you can just declare the `url` as usual (e.g. `url: '/events`) Don't forget to require the file with the new `Backbone.sync` code somewhere.
45,590,040
In my project I find timezones by id. Here is an example: ``` (GMT+07:00) Indian, Christmas ``` How can I make it look like this: ``` Indian\Christmas ``` with regular expression?
2017/08/09
[ "https://Stackoverflow.com/questions/45590040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8282497/" ]
You picked up the logic for set intersection and union but you didn't convert the input into the representation they use the logic on. You can't directly act on the input string. You need to operate on a bit map. Following logic can help you get a bitmap from a string. ``` uint8_t Bitmap1[256] = {0}; uint8_t Bitmap2[256] = {0}; for (i=0;input1[i];i++){ Bitmap1[input1[i]] = 1; } for (i=0;input2[i];i++){ Bitmap2[input2[i]] = 1; } ``` Now you can use the logic to count set union and intersection. ``` in = 0; un = 0; for(i=0;i<256;i++){ in+=Bitmap1[i] && Bitmap2[i]; un+=Bitmap1[i] || Bitmap2[i]; } // Rest of the logic ``` Here is the [DEMO](http://ideone.com/wQMm26) with valid result on your input.
``` un += (source[i] || cible[i]); // allways true you can replace it with un++ in += (source[i] && cible[i]); // allways true you can replace it with in++ ``` In the C every value != 0 is true and zero if the false. So the `source[i] || cible[i]` is always true as source[i] and cible[i] is allways != 0 same `source[i] && cible[i]` is always true as both sides of the expression are non zero
4,823,785
writing another program, it reads a txt file, and stores all the letter characters and spaces (as \0) in a char array, and ignores everything else. this part works. now what i need it to do is read a user inputted string, and search for that string in the array, then print the word every time it appears. im terrible at I/O in C, how do you read a string then find it in a char array?
2011/01/28
[ "https://Stackoverflow.com/questions/4823785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/593034/" ]
``` #include <stdio.h> ... char str [80]; printf ("Enter your word: "); scanf ("%s",str); char* pch=strstr(fileData,str); while (pch!=NULL) { printf ("found at %d\n",pch-fileData+1); pch=strstr(pch+1,str); } ```
1. read in the user inputted string as a char array as well (cause strings are basically char\* anyway in C) 2. use a string matching algorithm like Boyer-Moore or Knutt-Morris-Pratt (more popularly known as KMP) - google for it if you like for C implementations of these - cause they're neat, tried and tested ways of searching strings for substrings and pattern matches and all. 3. for each of these indexOf cases, print the position where the word is found maybe? or if you prefer, the number of occurrences. Generally, the list of C string functions, found [here](http://www.edcc.edu/faculty/paul.bladek/c_string_functions.htm), say, are of the format str\* or strn\*, depending on requirements.
4,823,785
writing another program, it reads a txt file, and stores all the letter characters and spaces (as \0) in a char array, and ignores everything else. this part works. now what i need it to do is read a user inputted string, and search for that string in the array, then print the word every time it appears. im terrible at I/O in C, how do you read a string then find it in a char array?
2011/01/28
[ "https://Stackoverflow.com/questions/4823785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/593034/" ]
``` #include <stdio.h> ... char str [80]; printf ("Enter your word: "); scanf ("%s",str); char* pch=strstr(fileData,str); while (pch!=NULL) { printf ("found at %d\n",pch-fileData+1); pch=strstr(pch+1,str); } ```
One for-loop inside another for-loop (called nested loop). Go through all the letters in your array, and for each letter go through all the letters in your input string and find out if that part of the array matches with the input string. If it does, print it.
67,972,601
I would like to edit the model matrix used by predict.lm() in R to predict main effects but not interactions (but using the coefficients and variance from the full model containing interactions). I have tried: ``` data(npk) #example data mod <- lm(yield ~ N*P*K, data=npk, x=T) #run model newmat <- mod$x # acquire model matrix newmat[, c(5:8)] <- 0 #set interaction terms to 0 #try to predict on the new matrix.. predict(mod, as.data.frame(newmat), type="response", interval="confidence") ``` ... but this returns the error `'data' must be a data.frame, not a matrix or an array` because predict.lm() does not accept a model matrix. How can I predict using the model matrix given in my example code? (or is there a better way of predicting main effects but not interactions, using the full model `yield ~ N*P*K?`)
2021/06/14
[ "https://Stackoverflow.com/questions/67972601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8569109/" ]
TL;DR; ------ The reason this is happening is because **the aggregate is a scalar aggregate.** --- There are two types of aggregates: ---------------------------------- * **Vector aggregates** + Needs a `GROUP BY` clause + Returns no rows at all if the input has no rows * **Scalar aggregates** + No `GROUP BY` clause + Always returns at least one row, even if there are no input rows. `COUNT` returns `0`, others return `NULL`. The one you have used is a scalar aggregate, so **there is always one row returned.** To get a vector aggregate, **you need to add a `GROUP BY`** ```sql SELECT * FROM #Order o CROSS APPLY ( SELECT SUM(oi.Price) AS TotalPrice, COUNT(*) AS Items, MIN(oi.Price) AS MinPrice FROM #OrderItem oi WHERE oi.OrderId = o.Id -- always specify inner table in column references GROUP BY () -- the empty set -- alternatively GROUP BY oi.OrderId ) t ``` --- See also this excellent article by @PaulWhite: [Fun with Scalar and Vector Aggregates](https://www.sql.kiwi/2012/03/fun-with-aggregates.html)
> > Does anyone know why that is? > > > Because the query you are APPLYing returns a row whether or not there any matching rows, since it's an aggregate query.
67,972,601
I would like to edit the model matrix used by predict.lm() in R to predict main effects but not interactions (but using the coefficients and variance from the full model containing interactions). I have tried: ``` data(npk) #example data mod <- lm(yield ~ N*P*K, data=npk, x=T) #run model newmat <- mod$x # acquire model matrix newmat[, c(5:8)] <- 0 #set interaction terms to 0 #try to predict on the new matrix.. predict(mod, as.data.frame(newmat), type="response", interval="confidence") ``` ... but this returns the error `'data' must be a data.frame, not a matrix or an array` because predict.lm() does not accept a model matrix. How can I predict using the model matrix given in my example code? (or is there a better way of predicting main effects but not interactions, using the full model `yield ~ N*P*K?`)
2021/06/14
[ "https://Stackoverflow.com/questions/67972601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8569109/" ]
TL;DR; ------ The reason this is happening is because **the aggregate is a scalar aggregate.** --- There are two types of aggregates: ---------------------------------- * **Vector aggregates** + Needs a `GROUP BY` clause + Returns no rows at all if the input has no rows * **Scalar aggregates** + No `GROUP BY` clause + Always returns at least one row, even if there are no input rows. `COUNT` returns `0`, others return `NULL`. The one you have used is a scalar aggregate, so **there is always one row returned.** To get a vector aggregate, **you need to add a `GROUP BY`** ```sql SELECT * FROM #Order o CROSS APPLY ( SELECT SUM(oi.Price) AS TotalPrice, COUNT(*) AS Items, MIN(oi.Price) AS MinPrice FROM #OrderItem oi WHERE oi.OrderId = o.Id -- always specify inner table in column references GROUP BY () -- the empty set -- alternatively GROUP BY oi.OrderId ) t ``` --- See also this excellent article by @PaulWhite: [Fun with Scalar and Vector Aggregates](https://www.sql.kiwi/2012/03/fun-with-aggregates.html)
It seems like you think that an aggregate returns no rows when there are no applicable rows. This isn't true if there is no `GROUP BY` clause. Take the following nonsense query: ```sql SELECT COUNT(*) AS C, SUM(object_ID) AS S, MAX(object_ID) AS M FROM sys.tables WHERE [name]= N'sdfhjklsdgfgjklb807ty3480A645*)&TY0'; ``` Now, unless you have a very silly name for one of your objects, you will still get a result set with a single here: ```none C S M ----------- ----------- ----------- 0 NULL NULL ``` As such, for your query, you too get a row for **every** row in your sub query, because it just contains aggregates and no `GROUP BY`. If you don't want a row for `Id` 2, then you could use a lateral subquery, or a `WHERE`: ```sql SELECT * FROM #Order O JOIN (SELECT sq.OrderId, SUM(sq.Price) AS TotalPrice, COUNT(*) AS Items, MIN(sq.Price) AS MinPrice FROM #OrderItem sq GROUP BY sq.OrderID) OI ON O.Id = OI.OrderID; SELECT * FROM #Order o CROSS APPLY(SELECT SUM(ca.Price) AS TotalPrice, COUNT(*) AS Items, MIN(ca.Price) AS MinPrice FROM #OrderItem ca WHERE ca.OrderId = o.Id) OI WHERE OI.Items > 0; ```
2,821,233
How to compute $\sum\_n (2n - \sqrt{n^2+1}-\sqrt{n^2-1})$? I tried two ways: **1.** \begin{align\*} (2n - \sqrt{n^2+1}-\sqrt{n^2-1}) &= n - \sqrt{n^2+1} + n -\sqrt{n^2-1} \\ &= \frac{1}{n+\sqrt{n^2-1}}-\frac{1}{n-\sqrt{n^2+1}}, \end{align\*} but I don't know how to do later. **2.** \begin{align\*} (2n - \sqrt{n^2+1}-\sqrt{n^2-1}) &= 2n - \frac{(\sqrt{n^2+1} + \sqrt{n^2-1})}{1} \\ &= 2n - \frac{2}{\sqrt{n^2+1} - \sqrt{n^2-1}}, \end{align\*} but I don't know how to do later too.
2018/06/16
[ "https://math.stackexchange.com/questions/2821233", "https://math.stackexchange.com", "https://math.stackexchange.com/users/377743/" ]
Starting with Sangchul Lee's integral representation (which is a consequence of the Laplace transform) $$ S = \int\_{0}^{+\infty}\frac{I\_1(x)-J\_1(x)}{x(e^x-1)}\,dx = \frac{1}{\pi}\int\_{0}^{+\infty}\int\_{0}^{\pi}\frac{e^{-x\cos\theta}-e^{ix\cos\theta}}{e^x-1}\sin^2\theta\,d\theta\,dx \tag{1}$$ and applying Fubini's theorem we get $$ S = \frac{1}{\pi}\int\_{0}^{\pi}\left[\psi(1-i\cos\theta)-\psi(1+\cos\theta)\right]\sin^2\theta\,d\theta \tag{2}$$ where $$\begin{eqnarray\*} S &=& \frac{1}{2\pi}\int\_{0}^{\pi}\left[\psi(1-i\cos\theta)+\psi(1+i\cos\theta)-2\psi(1-\cos\theta)\right]\sin^2\theta\,d\theta\\&=&\frac{1}{\pi}\int\_{0}^{\pi}\left[\log\Gamma(1-\cos\theta)-\text{Im}\,\log\Gamma(1-i\cos\theta)\right]\cos\theta\,d\theta \tag{3}\end{eqnarray\*}$$ allows an efficient numerical evaluation of $S$ through standard integration techniques (composite Simpson's rule or Gaussian quadrature): $$ S \approx 0.6369740582412\tag{4} $$ but I do not believe that $S$ has a simple closed form in terms of standard mathematical constants. We have a similar situation [here](https://math.stackexchange.com/questions/2442091/a-ramanujan-sum/2442175).
Let us assume that you need to compute the infinite summation with $$a\_n=2n - \sqrt{n^2+1}-\sqrt{n^2-1}$$ For large values of $n$, rewrite $$a\_n=n\left(2- \sqrt{1+\frac 1{n^2}}- \sqrt{1-\frac 1{n^2}}\right)$$ and use the binomial expansion or Taylor series to get $$a\_n=\frac{1}{4 n^3}+\frac{5}{64 n^7}+O\left(\frac{1}{n^{11}}\right)$$ So, $$\sum\_{n=1}^\infty a\_n\approx\sum\_{n=1}^p a\_n+\frac 14 \sum\_{n=p+1}^\infty \frac{1}{ n^3}=\sum\_{n=1}^p a\_n-\frac{1}{8}\psi ^{(2)}(p+1)\approx \sum\_{n=1}^p a\_n +\frac 1 {8 p^2}$$ If we use $p=10$, the first summation is $\approx 0.635843$, the correction term is $0.00125$ making a total of $0.637093$ while the infinite summation looks to be $\approx 0.636974$. For sure, if we increase $p$, we shall get closer and closer. Now, the question is : what is this number ?
51,508,046
I want to run an long running operation in Android. Say the task would run for about 5-10 mins. For this reason I am planning to use a `JobIntentService` and Bind it to an `Activity`. Right now I am using a `AsyncTask`, even though I know `AsyncTask` cannot/should not be used for long running operations hence I am planning to change it now. Many times what happens is while the task is running the user minimizes the app and after sometime the Android OS closes/clears the `Activity` to free up some memory. So my `AsyncTask` is kept running without any purpose and crashes while trying to update a view in that `Activity`. So I am planning to use an `JobIntentService` . But will using an `JobIntentService` and Binding it to an `Activity` will reduce the chances of Android OS closing/clearing the `Activity`? or still will it follow the same process? Any Help would be really grateful.
2018/07/24
[ "https://Stackoverflow.com/questions/51508046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9155610/" ]
If your `Activity` is in the background then blocking Android from killing your `Activity` doesn't sound like a good idea (and even necessary) to me. Since your `Activity` is in the background it's not visible to the user and there's no need to update the UI during this time. Instead, you could do the following: If `Activity` is in the foreground then it can receive updates from your `JobIntentService` via `BroadcastReceiver` that you register/unregister with `LocalBroadcastManager` in `onResume/onPause`. IF `JobIntentService` has completed its work when your `Activity` was killed or in the background you could persist the result somewhere (for example, in `SharedPreferences`) and then in `onResume` of your `Activity` you could read that result from `SharedPreferences`.
No it won't if you BIND the service and manage the binding (through ServiceConnection) in the "OnResume" Lifecycle Method and then you UNBIND the service on the "OnPause" Lifecycle Method. ( Never tryed but I think this will work. Also if you override the return of the OnBind method in a JobIntentService you need to call the "onHandleWork" from the "onBind" by starting a new Thread"). ( Tell me if you need some code examples and I will edit this answer when I have time (: ) Happy coding. Bye
52,247,213
I'm getting a vague syntax error with the print int(rollval) on line 15. ``` from random import randint roll == 0 def diceroll(roll): def dicenum(userdicenum): userdicenum = int(raw_input("How many dice would you like to roll?")) return userdicenum def dicesides(userdiceside): userdiceside = int(raw_input("How many sides for each die?")) return userdiceside for rollval in range(1,userdicenum): rollval = randint(1,userdiceside) print int(rollval) roll = roll + rollval return roll print roll ```
2018/09/09
[ "https://Stackoverflow.com/questions/52247213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10338692/" ]
``` from random import randint def diceroll(): def dicenum(): userdicenum = int(input("How many dice would you like to roll?")) return userdicenum def dicesides(): userdiceside = int(input("How many sides for each die?")) return userdiceside roll = 0 dicesida = dicesides() # so you dont have to re type it =) for rollval in range(dicenum()): rollval = randint(1,dicesida) print(int(rollval)) roll = roll + rollval return roll print(diceroll()) ``` is this what you want?
One difference between Python3 and Python2 is that in Python3, the print statement is a function in Python3, but a keyword in Python2. The fact that it is a function means that you have to use it like any other function, which is by putting the arguments within parenthesis. Use `print(int(rollval))` You should also have a look at the second line. `roll == 0` should probably be `roll = 0`. And as mentioned in comments, you should also not use `raw_input` in Python3. Use `input`.
7,354,227
I'm writing a service using Microsoft.NET framework 3.5 and I would like to send some status messages/notify on error without using the event log, a log file or by email. Any tips on how I can achieve this/possible/wise?
2011/09/08
[ "https://Stackoverflow.com/questions/7354227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57731/" ]
Have you thought about [Log4Net](http://logging.apache.org/log4net/) ? It can send email, or store entries on the database, or send messages remotely. Have a look at the options it provides.
You could log the errors into a database or event log, throw together a UI to read the DB/log, then fire off a text message whenever an error occurs. If your text recipients' cell providers offer the feature, sending a text is as simple as sending an e-mail. For example, to send a text to a Verizon phone, just e-mail `{number}@vtext.com`, where `{number}` is a 9-digit telephone number. Here's a list of [SMS Gateways](http://en.wikipedia.org/wiki/List_of_SMS_gateways).
10,568,952
So there are plenty of questions asking how to keep child events from triggering parent events, but I can't seem to find any for the opposite. I toggle a parent event on and off like so: ``` var body_event = function(e){ console.log('test'); }; $('#btn').toggle( function(e){ $('body').bind('click', body_event); }, function(){ $('body').unbind('click', body_event); } ); ``` Currently if I run this on a page like this: ``` <body> <div id="btn">click to activate</div> <div id="example" onclick="alert('do not show this when event is bound')"> try the body event by clicking here </div> </body> ``` the toggle works fine, but when I click on "try the body event by clicking here" the alert will still show up. I want to be able to ignore all child events when the body event is bound without individually referencing the child events. In other words I'm looking for a better solution than doing something like this on toggle: ``` $('#example").attr('onclick', ''); ```
2012/05/13
[ "https://Stackoverflow.com/questions/10568952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441935/" ]
This is close, but not quite there. It doesn't check whether the specific function is bound, just whether there are any events bound to the jQuery object. There must be a way to query the events to find if one is bound to click, and then subsequently what function it points too. Hopefully this gets you started though. <http://jsfiddle.net/PhjB8/> ``` var body_event = function(e) { alert('test'); }; $('#btn').toggle( function(e) { $('body').addClass('active').bind('click', body_event); }, function() { $('body').removeClass('active').unbind('click', body_event); }); $('#example').click(function() { //debugger; if ($('body').data('events') == undefined) { alert('do not show this when event is bound'); } });​ ```
event.stopPropagation() can solve this problem, inside body\_event?
20,384,338
The application I'm working on is an internal business application for managers. It's a C# web application. The main office has an instance of this app running and it always has the latest version. Each store has it's own instance of the application running as well, but may not always have the latest version. A manager logs in to the main office app and then selects a store to view. That store's instance is pulled up in the main part of the app, the upper menu bar is from the main office's instance. Thus, it is possible that the main office has v1.8 and a store to have v1.7. There are some features in 1.8 that show up on the menu bar that are not present in 1.7 that I would like to hide. The main page has multiple partials that get loaded and the very last partial has the specific store's version number that is determined by the code on that store's server. Because of this, the only way to get the version number is to get it after it is rendered on the page. The main problem I'm having is that the Javascript I'm using to hide the links to the new features is running before the partial with the version number loads. I need the Javascript to wait until the entire page finishes loading to execute the hiding code. Also, the application is only run in Chrome. Here is the code I've got to hide the links: ``` $(window).load(function () { if ($('.version').length !== 0) { if (parseFloat($('.version').text().slice(5)) > 1.7) { $('.analysis').show(); } else { $('.analysis').hide(); } } }); ```
2013/12/04
[ "https://Stackoverflow.com/questions/20384338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629412/" ]
If you are loading the partial with ajax on the client side explicitly, you can just add a complete function to call: ``` $( "#storeContainer" ).load( "url/for/partial", function () { if ($('.version').length !== 0) { if (parseFloat($('.version').text().slice(5)) > 1.7) { $('.analysis').show(); } else { $('.analysis').hide(); } } }); ``` Of course, you'll probably want the "url/for/partial" to use @Url.Content or @Url.Action if you can. If you are using The Ajax Helper, you can set the OnSuccess property of your AjaxOptions to call you back: ``` @Ajax.ActionLink("Refresh", "Store", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "storeContainer", InsertionMode = InsertionMode.Replace, OnSuccess = "updateSuccess" }); ``` where you have defined your OnSuccess function in javascript: ``` var updateSuccess = function () { if ($('.version').length !== 0) { if (parseFloat($('.version').text().slice(5)) > 1.7) { $('.analysis').show(); } else { $('.analysis').hide(); } } ``` There are some other ideas about how to include the script in your partial view or call it during your ajax success event on [How to initialize jquery ui widgets that may be loaded dynamically in MVC3 application](https://stackoverflow.com/questions/11800204/how-to-initialize-jquery-ui-widgets-that-may-be-loaded-dynamically-in-mvc3-appli) If you were using Asp.net AJAX, you could use `Sys.Application.add_load(function(){...})`.
Have you tried using ``` $(document).on("ready", function() { }); ``` in place of $window.load()?
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
It seems like this is by (the very dumb) design. You must have this exception thrown and caught in your code. MSDN looks silent about it indeed, but if you look at the documentation of another asynchronous socket method, [BeginConnect()](http://msdn.microsoft.com/en-us/library/tad07yt6.aspx), here's what we find: > > To cancel a pending call to the > BeginConnect() method, close the > Socket. When the Close() method is > called while an asynchronous operation > is in progress, the callback provided > to the BeginConnect() method is > called. A subsequent call to the > EndConnect(IAsyncResult) method will > throw an ObjectDisposedException to > indicate that the operation has been > cancelled. > > > If it is the proper way of doing for BeginConnect, it is probably so for BeginReceive as well. This is certainly a poor design on the part of Microsoft's async API, because making the user necessarily throw and catch exception as a part of a normal flow would annoy the debugger. You have really no way to "wait" until the operation is completed, because Close() is what completes it in the first place.
For TCP socket connections, you can use the [Connected](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.connected?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.Net.Sockets.Socket.Connected);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.7);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.7) property to determine the state of the socket before trying to access any disposed methods. Per MSDN: "The Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected." Since it says "no longer connected" it implies that a Close() was previously called on the socket. If you check whether the socket is Connected at the start of the receive callback, there will be no exception.
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
I am surprised no one recommended using SocketOptions. Once the stack has the send or receive operation it is bound by the socket options of the socket. Use a small send or receive timeout and use it before the operation so you don't care if it's changed during that same operation to something shorter or longer. This will cause more context switching but will not require closing the socket under any protocol. For example: 1) Set a small timeout 2) Perform operations 3) Set timeout larger This is similar to using Blocking = false but with an automatic timeout that you specify.
For TCP socket connections, you can use the [Connected](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.connected?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.Net.Sockets.Socket.Connected);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.7);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.7) property to determine the state of the socket before trying to access any disposed methods. Per MSDN: "The Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected." Since it says "no longer connected" it implies that a Close() was previously called on the socket. If you check whether the socket is Connected at the start of the receive callback, there will be no exception.
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
In the ReceiveCallback I checked client.Connected within the try block. Now, when data is received after BeginReceive, I can call client.Close(); This way, I do not see exceptions. I send modbus-TCP requests every 200mS, and get responses in time. The console output looks clean. I used a windows forms app, to test this. ``` private static void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; if (client.Connected) { // Read data from the remote device. state.dataSize = client.EndReceive(ar); if (state.dataSize > 0) { Console.WriteLine("Received: " + state.dataSize.ToString() + " bytes from server"); // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.dataSize)); // Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReceiveCallback), state); state.dataSizeReceived = true; //received data size? dataSize = state.dataSize; buffer = state.buffer.ToArray(); dataSizeReceived = state.dataSizeReceived; string hex = ByteArrayToString(state.buffer, state.dataSize); Console.WriteLine("<- " + hex); receiveDone.Set(); client.Close(); } else { Console.WriteLine("All the data has arrived"); // All the data has arrived; put it in response. if (state.sb.Length > 1) { Console.WriteLine("Length: " + state.sb.Length.ToString()); } // Signal that all bytes have been received. receiveDone.Set(); } } } catch (Exception e) { Console.WriteLine(e.ToString()); } } ```
I was struggling with this as well but as far as I can tell using a simple boolean flag before calling `.BeginReceive()` will work as well (so there'll be no need for exception handling). Since I already had start/stop handling, this fix was a matter of one `if` statement (scroll down to the bottom of the `OnReceive()` method). ``` if (_running) { _mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null); } ``` Should I have overlooked something with this approach, let me know!
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
You can read my solution of this problem here(using comment of Pavel Radzivilovsky here): [UdpClient.ReceiveAsync correct early termination](https://stackoverflow.com/questions/41019997/udpclient-receiveasync-correct-early-termination/41041601?noredirect=1#comment69291144_41041601)
I was struggling with this as well but as far as I can tell using a simple boolean flag before calling `.BeginReceive()` will work as well (so there'll be no need for exception handling). Since I already had start/stop handling, this fix was a matter of one `if` statement (scroll down to the bottom of the `OnReceive()` method). ``` if (_running) { _mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null); } ``` Should I have overlooked something with this approach, let me know!
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
It seems like this is by (the very dumb) design. You must have this exception thrown and caught in your code. MSDN looks silent about it indeed, but if you look at the documentation of another asynchronous socket method, [BeginConnect()](http://msdn.microsoft.com/en-us/library/tad07yt6.aspx), here's what we find: > > To cancel a pending call to the > BeginConnect() method, close the > Socket. When the Close() method is > called while an asynchronous operation > is in progress, the callback provided > to the BeginConnect() method is > called. A subsequent call to the > EndConnect(IAsyncResult) method will > throw an ObjectDisposedException to > indicate that the operation has been > cancelled. > > > If it is the proper way of doing for BeginConnect, it is probably so for BeginReceive as well. This is certainly a poor design on the part of Microsoft's async API, because making the user necessarily throw and catch exception as a part of a normal flow would annoy the debugger. You have really no way to "wait" until the operation is completed, because Close() is what completes it in the first place.
Another solution would be to send "yourself" a "control message" using a socket bound to a different port. It's not exactly an abort, but it would end your async operation.
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
I am surprised no one recommended using SocketOptions. Once the stack has the send or receive operation it is bound by the socket options of the socket. Use a small send or receive timeout and use it before the operation so you don't care if it's changed during that same operation to something shorter or longer. This will cause more context switching but will not require closing the socket under any protocol. For example: 1) Set a small timeout 2) Perform operations 3) Set timeout larger This is similar to using Blocking = false but with an automatic timeout that you specify.
You can read my solution of this problem here(using comment of Pavel Radzivilovsky here): [UdpClient.ReceiveAsync correct early termination](https://stackoverflow.com/questions/41019997/udpclient-receiveasync-correct-early-termination/41041601?noredirect=1#comment69291144_41041601)
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
In the ReceiveCallback I checked client.Connected within the try block. Now, when data is received after BeginReceive, I can call client.Close(); This way, I do not see exceptions. I send modbus-TCP requests every 200mS, and get responses in time. The console output looks clean. I used a windows forms app, to test this. ``` private static void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; if (client.Connected) { // Read data from the remote device. state.dataSize = client.EndReceive(ar); if (state.dataSize > 0) { Console.WriteLine("Received: " + state.dataSize.ToString() + " bytes from server"); // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.dataSize)); // Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReceiveCallback), state); state.dataSizeReceived = true; //received data size? dataSize = state.dataSize; buffer = state.buffer.ToArray(); dataSizeReceived = state.dataSizeReceived; string hex = ByteArrayToString(state.buffer, state.dataSize); Console.WriteLine("<- " + hex); receiveDone.Set(); client.Close(); } else { Console.WriteLine("All the data has arrived"); // All the data has arrived; put it in response. if (state.sb.Length > 1) { Console.WriteLine("Length: " + state.sb.Length.ToString()); } // Signal that all bytes have been received. receiveDone.Set(); } } } catch (Exception e) { Console.WriteLine(e.ToString()); } } ```
Another solution would be to send "yourself" a "control message" using a socket bound to a different port. It's not exactly an abort, but it would end your async operation.
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
It seems like this is by (the very dumb) design. You must have this exception thrown and caught in your code. MSDN looks silent about it indeed, but if you look at the documentation of another asynchronous socket method, [BeginConnect()](http://msdn.microsoft.com/en-us/library/tad07yt6.aspx), here's what we find: > > To cancel a pending call to the > BeginConnect() method, close the > Socket. When the Close() method is > called while an asynchronous operation > is in progress, the callback provided > to the BeginConnect() method is > called. A subsequent call to the > EndConnect(IAsyncResult) method will > throw an ObjectDisposedException to > indicate that the operation has been > cancelled. > > > If it is the proper way of doing for BeginConnect, it is probably so for BeginReceive as well. This is certainly a poor design on the part of Microsoft's async API, because making the user necessarily throw and catch exception as a part of a normal flow would annoy the debugger. You have really no way to "wait" until the operation is completed, because Close() is what completes it in the first place.
I was struggling with this as well but as far as I can tell using a simple boolean flag before calling `.BeginReceive()` will work as well (so there'll be no need for exception handling). Since I already had start/stop handling, this fix was a matter of one `if` statement (scroll down to the bottom of the `OnReceive()` method). ``` if (_running) { _mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null); } ``` Should I have overlooked something with this approach, let me know!
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
You can read my solution of this problem here(using comment of Pavel Radzivilovsky here): [UdpClient.ReceiveAsync correct early termination](https://stackoverflow.com/questions/41019997/udpclient-receiveasync-correct-early-termination/41041601?noredirect=1#comment69291144_41041601)
Another solution would be to send "yourself" a "control message" using a socket bound to a different port. It's not exactly an abort, but it would end your async operation.
4,662,553
Naturally, `BeginReceive()` will never end if there's no data. MSDN [suggests](http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx) that calling `Close()` would abort `BeginReceive()`. However, calling `Close()` on the socket also performs a `Dispose()` on it, as figured out in [this great answer](https://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548), and consequently `EndReceive()` would throw an exception because the object is already disposed (and it does!). How should I proceed?
2011/01/11
[ "https://Stackoverflow.com/questions/4662553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324922/" ]
I am surprised no one recommended using SocketOptions. Once the stack has the send or receive operation it is bound by the socket options of the socket. Use a small send or receive timeout and use it before the operation so you don't care if it's changed during that same operation to something shorter or longer. This will cause more context switching but will not require closing the socket under any protocol. For example: 1) Set a small timeout 2) Perform operations 3) Set timeout larger This is similar to using Blocking = false but with an automatic timeout that you specify.
Another solution would be to send "yourself" a "control message" using a socket bound to a different port. It's not exactly an abort, but it would end your async operation.
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
You can't use `DateTimePicker` instance as a query parameter. Use `DateTimePicker.Value` instead: ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); ```
Change your ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); ``` to ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Text); ``` What you do is you can't add a `DateTimePicker` instance as a parameter. `AddWithValue` method takes string as a second parameter. Use [`Value`](http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx) or [`Text`](http://msdn.microsoft.com/en-us/library/bt6y6733.aspx) properties.
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
You can't use `DateTimePicker` instance as a query parameter. Use `DateTimePicker.Value` instead: ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); ```
dateTimePicker1 is a control not a DateTime value. U need to get the DateTime value from: ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value.ToString()); ```
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
You can't use `DateTimePicker` instance as a query parameter. Use `DateTimePicker.Value` instead: ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); ```
You need the value of `dateTimePicker1`, you should change: ``` command.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); ``` to ``` command.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); ```
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
You can't use `DateTimePicker` instance as a query parameter. Use `DateTimePicker.Value` instead: ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); ```
What Dennis said is correct. Additionally you probably want to show an error message if it doesnt work. eg: ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { conect.Close(); } } ```
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
Change your ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); ``` to ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Text); ``` What you do is you can't add a `DateTimePicker` instance as a parameter. `AddWithValue` method takes string as a second parameter. Use [`Value`](http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx) or [`Text`](http://msdn.microsoft.com/en-us/library/bt6y6733.aspx) properties.
dateTimePicker1 is a control not a DateTime value. U need to get the DateTime value from: ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value.ToString()); ```
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
Change your ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); ``` to ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Text); ``` What you do is you can't add a `DateTimePicker` instance as a parameter. `AddWithValue` method takes string as a second parameter. Use [`Value`](http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx) or [`Text`](http://msdn.microsoft.com/en-us/library/bt6y6733.aspx) properties.
You need the value of `dateTimePicker1`, you should change: ``` command.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); ``` to ``` command.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); ```
19,179,635
i have a form on which controls are assigned ![enter image description here](https://i.stack.imgur.com/bxWr1.png) and this is the code when i clicked insert button ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } finally { conect.Close(); } } ``` but when i inserted data then this exception comes ![enter image description here](https://i.stack.imgur.com/Ch3Yw.png) what can i do here...my store procedure is also here ``` ALTER PROCEDURE InsertRecordingArtists @RecordingArtistName text, @DateOfBirth datetime, @BirthPlace text ``` AS BEGIN INSERT INTO [MusicCollection].[dbo].[RecordingArtists] ([RecordingArtistName],[DateOfBirth],[BirthPlace]) VALUES (@RecordingArtistName,@DateOfBirth,@BirthPlace)
2013/10/04
[ "https://Stackoverflow.com/questions/19179635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702357/" ]
Change your ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1); ``` to ``` comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Text); ``` What you do is you can't add a `DateTimePicker` instance as a parameter. `AddWithValue` method takes string as a second parameter. Use [`Value`](http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx) or [`Text`](http://msdn.microsoft.com/en-us/library/bt6y6733.aspx) properties.
What Dennis said is correct. Additionally you probably want to show an error message if it doesnt work. eg: ``` private void btnInsertRArtist_Click(object sender, EventArgs e) { SqlCommand comand = new SqlCommand("InsertRecordingArtists", conect); comand.CommandType = CommandType.StoredProcedure; try { if (txtboxRArtistName.Text == string.Empty || txtboxPlaceOB.Text == "") { errorProvider1.SetError(txtboxRArtistName, "Enter the Music category"); } else { conect.Open(); comand.Parameters.AddWithValue("@RecordingArtistName", txtboxRArtistName.Text); comand.Parameters.AddWithValue("@DateOfBirth", dateTimePicker1.Value); comand.Parameters.AddWithValue("@BirthPlace", txtboxPlaceOB.Text); SqlDataAdapter adapt = new SqlDataAdapter(comand); comand.ExecuteNonQuery(); txtboxRArtistName.Text = ""; } } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { conect.Close(); } } ```
50,753,645
I am facing the following situation: I own a domain name, let's say example.com at name.com We have a website hosted at bluehost on a shared hosting with an IP1 We have an ERP (odoo) hosted at digitalocean on a droplet where Nginx is running and where IP2 is allocated. The erp is accesible via IP2:port\_number I am trying to redirect erp.example.com in direction of odoo while keeping the main domaine <http://example.com> to point to IP1 I have tried to setup two A record. One for erp.example.com to point to IP2 but here I can not specify the port at name.com, problem is it doesn't seems even to point on the 80 port as I don't see the Nginx welcome page when I type <http://erp.example.com> I have setup another A record which point to the bluehost IP1 on a wordpress website and this works fine. DNS are recorded with two ns of bluehost only. Based on my understanding I should point the erp.example.com to IP2, then set nginx to filter erp.example.com to go to IP2:port with a redirection ? I don't understand why my A record pointing to IP2 doesn't direct me to the digital ocean server. In Chrome it gives me a ERR\_NAME\_NOT\_RESOLVED . What am I doing wrong ?
2018/06/08
[ "https://Stackoverflow.com/questions/50753645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5594353/" ]
To keep it very short. `ngOnInit()` is used to execute any piece of code for only one time (for eg : data fetch on load). `ngOnChanges()` will execute on every `@Input()` property change. If you want to execute any component method, based on the `@Input()` value change, then you should write such logic inside `ngOnChanges()`. As you claim why do we need `ngOnInit()` when we have `ngOnChanges(),` it is because you cannot execute one time code, on every `@Input()` property change. And you cannot use `constructor` as the replacement of `ngOnInit()` as well. Because the bindings, such as @Input properties are not available within the constructor. I think you will get fair idea with this [Diff between OnInit and constructor](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit)
ngOnChanges() is called whenever input bound properties of its component changes, it receives an object called SimpleChanges which contains changed and previous property. ngOnInit() is used to initialize things in a component,unlike ngOnChanges() it is called only once and after first ngOnChanges().
50,753,645
I am facing the following situation: I own a domain name, let's say example.com at name.com We have a website hosted at bluehost on a shared hosting with an IP1 We have an ERP (odoo) hosted at digitalocean on a droplet where Nginx is running and where IP2 is allocated. The erp is accesible via IP2:port\_number I am trying to redirect erp.example.com in direction of odoo while keeping the main domaine <http://example.com> to point to IP1 I have tried to setup two A record. One for erp.example.com to point to IP2 but here I can not specify the port at name.com, problem is it doesn't seems even to point on the 80 port as I don't see the Nginx welcome page when I type <http://erp.example.com> I have setup another A record which point to the bluehost IP1 on a wordpress website and this works fine. DNS are recorded with two ns of bluehost only. Based on my understanding I should point the erp.example.com to IP2, then set nginx to filter erp.example.com to go to IP2:port with a redirection ? I don't understand why my A record pointing to IP2 doesn't direct me to the digital ocean server. In Chrome it gives me a ERR\_NAME\_NOT\_RESOLVED . What am I doing wrong ?
2018/06/08
[ "https://Stackoverflow.com/questions/50753645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5594353/" ]
To keep it very short. `ngOnInit()` is used to execute any piece of code for only one time (for eg : data fetch on load). `ngOnChanges()` will execute on every `@Input()` property change. If you want to execute any component method, based on the `@Input()` value change, then you should write such logic inside `ngOnChanges()`. As you claim why do we need `ngOnInit()` when we have `ngOnChanges(),` it is because you cannot execute one time code, on every `@Input()` property change. And you cannot use `constructor` as the replacement of `ngOnInit()` as well. Because the bindings, such as @Input properties are not available within the constructor. I think you will get fair idea with this [Diff between OnInit and constructor](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit)
ngOnChanges will be called first on the life cycle hook when there is a change to the component inputs through the parent. ngOnInit will be called only once on initializing the component after the first ngOnChanges called.
50,753,645
I am facing the following situation: I own a domain name, let's say example.com at name.com We have a website hosted at bluehost on a shared hosting with an IP1 We have an ERP (odoo) hosted at digitalocean on a droplet where Nginx is running and where IP2 is allocated. The erp is accesible via IP2:port\_number I am trying to redirect erp.example.com in direction of odoo while keeping the main domaine <http://example.com> to point to IP1 I have tried to setup two A record. One for erp.example.com to point to IP2 but here I can not specify the port at name.com, problem is it doesn't seems even to point on the 80 port as I don't see the Nginx welcome page when I type <http://erp.example.com> I have setup another A record which point to the bluehost IP1 on a wordpress website and this works fine. DNS are recorded with two ns of bluehost only. Based on my understanding I should point the erp.example.com to IP2, then set nginx to filter erp.example.com to go to IP2:port with a redirection ? I don't understand why my A record pointing to IP2 doesn't direct me to the digital ocean server. In Chrome it gives me a ERR\_NAME\_NOT\_RESOLVED . What am I doing wrong ?
2018/06/08
[ "https://Stackoverflow.com/questions/50753645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5594353/" ]
How a form need be setup **0. Static design** Html markup should hold how the design is structured and laid out. Any permanent classes are to be applied directly in markup. **1. Constructor** Setup dependencies, like services, providers, configuration etc. These enable the component to manage itself along with interact with other elements. **2. Initializer (ngOnInit)** Populates form elements like dropdowns etc when their values are to be retrieved from external source, rather than being known at design time. This is to be done once only to setup the initial rendering of the form **3. Input changes (ngOnChanges)** Runs on every change on any input, and perform any action which gets triggered by that particular control. For example, if there are multiple inputs and on any validation failure on a single one, you need to focus on the failed control and disable *all* others, you can do it here. Useful for validation logic. Not to be used to handle other control's layout and structure. This often runs recursively if one control impacts others so logic has to be carefully designed. If you want to prevent this from running, you can disable the Angular change detection and manually handle the state yourself. **4. Control's event handlers** Here you take in the final value of the control and use it to perform manipulation of other controls in the form. As soon as you change the value of other controls, the ngOnChanges event fires again.
To keep it very short. `ngOnInit()` is used to execute any piece of code for only one time (for eg : data fetch on load). `ngOnChanges()` will execute on every `@Input()` property change. If you want to execute any component method, based on the `@Input()` value change, then you should write such logic inside `ngOnChanges()`. As you claim why do we need `ngOnInit()` when we have `ngOnChanges(),` it is because you cannot execute one time code, on every `@Input()` property change. And you cannot use `constructor` as the replacement of `ngOnInit()` as well. Because the bindings, such as @Input properties are not available within the constructor. I think you will get fair idea with this [Diff between OnInit and constructor](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit)
50,753,645
I am facing the following situation: I own a domain name, let's say example.com at name.com We have a website hosted at bluehost on a shared hosting with an IP1 We have an ERP (odoo) hosted at digitalocean on a droplet where Nginx is running and where IP2 is allocated. The erp is accesible via IP2:port\_number I am trying to redirect erp.example.com in direction of odoo while keeping the main domaine <http://example.com> to point to IP1 I have tried to setup two A record. One for erp.example.com to point to IP2 but here I can not specify the port at name.com, problem is it doesn't seems even to point on the 80 port as I don't see the Nginx welcome page when I type <http://erp.example.com> I have setup another A record which point to the bluehost IP1 on a wordpress website and this works fine. DNS are recorded with two ns of bluehost only. Based on my understanding I should point the erp.example.com to IP2, then set nginx to filter erp.example.com to go to IP2:port with a redirection ? I don't understand why my A record pointing to IP2 doesn't direct me to the digital ocean server. In Chrome it gives me a ERR\_NAME\_NOT\_RESOLVED . What am I doing wrong ?
2018/06/08
[ "https://Stackoverflow.com/questions/50753645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5594353/" ]
To keep it very short. `ngOnInit()` is used to execute any piece of code for only one time (for eg : data fetch on load). `ngOnChanges()` will execute on every `@Input()` property change. If you want to execute any component method, based on the `@Input()` value change, then you should write such logic inside `ngOnChanges()`. As you claim why do we need `ngOnInit()` when we have `ngOnChanges(),` it is because you cannot execute one time code, on every `@Input()` property change. And you cannot use `constructor` as the replacement of `ngOnInit()` as well. Because the bindings, such as @Input properties are not available within the constructor. I think you will get fair idea with this [Diff between OnInit and constructor](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit)
ngOnInit and ngOnChanges are functions belonging to a component life-cycle method groups and they are executed in a different moment of our component (that's why name life-cycle). Here is a list of all of them: [![enter image description here](https://i.stack.imgur.com/JwzQ4.png)](https://i.stack.imgur.com/JwzQ4.png)