title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Passing template variable to parent in Django
<p>I have a number of apps that each have their own intro section. This intro section has quite a few lines of HTML and only a few lines are adjusted for each app (Think title and intro). I would like this intro section to live at the project level (where the navbar template lives), but I can't find a way to pass template variables from the app to the project. </p> <p>All of my apps(about 15) follow this template scheme:</p> <pre><code>app_base.html extends project base.html app_base.html has an {% include %} to pull in app_intro.html all &lt;app_unique_templates&gt;.html that are called by &lt;app&gt;/views.py, extend the app_base.html </code></pre> <p>To reiterate, how can I pass a template variable from /views.py to project base.html template using my app template scheme? If I can't use this scheme, can I adjust it in a way that will allow me to accomplish this?</p> <p>Thank you all in advance!</p> <p>views.py:</p> <pre><code>def add_app_context(view_context): app_context = { 'app_name': 'Material Database', 'app_desc': 'Long String goes Here For Application Description', 'doc_link': '#', } view_context.update(app_context) return view_context class MaterialList(ListView): model = Material context_object_name = 'materials' def get_context_data(self): context = super().get_context_data() context['pagetitle'] = 'Material List' context['intro_btn_link'] = '/materials/new' context['intro_btn_name'] = 'Create New Material' return add_app_context(context) </code></pre> <p>app_base.html:</p> <pre><code>{% extends "mjd_tools/base.html" %} {% load staticfiles %} {% block body %} &lt;link rel="stylesheet" href="{% static 'mat_db/css/style.css' %}"&gt; {% include "mat_db/app_intro.html" %} {% block list %}{% endblock list %} {% block form %}{% endblock form %} &lt;script src="{% static 'mat_db/js/scripts.js' %}"&gt;&lt;/script&gt; {% endblock body %} </code></pre> <p>app_intro.html(this is what I have to repeat for each app).</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-sm-8"&gt; &lt;h1&gt;{{ app_name }}&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;hr&gt; &lt;div class="row"&gt; &lt;div class="col-sm-8"&gt; &lt;p&gt; {{ app_desc }} &lt;/p&gt; &lt;/div&gt; &lt;div class="col-auto ml-auto"&gt; &lt;a class="btn btn-warning" role="button" href="{{ doc_link }}"&gt;Documentation&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;hr&gt; &lt;div class="row"&gt; &lt;div class="col-sm text-center"&gt; &lt;h4&gt; &lt;span&gt;{{ pagetitle }}&lt;/span&gt; {% if intro_btn_name %} &lt;a class="btn btn-primary btn-sm pull-right" role="button" href="{{ intro_btn_link }}"&gt;{{ intro_btn_name }}&lt;/a&gt; &lt;/h4&gt; {% endif %} &lt;/div&gt; &lt;/div&gt; &lt;hr&gt; </code></pre>
3
1,273
Django MTPP display recursive hierarchical category in REST API
<p>I am trying to display my recursive category model in my Django REST API list view. This is how it is now:</p> <pre><code>"results": [ { "pk": 3, "title": "Test", "category": 7, }, ... ]} </code></pre> <p>I want to achieve something like this:</p> <pre><code>"results": [ { "pk": 3, "title": "Test", "category": [ { "id": 5, "name": "Cat", "slug": "cat", "child": [ { "id": 7, "name": "Parser", "slug": "parser", } ] } ], }, ... ]} </code></pre> <p>I am currently using Django MPTT to create a hierarchical Model. This is the Category in models.py:</p> <pre><code>class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.SET_NULL) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name = "Category" verbose_name_plural = "Categories" def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i + 1])) return slugs def __str__(self): return self.name </code></pre> <p>I am using generic views from Django Rest Framework to create the view. In views.py:</p> <pre><code>class CaseListCreateView(generics.ListCreateAPIView): serializer_class = CaseSerializer def get_queryset(self): qs = Case.objects.filter(active=True) query = self.request.GET.get("search") if query is not None: qs = qs.filter(Q(title__contains=query) | Q(text__contains=query)).distinct() return qs def perform_create(self, serializer): serializer.save(user=self.request.user) </code></pre> <p>I have tried <a href="https://github.com/heywbj/django-rest-framework-recursive" rel="nofollow noreferrer">using djangorestframework-recursive</a> to make the recursion but with no luck. </p> <p>Any help would be greatly appriciated! Thanks</p>
3
1,202
Extract data from xml file in C#
<p>I need to extract data from a XML file for my project based on C#. The XML file is like this :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Chemicals&gt; &lt;Titrates&gt; &lt;Titrate Name="Hydrochloric Acid" Basisity="1" Molarity="10" Normality="10" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;Experiment Name="Redox"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Titrate&gt; &lt;Titrate Name="Sulphuric Acid" Basisity="2" Molarity="20" Normality="50" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Titrate&gt; &lt;Titrate Name="Nitric Acid" Basisity="3" Molarity="50" Normality="40" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Titrate&gt; &lt;/Titrates&gt; &lt;Titrants&gt; &lt;Titrant Name="Sodium Hydroxide" Acidity="1" Molarity="10" Normality="20" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Titrant&gt; &lt;Titrant Name="Calcium Hydroxide" Acidity="1" Molarity="20" Normality="40" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Titrant&gt; &lt;/Titrants&gt; &lt;Indicators&gt; &lt;Indicator Name="Phenolphethalin" Color="Pink" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Indicator&gt; &lt;Indicator Name="Methyl Orange" Color="Orange" &gt; &lt;Experiments&gt; &lt;Experiment Name="AcidBase"&gt;&lt;/Experiment&gt; &lt;/Experiments&gt; &lt;/Indicator&gt; &lt;/Indicators&gt; &lt;/Chemicals&gt; </code></pre> <p>As you can see, The chemicals are divided under titrants, titrates and indicators and then each chemical may be used in multiple experiments. The file is just a sample so, please ignore the chemistry aspect :P. So, for a particular experiment I need to extract the relevant data of all the chemicals that will be used in it.</p> <p>Example:</p> <p>For AcidBase Titration I would need the Name, Molarity, Basisity etc ( under titrates ) of the particular titrate. Same way for titrants and indicators whichever have AcidBase in their Experiment part.</p>
3
1,290
Pg search gem doesn't work on Heroku
<p>I have problem with properly work pg_search gem on Heroku. On localhost works great, but when I try to search some expression on developer site always display empty result. I tried to inspect object of result, but nothing showed. In heroku console comand <em>PgSearch.multisearch("ruby")</em> working fine.</p> <p><strong>vocabulary.rb</strong></p> <pre><code># == Schema Information # # Table name: vocabularies # # id :integer not null, primary key # expression :string # meaning :string # created_at :datetime not null # updated_at :datetime not null # class Vocabulary &lt; ActiveRecord::Base include PgSearch multisearchable :against =&gt; [:expression, :meaning] belongs_to :user validates :expression, :meaning, presence: true default_scope -&gt; { order(updated_at: :desc)} end </code></pre> <p><strong>VocabulariesController</strong></p> <pre><code>class VocabulariesController &lt; ApplicationController def search if params[:search].present? @pg_search_documents = PgSearch.multisearch(params[:search]).paginate(:page =&gt; params[:page], :per_page =&gt; 4) else @pg_search_documents = Vocabulary.all end end end </code></pre> <p><strong>View:</strong></p> <pre><code>.searchbar_min =render 'layouts/searchbar' %table.table.table-striped %thead %tr %th Wyrażenie %th Znaczenie %th %th %th %tbody = will_paginate @pg_search_documents - @pg_search_documents.each do |pg_search_document| %tr =pg_search_document.inspect %td= pg_search_document.searchable.expression %td= HTML_Truncator.truncate(pg_search_document.searchable.meaning, 40).html_safe %td = link_to vocabulary_path(pg_search_document), class: "btn btn-link" do %i.glyphicon.glyphicon-eye-open Pokaż -if current_user &amp;&amp; current_user.admin? %td = link_to edit_vocabulary_path(pg_search_document), class: "btn btn-link" do %i.glyphicon.glyphicon-edit Edytuj %td = link_to vocabulary_path(pg_search_document), :method =&gt; :delete, :data =&gt; { :confirm =&gt; 'Jesteś pewny/a?' }, class: "btn btn-link" do %i.glyphicon.glyphicon-trash Usuń %br = will_paginate @pg_search_documents </code></pre> <p>Below there are few line of code with registered action when i try search expression: ruby. Heroku logs:</p> <pre><code>2016-02-11T10:10:37.832351+00:00 heroku[router]: at=info method=GET path="/vocabularies/search?utf8=%E2%9C%93&amp;search=ruby" host=uidictionary.herokuapp.com request_id=37e83ee8-db63-4b45-a70f-4eca54287db2 fwd="84.10.16.142" dyno=web.1 connect=1ms service=181ms status=200 bytes=4388 2016-02-11T10:10:38.104878+00:00 heroku[router]: at=info method=GET path="/assets/application-dd08fe2ece9bd6ce8ece8cf874543813ca1cab7fa569184002981bf9c3d5c2d8.css" host=uidictionary.herokuapp.com request_id=2803fdca-2057-430d-809c-7f4cf3cd4824 fwd="84.10.16.142" dyno=web.1 connect=1ms service=20ms status=304 bytes=133 2016-02-11T10:10:38.283719+00:00 heroku[router]: at=info method=GET path="/assets/application-073c4fa35429da031792509534cc1edc2d1c5fe7b72d6a51ad0c80df3d0636eb.js" host=uidictionary.herokuapp.com request_id=1eff89eb-ca19-4b28-a8bf-1117ed113dd9 fwd="84.10.16.142" dyno=web.1 connect=1ms service=28ms status=304 bytes=133 2016-02-11T10:10:39.019321+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=uidictionary.herokuapp.com request_id=c987cc45-848f-4ab9-a0fd-d9896b1b08e1 fwd="84.10.16.142" dyno=web.1 connect=1ms service=8ms status=304 bytes=133 2016-02-11T10:11:10.614151+00:00 heroku[router]: at=info method=GET path="/vocabularies/search?utf8=%E2%9C%93&amp;search=ruby" host=uidictionary.herokuapp.com request_id=a1e0f447-305b-4aa6-956b-5dc2543eefad fwd="84.10.16.142" dyno=web.1 connect=1ms service=34ms status=200 bytes=4388 2016-02-11T10:11:10.584974+00:00 app[web.1]: Started GET "/vocabularies/search?utf8=%E2%9C%93&amp;search=ruby" for 84.10.16.142 at 2016-02-11 10:11:10 +0000 2016-02-11T10:11:10.597016+00:00 app[web.1]: Rendered layouts/_searchbar.html.haml (1.0ms) 2016-02-11T10:11:10.604687+00:00 app[web.1]: PgSearch::Document Load (2.9ms) SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('simple', ''' ' || 'ruby' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'ruby' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC LIMIT 4 OFFSET 0 2016-02-11T10:11:10.611004+00:00 app[web.1]: Rendered layouts/_bootstrap.html.haml (0.1ms) 2016-02-11T10:11:10.612747+00:00 app[web.1]: Completed 200 OK in 24ms (Views: 12.3ms | ActiveRecord: 7.1ms) 2016-02-11T10:11:10.588341+00:00 app[web.1]: Processing by VocabulariesController#search as HTML 2016-02-11T10:11:10.588375+00:00 app[web.1]: Parameters: {"utf8"=&gt;"✓", "search"=&gt;"ruby"} 2016-02-11T10:11:10.591815+00:00 app[web.1]: User Load (1.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]] 2016-02-11T10:11:10.600817+00:00 app[web.1]: (2.4ms) SELECT COUNT(*) FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('simple', ''' ' || 'ruby' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'ruby' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id 2016-02-11T10:11:10.612038+00:00 app[web.1]: Rendered layouts/_navbar.html.haml (0.8ms) 2016-02-11T10:11:10.606390+00:00 app[web.1]: Rendered vocabularies/search.html.haml within layouts/application (10.7ms) </code></pre> <p>How to resolve problem?</p>
3
2,770
jquery next() returning nothing
<p>I was trying to select everything between adjacent <code>&lt;p&gt;</code>'s, the number of "p" changes every time. And contents in between p tag-pairs could be nothing to anything. Some thing like this:</p> <pre><code> &lt;p&gt;&lt;a href="x"&gt;...ABC...&lt;/a&gt;&lt;/p&gt; &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; Beginning of what I want &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &lt;fieldset&gt;...&lt;/fieldset&gt; &lt;font title="..."&gt;...&lt;/font&gt; sometext without any tag&lt;br&gt; &lt;a href="..."&gt;...&lt;/a&gt; //[0..N] more tags &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; End of what I want &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &lt;p&gt;&lt;a href="x+1"&gt;...ABC...&lt;/a&gt;&lt;/p&gt; [0..N] more "p"'s with similar pattern ("p" with random url in "a") </code></pre> <p>Update:</p> <p>I want to wrap those rogue codes (untagged text) into some div so that I can process them later. Like this:</p> <pre><code>&lt;div id="outer"&gt; &lt;div id="1"&gt; &lt;p&gt;&lt;a href="x"&gt;...ABC...&lt;/a&gt;&lt;/p&gt; &lt;! Beginning of what I want &gt; &lt;fieldset&gt;...&lt;/fieldset&gt; &lt;font title="..."&gt;...&lt;/font&gt; sometext without any tag&lt;br&gt; &lt;a href="..."&gt;...&lt;/a&gt; //[0..N] more tags &lt;! End of what I want &gt; &lt;/div&gt; &lt;div id="2"&gt; &lt;p&gt;&lt;a href="x+1"&gt;...ABC...&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id="3"&gt; //something or nothing &lt;/div&gt; //something or nothing &lt;/div&gt; </code></pre> <p>In order to do that, I had to this code because there is some text without any tags around it:</p> <pre><code> var ps = $("p:contains('ABC')"); ps.each(function(){ if(!($(this).next()[0])){ return true; } var me = $(this); var pa = me.parent().contents(); var nx = me.next("p:contains('ABC')"); //returns [] in this case var i0 = pa.index(me); var i1 = pa.index(nx); if (i1 &gt; i0) { var elements = pa.slice(i0, i1); elements.each(function(){ //Do something }); } }); </code></pre> <p>As marked in the code, the next() function would not return anything even if I change it to next("p"). But if I use me.next().next().next().next().next() I can select the next "p" tag. Why would this happen? How could I do it better? </p>
3
1,211
Django: Warning: Incorrect integer value: 'UnlocksBranch' for column 'type_id' at row 1
<p>I am writing a Django app that pulls data from a Bugzilla database and I am having trouble getting the flags.</p> <pre><code>class Bugzilla_bugs(models.Model): class Meta: db_table = 'bugs' bug_id = models.IntegerField(primary_key=True) ... </code></pre> <p>The flagtypes table which describes all of the different flag names and what they mean.</p> <pre><code>class Bugzilla_flagtypes(models.Model): class Meta: db_table = 'flagtypes' name = models.CharField(max_length=50,unique=True) description = models.TextField() ... </code></pre> <p>The flags table, which is a one-to-many mapping of bug_id, type_id and status values for each bug.</p> <pre><code>class Bugzilla_flags(models.Model): class Meta: db_table = 'flags' type_id = models.ForeignKey(Bugzilla_flagtypes,related_name='flagtype',db_column='type_id',to_field='name') status = models.CharField(max_length=50) bug_id = models.ForeignKey(Bugzilla_bugs,related_name='flaglines',db_column='bug_id',to_field='bug_id') </code></pre> <p>When I try to get the flaglines for a particular bug:</p> <pre><code>bug = Bugzilla_bugs.objects.using('bugzilla').get(bug_id=12345) bug.flaglines.get(type_id="UnlocksBranch") </code></pre> <p>I get the exception:</p> <pre><code>&gt;&gt;&gt; bug.flaglines.get(type_id__name="UnlocksBranch") Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 351, in get num = len(clone) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 122, in __len__ self._fetch_all() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 966, in _fetch_all self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 265, in iterator for row in compiler.results_iter(): File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 700, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 81, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 128, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 176, in execute if not self._defer_warnings: self._warning_check() File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 92, in _warning_check warn(w[-1], self.Warning, 3) Warning: Incorrect integer value: 'UnlocksBranch' for column 'type_id' at row 1 </code></pre> <p>I am trying to use the 'get' method to get the value of the 'status' field in the flags table.</p> <p>If I try to use flaglines to get query the numerical type_id, I get DoesNotExist.</p> <pre><code>&gt;&gt;&gt; bug.flaglines.get(type_id=20) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 460, in __repr__ u = six.text_type(self) File "/home/shubbard/django/cpe/dev/cpe/bugzilla/models.py", line 160, in __unicode__ return unicode(self.type_id) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 572, in __get__ rel_obj = qs.get() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 357, in get self.model._meta.object_name) DoesNotExist: Bugzilla_flagtypes matching query does not exist. </code></pre> <p>I know that the bug has that flag set.</p> <pre><code>mysql&gt; select * from flags where bug_id=12345; +-------+---------+--------+--------+ | id | type_id | status | bug_id | +-------+---------+--------+--------+ | 71732 | 29 | + | 12345 | | 72538 | 41 | + | 12345 | | 72547 | 12 | + | 12345 | | 72548 | 31 | ? | 12345 | | 72549 | 33 | ? | 12345 | | 72550 | 20 | ? | 12345 | | 72551 | 36 | ? | 12345 | +-------+---------+--------+--------+ 7 rows in set (0.01 sec) </code></pre> <p>What am I doing wrong?</p>
3
1,878
Intent Activity not firing?
<p>I'm doing a basic activity of moving from one page to another. Everything was going perfect until I get two pages deep into the app. I used the same exact code for each page class, put the activities in the manifest and made sure all words were spelled correctly, etc., but the intent doesn't do anything when I try to go three pages deep. There are no error messages in the log at all. When I click on a button on the third page, it just turns blue but doesn't move to the next page like the previous pages. Here's my code:</p> <p>from page 1 to 3:</p> <p>Page1:</p> <pre><code> public class MainActivity extends ActionBarActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListenerOnButton(); } public void addListenerOnButton() { final Context context = this; button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, MainMenu.class); startActivity(intent); } }); } } </code></pre> <p>Page 2: has more buttons...</p> <pre><code> public class MainMenu extends ActionBarActivity { Button button; Button button2; Button button3; Button button4; Button button5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_menu); addListenerOnButton(); } public void addListenerOnButton() { final Context context = this; button = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); button3 = (Button) findViewById(R.id.button3); button4 = (Button) findViewById(R.id.button4); button5 = (Button) findViewById(R.id.button5); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, OneMain.class); startActivity(intent); } }); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, TwoMain.class); startActivity(intent); } }); button3.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, ThreeMain.class); startActivity(intent); } }); button4.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, FourMain.class); startActivity(intent); } }); button5.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, FiveMain.class); startActivity(intent); } }); } } </code></pre> <p>Page 3:</p> <pre><code> public class OneMain extends ActionBarActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.one_main); } public void addListenerOnButton() { final Context context = this; button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, Alphabet.class); startActivity(intent); } }); } } </code></pre> <p>I also made sure I put in all the imports. Someone help. I'm stuck :(. </p> <p>Here is the manifest xml:</p> <pre><code> &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.juwar74.alarabic" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name=".MainActivity" android:label="@string/app_name" android:launchMode="singleTop" android:screenOrientation="portrait" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".MainMenu" &gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".OneMain" &gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".TwoMain" &gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".ThreeMain" &gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".FourMain" &gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".FiveMain" &gt; &lt;/activity&gt; &lt;activity android:label="@string/app_name" android:name=".OneVoc" &gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>And here is the code for the Alphabet.class</p> <pre><code> import android.os.Bundle; import android.support.v7.app.ActionBarActivity; public class Alphabet extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alphabet); } </code></pre> <p>}</p>
3
2,558
Different Ising Model results with Fortran and F2PY
<p>I am trying to implement my Fortran code in python using 'f2py'. I derived/extracted a Fortran subroutine from my original Fortran code of Ising model and did calculation using both with same lattice parameters/conditions, etc. But my results are different, which I am unable to understand. Since both should result in similar curves.</p> <p><strong>Output:</strong></p> <ol> <li>Lattice dimensions = 64 x 64</li> <li>Temperature range 0.1 - 5.0</li> <li>External Magnetic Field b = 0</li> <li>coupling constant j = 0</li> <li>No. of MonteCarlo Simulations = 100 + 50</li> </ol> <p>Original Fortran code Result:</p> <p><img src="https://i.stack.imgur.com/RRrqy.png" alt=""></p> <p>F2PY based Result:</p> <p><img src="https://i.stack.imgur.com/m4w2S.png" alt=""></p> <p><strong><em>Code:</em></strong></p> <p>Original Fortran Code:</p> <pre><code>program ising_model implicit none integer, allocatable, dimension(:,:) :: lattice real, allocatable, dimension(:) :: mag integer :: row, col, dim, mcs, sweeps, relax_sweeps real :: j, dE, B, temp, rval ! specify the file name open(12,file='myoutput.txt') ! square - lattice specification dim = 64 ! coupling constant j = 1.0 ! magnetic field B = 0.0 ! number of montecarlo simulations mcs = 100 ! sparse averaging relax_sweeps = 50 allocate(lattice(dim, dim)) allocate(mag(mcs + relax_sweeps)) call spin_array(dim, lattice) !call outputarray(dim, lattice) temp = 0.1 do while (temp .le. 5.0) mag = 0 do sweeps = 1, mcs + relax_sweeps ! One complete sweep do row = 1, dim do col = 1, dim call EnergyCal(row, col, j, B, lattice, dim, dE) call random_number(rval) if (dE .le. 0) then lattice(row,col) = -1 * lattice(row,col) elseif (exp(-1 * dE / temp) .ge. rval) then lattice(row,col) = -1 * lattice(row,col) else lattice(row,col) = +1 * lattice(row,col) end if end do end do mag(sweeps) = abs(sum(lattice))/float((dim * dim)) end do write(12,*) temp, sum(mag(relax_sweeps:))/float(mcs + relax_sweeps) temp = temp + 0.01 end do !print*,'' !call outputarray(dim, lattice) end program ising_model !-------------------------------------------------------------- ! subroutine to print array !-------------------------------------------------------------- subroutine outputarray(dim, array) implicit none integer :: col, row, dim integer, dimension(dim, dim) :: array do row = 1, dim write(*,10) (array(row,col), col = 1, dim) 10 format(100i3) end do end subroutine outputarray !-------------------------------------------------------------- ! subroutine to fill the square lattice with spin randomly !-------------------------------------------------------------- subroutine spin_array(dim, array) implicit none integer :: dim, row, col real :: rval integer, dimension(dim, dim) :: array do row = 1, dim do col = 1, dim call random_number(rval) if (rval .ge. 0.5) then array(row, col) = +1 else array(row, col) = -1 end if end do end do end subroutine spin_array !-------------------------------------------------------------- ! subroutine to calculate energy !-------------------------------------------------------------- subroutine EnergyCal(row, col, j, B, array, dim, dE) implicit none integer, intent(in) :: row, col, dim real, intent(in) :: j, B integer :: left, right, top, bottom integer, dimension(dim, dim), intent(in) :: array real, intent(out) :: dE ! periodic boundry condtions left = col - 1 if (col .eq. 1) left = dim right = col + 1 if (col .eq. dim) right = 1 top = row - 1 if (row .eq. 1) top = dim bottom = row + 1 if (row .eq. dim) bottom = 1 dE = 2 * j * array(row, col) * ((array(top, col) + array(bottom, col) + &amp; array(row, left) + array(row, right)) + B) end subroutine EnergyCal </code></pre> <p>F2PY Extracted Code which is converted using F2PY:</p> <pre><code>subroutine mcmove(inlattice, dim, j, b, temp, finlattice) implicit none integer :: row, col real, intent(in) :: j, B, temp integer, intent(in) :: dim integer, dimension(dim,dim), intent(in) :: inlattice integer, dimension(dim,dim), intent(out) :: finlattice real :: rval, de finlattice = inlattice do row = 1, dim do col = 1, dim call EnergyCal(row, col, j, b, finlattice, dim, dE) call random_number(rval) if (dE .le. 0) then finlattice(row,col) = -1 * finlattice(row,col) elseif (exp(-1 * dE / temp) .ge. rval) then finlattice(row,col) = -1 * finlattice(row,col) else finlattice(row,col) = +1 * finlattice(row,col) end if end do end do end subroutine mcmove !-------------------------------------------------------------- ! subroutine to calculate energy !-------------------------------------------------------------- subroutine EnergyCal(row, col, j, b, array, dim, dE) implicit none integer, intent(in) :: row, col, dim real, intent(in) :: j, b integer :: left, right, top, bottom integer, dimension(dim, dim), intent(in) :: array real, intent(out) :: dE ! periodic boundry condtions left = col - 1 if (col .eq. 1) left = dim right = col + 1 if (col .eq. dim) right = 1 top = row - 1 if (row .eq. 1) top = dim bottom = row + 1 if (row .eq. dim) bottom = 1 dE = 2 * j * array(row, col) * ((array(top, col) + array(bottom, col) + &amp; array(row, left) + array(row, right)) + b) end subroutine EnergyCal </code></pre> <p>Implemented F2PY + Python (if in case needed)</p> <pre><code># required packages import numpy as np import matplotlib.pyplot as plt # fortran module import ising_f90 as fmod print(fmod.__doc__) ## definitions ## def spin_field(rows, cols): ''' generates a configuration with spins -1 and +1''' return np.random.choice([-1, 1], size = (rows, cols)) ## relavant details about the configuration ## # number of monte carlo simulations mcs = 500 # sparse averaging relax_sweeps = 50 # square lattice dimensions dim = 64 # coupling constant j = 1.0 # external magnetic field b = 0.0 # temperature - heat bath lowTemp = 0.1 upTemp = 5.0 # initialisation of lattice with random spins inlattice = spin_field(dim, dim) avg_mg = [] T = [] n = 0 for temp in np.linspace(0.1,5.0,20): mag = np.zeros(mcs + relax_sweeps) for sweeps in range(0, mcs + relax_sweeps): finlattice = fmod.mcmove(inlattice,j,b,temp,dim) mag[sweeps] = abs(sum(sum(finlattice))) / (dim * dim) n += 1 T.append(temp) avg_mg.append(sum(mag[relax_sweeps:]) / (sweeps+1)) plt.plot(T,avg_mg,'k.--',label='{0} x {0}'.format(str(dim))) plt.legend() plt.xlabel('Temperature') plt.ylabel('Magnetization') plt.title('Ising Model 2D') plt.show() </code></pre>
3
3,635
Keypress detection wont work after seemingly unrelated code change
<p>I'm trying to have the Enter key cause a new 'map' to generate for my game, but for whatever reason after implementing full-screen in it the input check won't work anymore. I tried removing the new code and only pressing one key at a time, but it still won't work.</p> <p>Here's the check code and the method it uses, along with the newMap method:</p> <pre><code>public class Game1 : Microsoft.Xna.Framework.Game { // ... protected override void Update(GameTime gameTime) { // ... // Check if Enter was pressed - if so, generate a new map if (CheckInput(Keys.Enter, 1)) { blocks = newMap(map, blocks, console); } // ... } // Method: Checks if a key is/was pressed public bool CheckInput(Keys key, int checkType) { // Get current keyboard state KeyboardState newState = Keyboard.GetState(); bool retType = false; // Return type if (checkType == 0) { // Check Type: Is key currently down? retType = newState.IsKeyDown(key); } else if (checkType == 1) { // Check Type: Was the key pressed? if (newState.IsKeyDown(key)) { if (!oldState.IsKeyDown(key)) { // Key was just pressed retType = true; } else { // Key was already pressed, return false retType = false; } } } // Save keyboard state oldState = newState; // Return result return retType; } // Method: Generate a new map public List&lt;Block&gt; newMap(Map map, List&lt;Block&gt; blockList, Console console) { // Create new map block coordinates List&lt;Vector2&gt; positions = new List&lt;Vector2&gt;(); positions = map.generateMap(console); // Clear list and reallocate memory previously used up by it blockList.Clear(); blockList.TrimExcess(); // Add new blocks to the list using positions created by generateMap() foreach (Vector2 pos in positions) { blockList.Add(new Block() { Position = pos, Texture = dirtTex }); } // Return modified list return blockList; } // ... } </code></pre> <p>I never touched any of the above code for this when it broke - changing keys won't seem to fix it. Despite this, I have camera movement set inside another Game1 method that uses WASD and works perfectly. All I did was add a few lines of code here:</p> <pre><code>private int BackBufferWidth = 1280; // Added these variables private int BackBufferHeight = 800; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = BackBufferWidth; // and this graphics.PreferredBackBufferHeight = BackBufferHeight; // this Content.RootDirectory = "Content"; this.graphics.IsFullScreen = true; // and this } </code></pre> <p>When I try adding text to be displayed in the event the key is pressed, it seems that the If is never even triggered despite the correct key being pressed.</p> <p>It seems that when the CheckInput method attempts to check for 'Enter' having just been pressed, it passes the first check <code>if (newState.IsKeyDown(key))</code> (which returns true) but fails the second <code>if (!oldState.IsKeyDown(key))</code> check. (and returns true, but shouldn't)</p>
3
1,397
Action Mailer Invites Rails 3.1
<p>Using Ryan Bate's RailsCasts #124 Beta Invites (as well as the updated rails 3.1 api) as a crutch, I'm trying to put together my first piece of Action Mailer functionality: inviting someone to collaborate with you on a project. </p> <p>My issue is that the <code>:recipient_email</code> isn't getting saved in the DB and I can't see what I'm missing.</p> <p>config/initializers/setup_mail.rb</p> <pre><code>ActionMailer::Base.smtp_settings = { :address =&gt; "smtp.gmail.com", :port =&gt; 587, :domain =&gt; 'blah.com', :user_name =&gt; 'gmail username', :password =&gt; 'gmail password', :authentication =&gt; 'plain', :enable_starttls_auto =&gt; true } ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development? </code></pre> <p>app/models/invitation.rb</p> <pre><code>class Invitation &lt; ActiveRecord::Base email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i attr_accessor :recipient_email belongs_to :sender, :class_name =&gt; "User", :foreign_key =&gt; "sender_id" has_one :recipient, :class_name =&gt; "User", :foreign_key =&gt; "recipient_id" validates_presence_of :recipient_email, :on =&gt; :create, :message =&gt; "can't be blank" validates :recipient_email, :format =&gt; email_regex validate :recipient_is_not_registered before_create :generate_token def sender_name sender.user_name end def sender_email sender.email end private def recipient_is_not_registered exsisting_user = User.find_by_email(recipient_email) if exsisting_user errors.add :recipient_email, 'is already a member.' else recipient_email end end def generate_token self.token = Digest::SHA1::hexdigest([Time.now, rand].join) end end </code></pre> <p>app/models/user.rb (minus all the auth stuff)</p> <pre><code>class User &lt; ActiveRecord::Base attr_accessible :invitation_token has_many :sent_invitations, :class_name =&gt; "Invitation", :foreign_key =&gt; "sender_id" belongs_to :invitation end </code></pre> <p>app/controller/invitations_controller.rb</p> <pre><code>class InvitationsController &lt; ApplicationController before_filter :authenticate def new @title = "Invite client" @invitation = current_user.sent_invitations.new end def create @invitation = current_user.sent_invitations.create!(params[:invitation]) sender_name = @invitation.sender_name sender_email = @invitation.sender_email if @invitation.save Mailer.invitation(@invitation, signup_url(@invitation.token), sender_name, sender_email).deliver flash[:success] = "Your client has been sent the email. Why not create a booking for them?" redirect_to bookings_path else @title = "Invite client" render :new end end end </code></pre> <p>app/mailers/mailer.rb</p> <pre><code> def invitation(invitation, signup_url, sender_name, sender_email) @signup_url = signup_url @sender_name = sender_name @sender_email = sender_email mail(:to =&gt; invitation.recipient_email, :subject =&gt; "Invitation to Join", :from =&gt; @sender_email) end </code></pre> <p>app/views/invitations/_invitation_form.html.erb</p> <pre><code>&lt;%= form_for @invitation do |f| %&gt; &lt;%= render 'shared/error_messages', :object =&gt; f.object %&gt; &lt;%= f.hidden_field :email_token %&gt; &lt;br /&gt; &lt;div class="field"&gt; &lt;%= f.label :recipient_email, "Client's email address" %&gt; &lt;%= f.email_field :recipient_email %&gt; &lt;/div&gt; &lt;br /&gt; &lt;div class="action"&gt; &lt;%= f.submit "Send invitation", :class =&gt; "a small white button radius" %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>The SQL log showing that the :recipient_email isn't getting saved</p> <pre><code>Started POST "/invitations" for 127.0.0.1 at 2011-12-14 21:27:11 +1100 Processing by InvitationsController#create as HTML Parameters: {"utf8"=&gt;"✓", "authenticity_token"=&gt;"7/SGZypGXtf9ShlcjC6o8ZRj2Qe4OJTHdjis2/m3ulc=", "invitation"=&gt;{"recipient_email"=&gt;"users@email.com"}, "commit"=&gt;"Send invitation"} User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 (0.1ms) BEGIN User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'users@email.com' LIMIT 1 SQL (0.4ms) INSERT INTO "invitations" ("created_at", "recipient_email", "sender_id", "sent_at", "token", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["created_at", Wed, 14 Dec 2011 10:27:11 UTC +00:00], ["recipient_email", nil], ["sender_id", 1], ["sent_at", nil], ["token", "56fba1647d40b53090dd49964bfdf060228ecb2d"], ["updated_at", Wed, 14 Dec 2011 10:27:11 UTC +00:00]] (10.2ms) COMMIT User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 (0.1ms) BEGIN User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'users@email.com' LIMIT 1 (0.1ms) COMMIT Rendered mailer/invitation.text.erb (0.4ms) Sent mail to users@email.com (7ms) Date: Wed, 14 Dec 2011 21:27:11 +1100 From: admin@email.com </code></pre>
3
2,210
How to reach local server runing nightwatch tests against docker selenium and local app?
<h3>Nightwatch</h3> <p><strong>nightwatch --version</strong></p> <pre><code> v0.9.14 </code></pre> <p><strong>config</strong></p> <pre><code>{ "src_folders": [ "test/e2e" ], "selenium": { "start_process": false, "port": 4444 }, "test_settings": { "default": { "launch_url": "http://localhost:8080", "selenium_port": 4444, "selenium_host": "172.17.0.2", "silent": true }, "dev": { "desiredCapabilities": { "browserName": "chrome" }, "globals": { "baseUrl": "http://localhost:8080/" } } } } </code></pre> <h3>Docker</h3> <p><strong>image</strong></p> <pre><code>$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8afbc5b1ee50 selenium/standalone-chrome "/opt/bin/entry_po..." 25 minutes ago Up 25 minutes 0.0.0.0:32770-&gt;4444/tcp nightwatch-server </code></pre> <p><strong>network</strong></p> <pre><code>$ docker inspect nightwatch-server --format "{{ json .NetworkSettings.Networks }}" | python -m json.tool { "bridge": { "Aliases": null, "EndpointID": "7e621587f6ecbaa9b9d73aee601f647bebd76346b16d9d88e27c8ac7671e503d", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAMConfig": null, "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "Links": null, "MacAddress": "02:42:ac:11:00:02", "NetworkID": "363882b98acd8d8fb0756a296610a0135e3ebde4feae8bdceaa7917939d79752" } } </code></pre> <h3>Test</h3> <pre><code>module.exports = { 'index page': function (client) { client .url('http://localhost:8080') .waitForElementVisible('body', 1000) .assert.title('Google') .end(); } }; </code></pre> <h3>Result</h3> <pre><code>[Index] Test Suite ====================== Running: index page ✔ Element &lt;body&gt; was visible after 100 milliseconds. ✖ Testing if the page title equals "Google". - expected "Google" but got: "localhost" at Object.index page (/data/projects/apidae/frontend/static_src/test/e2e/index.js:6:12) at _combinedTickCallback (internal/process/next_tick.js:73:7) FAILED: 1 assertions failed and 1 passed (674ms) _________________________________________________ TEST FAILURE: 1 assertions failed, 1 passed. (746ms) ✖ index - index page (674ms) Testing if the page title equals "Google". - expected "Google" but got: "localhost" at Object.index page (/data/projects/apidae/frontend/static_src/test/e2e/index.js:6:12) at _combinedTickCallback (internal/process/next_tick.js:73:7) </code></pre> <h3>Question</h3> <p>Why can't I reach my local server?</p>
3
2,704
Swapping rows in 2-D array C++
<p>So yeah, I wrote a program which sort rows of two-dimensional array in ascending order according to sum of all positive even elements in every row, BUT it does not work properly. Sometimes it can swap rows correctly but mostly it feels like this program only swap two adjacent rows or something like that.</p> <p>Probably, there is a problem with incorrect using bubble sort for 2-d arrays. Here is the function where I did most things:</p> <pre><code>void print(int** arr, int rows, int columns) { for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { cout &lt;&lt; setw(7) &lt;&lt; arr[i][j]; } cout &lt;&lt; endl; } int* sumRows = new int[rows]; int sum = 0; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { if (arr[i][j] &gt; 0 &amp;&amp; arr[i][j] % 2 == 0) { //cout &lt;&lt; setw(7) &lt;&lt; arr[i][j]; sum = sum + arr[i][j]; } } cout &lt;&lt; endl &lt;&lt; &quot;Sum of positive even elements in the row &quot; &lt;&lt; i + 1 &lt;&lt; &quot; = &quot; &lt;&lt; sum; sumRows[i] = sum; sum = 0; } cout &lt;&lt; endl &lt;&lt; &quot;Array of sums: &quot;; for (int i = 0; i &lt; rows; i++) { cout &lt;&lt; setw(7) &lt;&lt; sumRows[i]; } //for (int i = 0; i &lt; r; i++) cout &lt;&lt; setw(7) &lt;&lt; sumRows[i]; cout &lt;&lt; endl; bool swapped; for (int i = 0; i &lt; rows - 1; i++) { swapped = false; for (int j = 0; j &lt; columns - 1; j++) { for (int k = 0; k &lt; rows - i - 1; k++) { if (sumRows[k] &gt; sumRows[k + 1]) { swap(arr[k][j], arr[k + 1][j]); swapped = true; } } } if (swapped == false) break; } cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; &quot;Swapped array:&quot; &lt;&lt; endl; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { cout &lt;&lt; setw(7) &lt;&lt; arr[i][j]; } cout &lt;&lt; endl; } } </code></pre> <p>Full code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;time.h&gt; #include &lt;conio.h&gt; #include &lt;algorithm&gt; using namespace std; int** createMalloc(int, int); int** createCalloc(int rows, int columns); int** createNew(int rows, int columns); void deleteNew(int** arr, int rows); void init(int**, int, int); void freeMemory(int**, int); void print(int**, const int, const int); void initPrint(int** arr, int rows, int columns); void main() { int rowCount, colCount; cout &lt;&lt; &quot;Enter number of rows: &quot;; cin &gt;&gt; rowCount; cout &lt;&lt; &quot;Enter number of columns: &quot;; cin &gt;&gt; colCount; cout &lt;&lt; &quot; Array creation algorithm\n&quot;; start: cout &lt;&lt; &quot;Input number : \n1 for malloc\n2 for calloc\n3 for new\n&quot;; int k; cin &gt;&gt; k; switch (k) { case 1: { int** a = createMalloc(rowCount, colCount); initPrint(a, rowCount, colCount); freeMemory(a, rowCount); break; } case 2: { int** a = createCalloc(rowCount, colCount); initPrint(a, rowCount, colCount); freeMemory(a, rowCount); break; } case 3: { int** a = createNew(rowCount, colCount); initPrint(a, rowCount, colCount); deleteNew(a, rowCount); break; } default:cout &lt;&lt; &quot;Input 1, 2 or 3, please.&quot;; cout &lt;&lt; endl &lt;&lt; endl; goto start; } cout &lt;&lt; endl &lt;&lt; endl; } int** createMalloc(int rows, int columns) { int** arr = (int**)malloc(rows * sizeof(int*)); for (int i = 0; i &lt; rows; i++) { arr[i] = (int*)malloc(columns * sizeof(int)); } return arr; } int** createCalloc(int rows, int columns) { int** arr = (int**)calloc(rows, sizeof(int*)); for (int i = 0; i &lt; rows; i++) { arr[i] = (int*)calloc(columns, sizeof(int)); } return arr; } int** createNew(int rows, int columns) { int** arr = new int* [rows]; for (int i = 0; i &lt; rows; i++) { arr[i] = new int[columns]; } return arr; } void initPrint(int** arr, int rows, int columns) { init(arr, rows, columns); print(arr, rows, columns); } void init(int** arr, int rows, int columns) { const int Low = -10, High = 10; srand((unsigned)time(NULL)); for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { arr[i][j] = Low + rand() % (High - Low + 1); } } } void freeMemory(int** arr, int rows) { for (int i = 0; i &lt; rows; i++) { free(arr[i]); } free(arr); } void deleteNew(int** arr, int rows) { for (int i = 0; i &lt; rows; i++) { delete[] arr[i]; } delete[] arr; } void print(int** arr, int rows, int columns) { for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { cout &lt;&lt; setw(7) &lt;&lt; arr[i][j]; } cout &lt;&lt; endl; } int* sumRows = new int[rows]; int sum = 0; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { if (arr[i][j] &gt; 0 &amp;&amp; arr[i][j] % 2 == 0) { //cout &lt;&lt; setw(7) &lt;&lt; arr[i][j]; sum = sum + arr[i][j]; } } cout &lt;&lt; endl &lt;&lt; &quot;Sum of positive even elements in the row &quot; &lt;&lt; i + 1 &lt;&lt; &quot; = &quot; &lt;&lt; sum; sumRows[i] = sum; sum = 0; } cout &lt;&lt; endl &lt;&lt; &quot;Array of sums: &quot;; for (int i = 0; i &lt; rows; i++) { cout &lt;&lt; setw(7) &lt;&lt; sumRows[i]; } //for (int i = 0; i &lt; r; i++) cout &lt;&lt; setw(7) &lt;&lt; sumRows[i]; cout &lt;&lt; endl; bool swapped; for (int i = 0; i &lt; rows - 1; i++) { swapped = false; for (int j = 0; j &lt; columns - 1; j++) { for (int k = 0; k &lt; rows - i - 1; k++) { if (sumRows[k] &gt; sumRows[k + 1]) { swap(arr[k][j], arr[k + 1][j]); swapped = true; } } } //IF no two elements were swapped by inner loop, then break if (swapped == false) break; } cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; &quot;Swapped array:&quot; &lt;&lt; endl; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { cout &lt;&lt; setw(7) &lt;&lt; arr[i][j]; } cout &lt;&lt; endl; } } </code></pre> <p>P.S. Two-dimensional arrays must be necessarily dynamic ones. Besides, I needed to give user a choice of creating an array with <code>malloc</code>, <code>calloc</code> or <code>new</code>. Also, cannot do this task using <code>vector</code> yet.</p> <p>P.P.S. I know that most of you will find it easy but for me it is definitely not as this task is my homework in a university and we have not learnt any sorting algorithms. Anyway, when I asked the teacher how can I sort rows like that, he told me to use bubble sort so here I am</p>
3
3,651
What is the best way to compare time periods and how do I structure my database for it?
<p>I'm looking for a way, that if my app says "Looking for person available from <strong>March 3rd, 2016 8:00 am to March 3rd, 2016 3:00 pm</strong>" to match it with a person that might be available from <strong>March 3rd, 2016 7:00 am to March 3rd, 2016 16:00 pm.</strong></p> <p>Now this is a just a snapshot, it has to scale for infinite times/dates for example a person might be available from <strong>March 3rd, 2016 7:00 am to 9:00 am, then again from 2:00pm to 8:00pm</strong>, so I'd have to have a way to filter people like this as a not complete match.</p> <p>What I have so far is ONE TABLE that holds the dates to match against, so for example March 3rd 8 - 3pm, March 4th 8 - 3pm, March 5th 8 - 3pm..etc..</p> <p>Another table that holds people and their availability as child elements, but I am not sure how to structure this part to make it easy and efficient to match inside loops with the other table.</p> <p>Right now, in my employee table I have one field "March 3rd" and then another field with hours/minutes available as an array so for example "8:00, 8:15, 8:30, 8:45, 9:00...etc... The hours increments have to be in 15 min periods, so I can't just put 8am - 5pm for example...especially if the person is available during certain periods of the day...</p> <p>Here is what my "employee select your availability looks like" </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table class="table table-bordered table-hover employe-availability-table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="warning"&gt; Hour &lt;/th&gt; &lt;th class="warning"&gt; 15 &lt;/th&gt; &lt;th class="warning"&gt; 30 &lt;/th&gt; &lt;th class="warning"&gt; 45 &lt;/th&gt; &lt;th class="warning"&gt; Hour &lt;/th&gt; &lt;th class="warning"&gt; 15 &lt;/th&gt; &lt;th class="warning"&gt; 30 &lt;/th&gt; &lt;th class="warning"&gt; 45 &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td data-hour="0" data-minute="00" data-day-period="N" class="hour"&gt; 0:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="0:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="0" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="0:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="0" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="0:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="0" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="0:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="12" data-minute="00" data-day-period="J" class="hour"&gt; 12:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="12:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="12" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="12:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="12" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="12:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="12" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="12:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="1" data-minute="00" data-day-period="N" class="hour"&gt; 1:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="1:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="1" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="1:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="1" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="1:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="1" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="1:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="13" data-minute="00" data-day-period="J" class="hour"&gt; 13:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="13:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="13" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="13:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="13" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="13:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="13" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="13:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="2" data-minute="00" data-day-period="N" class="hour"&gt; 2:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="2:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="2" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="2:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="2" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="2:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="2" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="2:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="14" data-minute="00" data-day-period="J" class="hour"&gt; 14:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="14:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="14" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="14:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="14" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="14:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="14" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="14:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="3" data-minute="00" data-day-period="N" class="hour"&gt; 3:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="3:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="3" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="3:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="3" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="3:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="3" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="3:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="15" data-minute="00" data-day-period="S" class="hour"&gt; 15:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="15:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="15" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="15:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="15" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="15:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="15" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="15:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="4" data-minute="00" data-day-period="N" class="hour"&gt; 4:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="4:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="4" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="4:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="4" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="4:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="4" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="4:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="16" data-minute="00" data-day-period="S" class="hour"&gt; 16:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="16:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="16" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="16:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="16" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="16:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="16" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="16:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="5" data-minute="00" data-day-period="N" class="hour"&gt; 5:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="5:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="5" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="5:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="5" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="5:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="5" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="5:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="17" data-minute="00" data-day-period="S" class="hour"&gt; 17:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="17:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="17" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="17:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="17" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="17:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="17" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="17:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="6" data-minute="00" data-day-period="N" class="hour"&gt; 6:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="6:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="6" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="6:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="6" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="6:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="6" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="6:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="18" data-minute="00" data-day-period="S" class="hour"&gt; 18:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="18:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="18" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="18:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="18" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="18:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="18" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="18:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="7" data-minute="00" data-day-period="J" class="hour"&gt; 7:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="7:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="7" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="7:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="7" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="7:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="7" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="7:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="19" data-minute="00" data-day-period="S" class="hour"&gt; 19:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="19:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="19" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="19:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="19" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="19:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="19" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="19:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="8" data-minute="00" data-day-period="J" class="hour"&gt; 8:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="8:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="8" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="8:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="8" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="8:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="8" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="8:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="20" data-minute="00" data-day-period="S" class="hour"&gt; 20:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="20:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="20" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="20:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="20" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="20:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="20" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="20:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="9" data-minute="00" data-day-period="J" class="hour"&gt; 9:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="9:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="9" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="9:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="9" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="9:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="9" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="9:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="21" data-minute="00" data-day-period="S" class="hour"&gt; 21:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="21:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="21" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="21:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="21" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="21:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="21" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="21:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="10" data-minute="00" data-day-period="J" class="hour"&gt; 10:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="10:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="10" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="10:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="10" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="10:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="10" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="10:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="22" data-minute="00" data-day-period="S" class="hour"&gt; 22:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="22:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="22" data-minute="15" data-day-period="S"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="22:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="22" data-minute="30" data-day-period="S"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="22:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="22" data-minute="45" data-day-period="S"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="22:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-hour="11" data-minute="00" data-day-period="J" class="hour"&gt; 11:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="11:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="11" data-minute="15" data-day-period="J"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="11:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="11" data-minute="30" data-day-period="J"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="11:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="11" data-minute="45" data-day-period="J"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="11:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour="23" data-minute="00" data-day-period="N" class="hour"&gt; 23:00 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="23:00" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="23" data-minute="15" data-day-period="N"&gt; 15 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="23:15" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="23" data-minute="30" data-day-period="N"&gt; 30 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="23:30" style="display: inline-block;"&gt;&lt;/td&gt; &lt;td data-hour-ref="23" data-minute="45" data-day-period="N"&gt; 45 &lt;input type="checkbox" class="hide undoUniform" name="field_108890_tab_14" value="23:45" style="display: inline-block;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>Any nudge in the right direction regarding my logic and setup would be greatly appreciated. </p>
3
9,944
How to use REST API mark tests as fail?
<p>I use this <a href="https://www.browserstack.com/docs/automate/selenium/view-test-results/mark-tests-as-pass-fail" rel="nofollow noreferrer">https://www.browserstack.com/docs/automate/selenium/view-test-results/mark-tests-as-pass-fail</a> as reference. But I not able to let the REST API shows 'fail'. May I know what is my problem? I also attached the text logs, it shows 'Run JavaScript......' , is it correct?</p> <pre><code>import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.JavascriptExecutor; public class test1 { public WebDriver driver = null; public static final String USERNAME = &quot;&quot;; public static final String AUTOMATE_KEY = &quot;&quot;; public static final String URL = &quot;https://&quot; + USERNAME + &quot;:&quot; + AUTOMATE_KEY + &quot;@hub-cloud.browserstack.com/wd/hub&quot;; @BeforeClass public void setup() throws MalformedURLException { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(&quot;os&quot;, &quot;Windows&quot;); caps.setCapability(&quot;os_version&quot;, &quot;10&quot;); caps.setCapability(&quot;browser&quot;, &quot;Chrome&quot;); caps.setCapability(&quot;browser_version&quot;, &quot;80&quot;); caps.setCapability(&quot;name&quot;, &quot;Test1&quot;); driver = new RemoteWebDriver(new URL(URL), caps); } @Test (priority = 1) public void test_1() { driver.get(&quot;https://youtube.com&quot;); String actualUrl = &quot;https://www.youtube.com/&quot;; String expectedUrl = &quot;https://www.youtube.com/&quot;; Assert.assertEquals(actualUrl, expectedUrl); JavascriptExecutor jse = (JavascriptExecutor)driver; if (actualUrl.equals(expectedUrl)) { jse.executeScript(&quot;browserstack_executor: {\&quot;action\&quot;: \&quot;setSessionStatus\&quot;, \&quot;arguments\&quot;: {\&quot;status\&quot;: \&quot;passed\&quot;, \&quot;reason\&quot;: \&quot;Url matched!\&quot;}}&quot;); } else { jse.executeScript(&quot;browserstack_executor: {\&quot;action\&quot;: \&quot;setSessionStatus\&quot;, \&quot;arguments\&quot;: {\&quot;status\&quot;:\&quot;failed\&quot;, \&quot;reason\&quot;: \&quot;Url not matched\&quot;}}&quot;); } } @Test (priority = 2) public void test_2() { driver.get(&quot;https://google.com&quot;); String actualUrl = &quot;https://www.google.com/&quot;; String expectedUrl = &quot;https://www.youtube1.com/&quot;; Assert.assertEquals(actualUrl, expectedUrl); JavascriptExecutor jse = (JavascriptExecutor)driver; if (actualUrl.equals(expectedUrl)) { jse.executeScript(&quot;browserstack_executor: {\&quot;action\&quot;: \&quot;setSessionStatus\&quot;, \&quot;arguments\&quot;: {\&quot;status\&quot;: \&quot;passed\&quot;, \&quot;reason\&quot;: \&quot;Url matched!\&quot;}}&quot;); } else { jse.executeScript(&quot;browserstack_executor: {\&quot;action\&quot;: \&quot;setSessionStatus\&quot;, \&quot;arguments\&quot;: {\&quot;status\&quot;:\&quot;failed\&quot;, \&quot;reason\&quot;: \&quot;Url not matched\&quot;}}&quot;); } } @AfterClass public void tearDown() { driver.quit(); } } </code></pre> <p>I tested with youtube and google url.</p>
3
1,616
React/Redux Can't update initial state / undefined problem
<p>I am trying to update my state and getting it to render.</p> <p>Below I am calling my state from the reducer.js file and displaying the initial list fine.</p> <pre><code>&lt;div className={classes.resultborder}&gt; {this.props.transInput.map(data =&gt; { return ( &lt;Inputs key={data.id} xParty={data.xParty} zParty={data.zParty} yAction={data.yAction} amount={data.amount} deleteItem={() =&gt; this.deleteItem(data.id)}/&gt; ); })} &lt;/div&gt; </code></pre> <p>At the bottom of my parent app, I have</p> <pre><code>const mapStateToProps = state =&gt; { return { transInput: state.transactionInputs }; }; const mapDispatchToProps = dispatch =&gt; { return { submitResults: () =&gt; dispatch({type: 'SUBMIT', x: { xParty: 'Henry', yAction: 'Funds', zParty: 'Elizbath' }}) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Transactions); </code></pre> <p>I have hard coded my <code>submitResults</code> because I have not yet been able to update my state and display, this is for simplicity.</p> <p>I am calling <code>submitResults</code> in a button</p> <pre><code>submitResults={this.props.submitResults} </code></pre> <p>Now below is my whole reducer</p> <pre><code>const initialReducer = { transactionInputs: [ {id: 1, xParty: "statePaul", yAction: "Funds", zParty: "stateSandra", amount: 100}, {id: 2, xParty: "stateEmily", yAction: "Loans", zParty: "stateJohn", amount: 200}, {id: 3, xParty: "stateMatt", yAction: "Repays", zParty: "stateMicheal", amount: 300}, ], emptyInputs: false, toggle: false }; const reducer = (state = initialReducer, action) =&gt; { console.log(initialReducer.transactionInputs); if(action.type === 'SUBMIT'){ return{ ...state, xParty: state.xParty.concat(action.x) } } return state; }; export default reducer; </code></pre> <p>When I press te button to run <code>submitResults</code> I get the following error message <code>TypeError: Cannot read property 'concat' of undefined</code></p> <p>I want to be able to update my initial state and have it displayed (currently I do believe if I can get the initial state to update then the display will re-render fine).</p> <p>I am not completely sure why this is not working but I do believe it's in my reducer.js file has something to dow ith how I'm returning my state.</p> <p>I apprentice any suggestions.</p>
3
1,222
Hashing collision keys to next in the hashtable
<p>I have a problem in linking the collided keys, the latest key will override the previous key that was linked to the table. I have hard coded for a collision to see if the keys that collide are saved in the linked list correctly, but its not saved correctly. Here is the involved part of the code. </p> <pre><code>typedef struct student { char name[10]; char sex[4]; char number[12]; char mail[50]; bool filled; struct student *next; }ST; void Readfromfile(ST *hashTable)//Read data from txt file and build hash table { FILE *ft; ft = fopen("info.txt", "r"); if(!ft) { printf("FAILED TO OPEN FILE\n"); return; } char *buffer = malloc(sizeof(char)*43); char cp_name[10], cp_sex[4], cp_num[12], cp_mail[50]; int st_index =0, i; while((fgets(buffer, sizeof(buffer)*50, ft)) != NULL) { if(strlen(buffer) != 0) sscanf(buffer, "%s %s %s %s", cp_name, cp_sex, cp_num, cp_mail); printf("READ: %s", buffer); int hash_value = Hashfun(cp_num); ST *current = malloc(sizeof(ST)); strcpy(current-&gt;name, cp_name); strcpy(current-&gt;sex, cp_sex); strcpy(current-&gt;number, cp_num); strcpy(current-&gt;mail, cp_mail); current-&gt;filled = true; current-&gt;next = NULL; ST *tempHash = &amp;hashTable[hash_value]; if(tempHash-&gt;filled == true) { printf("THERE IS A COLLISION at %d SAVING AT NEXT \n\n\n",hash_value); while(tempHash!= NULL) { printf("I AM PROBLEM HEREEEEEEEEEEEEEEEEEEEEEEE\n"); printf("PASSING BY: %s %s %s %s at %d\n",tempHash-&gt;name,tempHash-&gt;sex, tempHash-&gt;number,tempHash-&gt;mail, hash_value); tempHash = tempHash-&gt;next; } tempHash = current; printf("HASHED NEXT: %s %s %s %s at %d\n",tempHash-&gt;name,tempHash-&gt;sex, tempHash-&gt;number, tempHash-&gt;mail, hash_value); } else { strcpy(tempHash-&gt;name, cp_name); strcpy(tempHash-&gt;sex, cp_sex); strcpy(tempHash-&gt;mail, cp_mail); strcpy(tempHash-&gt;number, cp_num); tempHash-&gt;filled = true; tempHash-&gt;next = NULL; printf("HASHED: %s %s %s %s at %d\n",tempHash-&gt;name,tempHash-&gt;sex, tempHash-&gt;number, tempHash-&gt;mail, hash_value); } } } </code></pre>
3
1,277
Screen does not appears after few seconds
<p>I want the GameOverScreen to appear after few seconds from when the plane collided with one of the rocks, but whenever I run the game , GameOverScreen appears immediately. please help me solve this. Here's the code.</p> <pre><code>package com.ravicake.motiontest; import java.util.Iterator; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.TimeUtils; public class GameScreen implements Screen, InputProcessor { final MotionTestGame motionTestGame; Texture rockImage; Texture rockImageR; Texture playerImage; TextureAtlas planeAtlas; TextureAtlas sideRockAtlas; TextureAtlas explosionAtlas; Animation planeAnimation; Animation sideRockAnimation; Animation explosionAnimation; Texture bg; Sound dropSound; Sound bombSound; // Music rainMusic; OrthographicCamera camera; Rectangle player; Array&lt;Rectangle&gt; rocksArray; Array&lt;Rectangle&gt; rocksArrayR; long lastRockTime; long lastRockTimeR; long explosionTime; int speed = 400; int lives = 3; public float posX, posY; float elapsedTime = 0; boolean repeatAnimation = true; boolean gameover = false; public void setDropsCollected(int dropsCollected) { } public GameScreen(final MotionTestGame game) { motionTestGame = game; Gdx.input.setInputProcessor(this); rockImage = new Texture(Gdx.files.internal("rockb.png")); rockImageR = new Texture(Gdx.files.internal("rocka.png")); planeAtlas = new TextureAtlas(Gdx.files.internal("planeAtlas.pack")); sideRockAtlas = new TextureAtlas(Gdx.files.internal("siderock.pack")); explosionAtlas = new TextureAtlas(Gdx.files.internal("explosionAtlas.pack")); planeAnimation = new Animation(1 / 12f, planeAtlas.getRegions()); sideRockAnimation = new Animation(1 / 9f, sideRockAtlas.getRegions()); explosionAnimation = new Animation(1 / 9f, explosionAtlas.getRegions()); // buck = new Texture(Gdx.files.internal("petrol.png")); bg = new Texture(Gdx.files.internal("background1.png")); // load the sound effect and the rain background "music" // dropSound = Gdx.audio.newSound(Gdx.files.internal("pick.wav")); // bombSound = Gdx.audio.newSound(Gdx.files.internal("bomb.wav")); // rainMusic = Gdx.audio.newMusic(Gdx.files.internal("flute.ogg")); // rainMusic.setLooping(true); // load preference file // create the camera and the SpriteBatch camera = new OrthographicCamera(); camera.setToOrtho(false, 480, 800); // create a Rectangle to logically represent the player player = new Rectangle(); player.x = 480 / 2 - 64 / 2; player.y = 650; player.width = 128; player.height = 128; // create the rocks array and spawn the first rock rocksArray = new Array&lt;Rectangle&gt;(); rocksArrayR = new Array&lt;Rectangle&gt;(); spawnRocks(); spawnRocksR(); } private void spawnRocks() { // TODO Auto-generated method stub Rectangle rock = new Rectangle(); rock.x = MathUtils.random(-150, -100); rock.y = -130; rock.width = 256; rock.height = 128; rocksArray.add(rock); lastRockTime = TimeUtils.nanoTime() + 1000000000 * MathUtils.random(1, 2); } private void spawnRocksR() { Rectangle rockR = new Rectangle(); rockR.x = MathUtils.random(300, 400); rockR.y = -130; rockR.width = 256; rockR.height = 128; rocksArrayR.add(rockR); lastRockTimeR = TimeUtils.nanoTime() + 1000000000 * MathUtils.random(1, 2); } private void crashed() { planeAnimation = explosionAnimation; explosionTime = TimeUtils.nanoTime(); System.out.println("timer started"); } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0.5f, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // tell the camera to update its matrices. camera.update(); // tell the SpriteBatch to render in the // coordinate system specified by the camera. motionTestGame.batch.setProjectionMatrix(camera.combined); elapsedTime += Gdx.graphics.getDeltaTime(); // begin a new batch and draw the player and everything // motionTestGame.batch.begin(); motionTestGame.batch.draw(bg, 0, 0); motionTestGame.font.setScale((float) 1.5); // game.font.draw(game.batch, "Level: " + level, 710, 470); motionTestGame.font.draw(motionTestGame.batch, "DROPED: " + (3 - lives), 300, 770); motionTestGame.batch.draw( planeAnimation.getKeyFrame(elapsedTime, repeatAnimation), player.x, player.y); motionTestGame.batch.draw( sideRockAnimation.getKeyFrame(elapsedTime, repeatAnimation), -165, 0); motionTestGame.batch.draw( sideRockAnimation.getKeyFrame(elapsedTime, repeatAnimation), 413, 0); for (Rectangle rock : rocksArray) { motionTestGame.batch.draw(rockImage, rock.x, rock.y); } for (Rectangle rockR : rocksArrayR) { motionTestGame.batch.draw(rockImageR, rockR.x, rockR.y); } motionTestGame.batch.end(); // / accelerometer controls player.x -= Gdx.input.getAccelerometerX() * 3; // process user input if (Gdx.input.isTouched()) { Vector3 touchPos = new Vector3(); touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); camera.unproject(touchPos); player.x = touchPos.x - 64 / 2; } if (Gdx.input.isKeyPressed(Keys.LEFT)) player.x -= 400 * Gdx.graphics.getDeltaTime(); if (Gdx.input.isKeyPressed(Keys.RIGHT)) player.x += 400 * Gdx.graphics.getDeltaTime(); // make sure the player stays within the screen bounds if (player.x &lt; 0) player.x = 0; if (player.x &gt; 480 - 64) player.x = 480 - 64; // check if we need to create a new rocks if (TimeUtils.nanoTime() - lastRockTime &gt; 1000000000) { spawnRocks(); } if (TimeUtils.nanoTime() - lastRockTimeR &gt; 1000000000f) { spawnRocksR(); } if (TimeUtils.nanoTime() - explosionTime &gt; 7000000000f) { gameover=true; } // ////////// left side rocks Iterator&lt;Rectangle&gt; iter = rocksArray.iterator(); while (iter.hasNext()) { Rectangle rock = iter.next(); rock.y += speed * Gdx.graphics.getDeltaTime(); if (rock.y + 128 &gt; 1000) { iter.remove(); } if (rock.overlaps(player)) { crashed(); //repeatAnimation = false; } } // //////// right side rocks Iterator&lt;Rectangle&gt; iter2 = rocksArrayR.iterator(); while (iter2.hasNext()) { Rectangle rockR = iter2.next(); rockR.y += speed * Gdx.graphics.getDeltaTime(); if (rockR.y + 128 &gt; 1000) { iter2.remove(); } if (rockR.overlaps(player)) { crashed(); } } if(gameover){ motionTestGame.setScreen((new GameOverScreen(motionTestGame))); dispose(); } } @Override public void resize(int width, int height) { } @Override public void show() { // start the playback of the background music // when the screen is shown // rainMusic.play(); } @Override public void hide() { } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { // playerImage.dispose(); rockImage.dispose(); rockImageR.dispose(); // dropSound.dispose(); // bombSound.dispose(); sideRockAtlas.dispose(); planeAtlas.dispose(); // rainMusic.dispose(); bg.dispose(); } @Override public boolean keyDown(int keycode) { return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } </code></pre> <p>}</p>
3
3,355
Pellet reasoner crashes when classifying ontology with datatype restriction as pattern
<p>I have an ontology that defines a new data type as pattern restriction on string type. This data type is then used as a property range restriction. Then a class is defined as a restriction on this property:</p> <pre><code>@prefix : &lt;http://test.com/prop#&gt; . @prefix owl: &lt;http://www.w3.org/2002/07/owl#&gt; . @prefix rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; . @prefix xml: &lt;http://www.w3.org/XML/1998/namespace&gt; . @prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . @prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; . @base &lt;http://test.com/prop&gt; . &lt;http://test.com/prop&gt; rdf:type owl:Ontology . :MyType rdf:type rdfs:Datatype ; owl:equivalentClass [ rdf:type rdfs:Datatype ; owl:onDatatype xsd:string ; owl:withRestrictions ( [ xsd:pattern "[a-zA-Z]*" ] ) ] . # Properties :hasProperty rdf:type owl:ObjectProperty . :hasValue rdf:type owl:DatatypeProperty . # Classes :BaseClass rdf:type owl:Class . :BaseProperty rdf:type owl:Class . :MyClass rdf:type owl:Class ; owl:equivalentClass [ rdf:type owl:Class ; owl:intersectionOf ( :BaseClass [ rdf:type owl:Restriction ; owl:onProperty :hasProperty ; owl:someValuesFrom :MyProperty ] ) ] ; rdfs:subClassOf :BaseClass . :MyProperty rdf:type owl:Class ; owl:equivalentClass [ rdf:type owl:Class ; owl:intersectionOf ( :BaseProperty [ rdf:type owl:Restriction ; owl:onProperty :hasValue ; owl:someValuesFrom :MyType ] ) ] ; rdfs:subClassOf :BaseProperty . # Individuals :Ind1 rdf:type :BaseClass , owl:NamedIndividual ; :hasProperty :Prop1 . :Prop1 rdf:type :BaseProperty , owl:NamedIndividual ; :hasValue "Maier" . </code></pre> <p>The Protege crashes while classifying this ontology with Pellet reasoner:</p> <pre><code>UnsupportedOperationException: null com.clarkparsia.pellet.datatypes.types.text.RestrictedTextDatatype.applyConstrainingFacet(RestrictedTextDatatype.java:93) com.clarkparsia.pellet.datatypes.DatatypeReasonerImpl.getDataRange(DatatypeReasonerImpl.java:440) </code></pre> <p>The FaCT++ reasoner failed with exception:</p> <pre><code>ReasonerInternalException: Unsupported datatype 'http://test.com/prop#MyType' uk.ac.manchester.cs.factplusplus.FaCTPlusPlus.getBuiltInDataType(Native Method) </code></pre> <p>The Pellet seems only to have trouble with the pattern as a restriction. The FaCT++ seems to have trouble with a user defined datatype.</p> <p>Do I have errors in the ontology or the reasoners are not able to classify such pattern restriction?</p>
3
1,877
android StringBuilder to save as .txt file on sdcard
<p>I need help! can someone see my line of codes here. Currently im writing a code to save calllogs into a .txt file and save it to sdcard. It can run but not saving the stringbuilder variable to sdcard. Im new to android programming. </p> <pre><code>package com.example.calllog; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.Date; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.provider.CallLog; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Cursor mCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null); int number = mCursor.getColumnIndex(CallLog.Calls.NUMBER); int date = mCursor.getColumnIndex(CallLog.Calls.DATE); int duration = mCursor.getColumnIndex(CallLog.Calls.DURATION); int type = mCursor.getColumnIndex(CallLog.Calls.TYPE); StringBuilder sb = new StringBuilder(); while (mCursor.moveToNext()) { String phnumber = mCursor.getString(number); String callduration = mCursor.getString(duration); String calltype = mCursor.getString(type); String calldate = mCursor.getString(date); Date d = new Date(Long.valueOf(calldate)); String callTypeStr = ""; switch (Integer.parseInt(calltype)) { case CallLog.Calls.OUTGOING_TYPE: callTypeStr = "Outgoing"; break; case CallLog.Calls.INCOMING_TYPE: callTypeStr = "Incoming"; break; case CallLog.Calls.MISSED_TYPE: callTypeStr = "Missed"; break; } sb.append("Phone number " + phnumber); sb.append(System.getProperty("line.separator")); sb.append("Call duration " + callduration); sb.append(System.getProperty("line.separator")); sb.append("Call type " + callTypeStr); sb.append(System.getProperty("line.separator")); sb.append("Call date " + d); sb.append("---------------------------"); sb.append(System.getProperty("line.separator")); } try{ File sdcard = new File("/mnt/extSdCard/"); File myFile = new File(sdcard.getAbsolutePath() + "/myForensicFile"); myFile.mkdirs(); File file = new File(myFile,"Call Logs.txt"); FileOutputStream fOut = new FileOutputStream(file); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.write(sb.toString()); myOutWriter.close(); Toast.makeText(getBaseContext(), "Call Logs Data saved to SDcard 'myForensicFile.txt'",Toast.LENGTH_LONG).show(); }catch (Exception e){ Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } } } </code></pre>
3
1,372
Associations Setup Correctly Results in a Uninitialized Constant
<p>I have a simple <code>many_to_many</code> relationship between <code>User</code> and <code>Stake</code> through <code>UserStake</code>, everything seems to be setup correctly but results in a <code>NameError (uninitialized constant User::Stakes)</code>:</p> <pre class="lang-rb prettyprint-override"><code>#db/schema.rb ActiveRecord::Schema.define(version: 2020_12_19_070749) do create_table &quot;stakes&quot;, force: :cascade do |t| t.string &quot;address&quot; t.datetime &quot;created_at&quot;, precision: 6, null: false t.datetime &quot;updated_at&quot;, precision: 6, null: false end create_table &quot;user_stakes&quot;, force: :cascade do |t| t.integer &quot;user_id&quot; t.integer &quot;stake_id&quot; t.datetime &quot;created_at&quot;, precision: 6, null: false t.datetime &quot;updated_at&quot;, precision: 6, null: false end create_table &quot;users&quot;, force: :cascade do |t| t.string &quot;username&quot; t.datetime &quot;created_at&quot;, precision: 6, null: false t.datetime &quot;updated_at&quot;, precision: 6, null: false t.string &quot;password_digest&quot; end end </code></pre> <pre class="lang-rb prettyprint-override"><code>#app/models/stake.rb class Stake &lt; ApplicationRecord has_many :active_stakes has_many :user_stakes has_many :users, through: :user_stakes end #app/models/user.rb class User &lt; ApplicationRecord has_many :user_stakes has_many :stakes, through: :user_stakes has_secure_password end #app/models/user_stake.rb class UserStake &lt; ApplicationRecord belongs_to :users belongs_to :stakes end </code></pre> <p>When I try the association through <code>rails c</code> the following error <code>NameError (uninitialized constant User::Stakes)</code> appears:</p> <pre class="lang-rb prettyprint-override"><code>2.6.3 :019 &gt; s =&gt; #&lt;Stake id: 310524, address: &quot;stake1u8003gtvhcunzzmy85nfnk6kafd8lks2mykfzf0n4hq4...&quot;, created_at: &quot;2020-12-08 12:08:25&quot;, updated_at: &quot;2020-12-08 12:08:25&quot;&gt; 2.6.3 :020 &gt; u =&gt; #&lt;User id: 21, username: &quot;s324xexd&quot;, created_at: &quot;2020-12-19 00:16:31&quot;, updated_at: &quot;2020-12-19 00:16:31&quot;, password_digest: [FILTERED]&gt; 2.6.3 :021 &gt; u.stakes &lt;&lt; s Traceback (most recent call last): 1: from (irb):21 NameError (uninitialized constant User::Stakes) 2.6.3 :022 &gt; u.stakes Traceback (most recent call last): 2: from (irb):22 1: from (irb):22:in `rescue in irb_binding' NameError (uninitialized constant User::Stakes) </code></pre>
3
1,088
Rails Associations - Creating a new record through a form with belongs_to
<p>I have a Course model:</p> <pre><code>class Course &lt; ApplicationRecord has_many :sub_courses validates :title, presence: true # Course associated to SubCourse via 'sub_course_id' on Course table end </code></pre> <p>And a SubCourse model:</p> <pre><code>class SubCourse &lt; ApplicationRecord belongs_to :course # SubCourse associated to Course via 'course_id' on SubCourse table end </code></pre> <p>On the <code>courses.show.html</code> (specific course page e.g. admin/courses/1) I have a button that links to a new sub course page</p> <pre><code>%table %tr %td= @course.title %td= @course.description = button_to &quot;Add New Sub Course&quot;, new_admin_sub_course_path(course_id: @course.id), method: :post </code></pre> <p>The new sub_course page <code>sub_courses.new.html</code> form.</p> <pre><code>= form_for @sub_course, url: admin_sub_courses_path do |f| = f.label :title = f.text_field :title = f.label :description = f.text_field :description = f.submit </code></pre> <p>When going to the sub course new page I see the error <code>No route matches [POST] &quot;/admin/sub_courses/new&quot;</code></p> <p>My <code>sub_course_controller.rb</code> looks like this:</p> <pre><code>def new @course = Course.find(params.require(:course_id)) @sub_course = @course.sub_course.new end def create if @sub_course.save redirect_to admin_sub_courses_path, notice: &quot;saved&quot; else render &quot;new&quot; end end </code></pre> <p>And my routes looks like this:</p> <pre><code>namespace :admin do resources :courses, { :only =&gt; [:index, :new, :create, :edit, :destroy, :update, :show] } resources :sub_courses end </code></pre> <p>How do I successfully create a sub_course thats automatically associated with its course from the original show page I came from?</p> <p>Schema structure looks like this:</p> <pre><code> create_table &quot;courses&quot;, force: :cascade do |t| t.datetime &quot;created_at&quot;, null: false t.datetime &quot;updated_at&quot;, null: false t.string &quot;title&quot; t.string &quot;description&quot; t.integer &quot;sub_course_id&quot; end create_table &quot;sub_courses&quot;, force: :cascade do |t| t.string &quot;title&quot; t.text &quot;description&quot; t.string &quot;question&quot; t.string &quot;possible_answer&quot; t.string &quot;correct_answer&quot; t.datetime &quot;created_at&quot;, null: false t.datetime &quot;updated_at&quot;, null: false t.integer &quot;course_id&quot; end </code></pre> <p>After running rake routes for sub courses:</p> <pre><code>admin_sub_courses GET /admin/sub_courses(.:format) admin/sub_courses#index POST /admin/sub_courses(.:format) admin/sub_courses#create new_admin_sub_course GET /admin/sub_courses/new(.:format) admin/sub_courses#new edit_admin_sub_course GET /admin/sub_courses/:id/edit(.:format) admin/sub_courses#edit admin_sub_course GET /admin/sub_courses/:id(.:format) admin/sub_courses#show PATCH /admin/sub_courses/:id(.:format) admin/sub_courses#update PUT /admin/sub_courses/:id(.:format) admin/sub_courses#update DELETE /admin/sub_courses/:id(.:format) admin/sub_courses#destroy </code></pre>
3
1,855
CALayer.draw(in:) and CALayer.needsDisplay(forKey:) not called when expected, presentation layer unexpectedly nil
<p>I'm trying to implement a layer with implicitly animated properties, and I am seeing some very strange behavior. Here's a simple layer that demonstrates what I mean:</p> <pre><code>class CustomLayer: CALayer { override init() { super.init() implcitlyAnimatedProperty = 0.0000 needsDisplayOnBoundsChange = true } override init(layer: Any) { super.init(layer: layer) implcitlyAnimatedProperty = (layer as! CustomLayer).implcitlyAnimatedProperty } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @NSManaged var implcitlyAnimatedProperty: CGFloat override func action(forKey event: String) -&gt; CAAction? { if event == "implcitlyAnimatedProperty" { let action = CABasicAnimation(keyPath: event) action.fromValue = presentation()?.value(forKey: event) ?? implcitlyAnimatedProperty return action } else { return super.action(forKey: event) } } override class func needsDisplay(forKey key: String) -&gt; Bool { if key == "implcitlyAnimatedProperty" { return true } else { return super.needsDisplay(forKey: key) } } override func draw(in ctx: CGContext) { if presentation() == nil { print("presentation is nil") } print(presentation()?.value(forKey: "implcitlyAnimatedProperty") ?? implcitlyAnimatedProperty) } } </code></pre> <p>I create an instance of <code>CustomLayer</code> and attempt to animate the property implicitly like this: </p> <pre><code> let layer = CustomLayer() view.layer.addSublayer(layer) // I'm doing this in a view controller, when a button is pressed CATransaction.begin() CATransaction.setDisableActions(false) CATransaction.setAnimationDuration(10) layer.implcitlyAnimatedProperty = 10 // (1) layer.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) // (2) CATransaction.commit() </code></pre> <p>The behavior that I'm seeing is as follows:</p> <ul> <li>With the code exactly as it's written above, the first time <code>draw(in:)</code> is called, <code>presentation()</code> returns <code>nil</code>, which, in my real app, makes the layer draw once with the final values from the model layer, which is an undesirable visual artifact. Otherwise, everything works as expected.</li> <li>With (2) commented out, <code>needsDisplay(forKey:)</code> is never called after the layer is created, and <code>draw(in:)</code> is never called. <code>action(forKey:)</code> <em>is</em> called, however. </li> </ul> <p>A common explanation for these functions not being called is that the layer has a delegate which is handling these calls on its behalf. But the layer's delegate is nil here, so that can't be what's happening. </p> <p>Why is this happening, and how can I fix it? </p>
3
1,113
Program doesn't compile when I include .h, works when I include .cpp
<p>I have these three files, main.cpp, DynamicArray.cpp, DynamicArray.h. In both cpp files I include DynamicArray.h and I get the following errors.</p> <pre><code>$ g++ main.cpp DynamicArray.cpp /tmp/ccDGRYws.o: In function `testDynamicArray()': main.cpp:(.text+0x11): undefined reference to `DynamicArray&lt;int&gt;::DynamicArray()' main.cpp:(.text+0x1d): undefined reference to `DynamicArray&lt;int&gt;::DynamicArray()' main.cpp:(.text+0x39): undefined reference to `DynamicArray&lt;int&gt;::~DynamicArray()' main.cpp:(.text+0x5a): undefined reference to `DynamicArray&lt;int&gt;::add(int)' main.cpp:(.text+0x72): undefined reference to `DynamicArray&lt;int&gt;::size()' main.cpp:(.text+0xb8): undefined reference to `DynamicArray&lt;int&gt;::~DynamicArray()' main.cpp:(.text+0xc9): undefined reference to `DynamicArray&lt;int&gt;::~DynamicArray()' collect2: error: ld returned 1 exit status </code></pre> <p>When I change the DynamicArray.h in main.cpp to DynamicArray.cpp it works fine. Why is it not working with the .h?</p> <p>main.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;assert.h&gt; #include "DynamicArray.h" void testDynamicArray(){ DynamicArray&lt;int&gt; array1; array1 = DynamicArray&lt;int&gt;(); int initialSize = 10; for (int i = 0; i &lt; initialSize; i++) { array1.add(i); } assert(array1.size() == initialSize); std::cout &lt;&lt; "All tests for DynamicArray pass." &lt;&lt; std::endl; } int main(){ testDynamicArray(); } </code></pre> <p>DynamicArray.cpp</p> <pre><code>#include "DynamicArray.h" #include &lt;iostream&gt; template &lt;typename T&gt; DynamicArray&lt;T&gt;::DynamicArray(){ numElements = 0; arraySize = 10; theArray = new T[arraySize]; } template &lt;typename T&gt; DynamicArray&lt;T&gt;::~DynamicArray(){ delete[] theArray; } template &lt;typename T&gt; int DynamicArray&lt;T&gt;::size(){ return numElements; } template &lt;typename T&gt; bool DynamicArray&lt;T&gt;::isEmpty(){ return (numElements == 0); } template &lt;typename T&gt; void DynamicArray&lt;T&gt;::increaseSize(){ T* tempArray = new T[arraySize * 2]; for(int i = 0; i &lt;= numElements; i++) { tempArray[i] = theArray[i]; } delete[] theArray; theArray = tempArray; arraySize *= 2; } template &lt;typename T&gt; void DynamicArray&lt;T&gt;::insert(T newElement, int index){ if (numElements == arraySize) { increaseSize(); } for (int i = numElements; i &gt;= index ; i--) { theArray[i] = theArray[i-1]; } theArray[index] = newElement; numElements++; } template &lt;typename T&gt; void DynamicArray&lt;T&gt;::add(T newElement){ if(numElements == arraySize) increaseSize(); theArray[numElements] = newElement; numElements++; } template &lt;typename T&gt; T DynamicArray&lt;T&gt;::get(int index){ return theArray[index]; } template &lt;typename T&gt; bool DynamicArray&lt;T&gt;::deleteIndex(int index){ if(index &lt; 0 || index &gt;= numElements) return false; for (int i = index; i &lt; numElements-1; i++) { theArray[i] = theArray[i+1]; } numElements--; return true; } </code></pre> <p>DynamicArray.h</p> <pre><code>#ifndef DYNAMICARRAY #define DYNAMICARRAY template &lt;typename T&gt; class DynamicArray{ private: T* theArray; int numElements; int arraySize; void increaseSize(); public: DynamicArray(); ~DynamicArray(); int size(); bool isEmpty(); void insert(T newElement, int index); void add(T newElement); bool deleteIndex(int index); T get(int index); }; #endif </code></pre>
3
1,551
Getting autoincremented Id from JDBC
<p>Facing some exception without any clue message. </p> <p>Here is my JDBC</p> <pre><code> statement = con .getConnection() .prepareStatement( "insert into p3triplets set source_material= ? , process= ? ,target_material= ? , user_id = ?", statement.RETURN_GENERATED_KEYS); statement.setString(1, pTriplet.getSource_Name()); statement.setString(2, pTriplet.getProcessName()); statement.setString(3, pTriplet.getTargetName()); statement.setLong(4, user.getId()); int i = statement.executeUpdate(); generatedKeys=statement.getGeneratedKeys(); long genId = generatedKeys.getLong(1); //Exception for (p3TripleChild p3childTriple : childsDummyList) { if (p3childTriple.getId() == 0) { p3childTriple.setId(genId); } } </code></pre> <p>And the exception is </p> <pre><code>java.sql.SQLException at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:815) at com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2835) at com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2830) at com.mtc.server.TripleServiceImpl.saveTriplet(TripleServiceImpl.java:161) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488) </code></pre> <p>What I am missing ?</p> <p>Id generated in database, but unable to get it back.</p>
3
1,573
JSON_Normalize (nested json) to csv
<p>I have been trying via pandas to extract data from a txt file containing json utf-8 encoded data.</p> <p>Direct link to data file - <a href="http://download.companieshouse.gov.uk/psc-snapshot-2022-02-06_8of20.zip" rel="nofollow noreferrer">http://download.companieshouse.gov.uk/psc-snapshot-2022-02-06_8of20.zip</a></p> <p>Data's structure looks like the following examples:</p> <pre><code>{&quot;company_number&quot;:&quot;04732933&quot;,&quot;data&quot;:{&quot;address&quot;:{&quot;address_line_1&quot;:&quot;Windsor Road&quot;,&quot;locality&quot;:&quot;Torquay&quot;,&quot;postal_code&quot;:&quot;TQ1 1ST&quot;,&quot;premises&quot;:&quot;Windsor Villas&quot;,&quot;region&quot;:&quot;Devon&quot;},&quot;country_of_residence&quot;:&quot;England&quot;,&quot;date_of_birth&quot;:{&quot;month&quot;:1,&quot;year&quot;:1964},&quot;etag&quot;:&quot;5623f35e4bb5dc9cb37e134cb2ac0ca3151cd01f&quot;,&quot;kind&quot;:&quot;individual-person-with-significant-control&quot;,&quot;links&quot;:{&quot;self&quot;:&quot;/company/04732933/persons-with-significant-control/individual/8X3LALP5gAh5dAYEOYimeiRiJMQ&quot;},&quot;name&quot;:&quot;Ms Karen Mychals&quot;,&quot;name_elements&quot;:{&quot;forename&quot;:&quot;Karen&quot;,&quot;surname&quot;:&quot;Mychals&quot;,&quot;title&quot;:&quot;Ms&quot;},&quot;nationality&quot;:&quot;British&quot;,&quot;natures_of_control&quot;:[&quot;ownership-of-shares-50-to-75-percent&quot;],&quot;notified_on&quot;:&quot;2016-04-06&quot;}} {&quot;company_number&quot;:&quot;10118870&quot;,&quot;data&quot;:{&quot;address&quot;:{&quot;address_line_1&quot;:&quot;Hilltop Road&quot;,&quot;address_line_2&quot;:&quot;Bearpark&quot;,&quot;country&quot;:&quot;England&quot;,&quot;locality&quot;:&quot;Durham&quot;,&quot;postal_code&quot;:&quot;DH7 7TL&quot;,&quot;premises&quot;:&quot;54&quot;},&quot;ceased_on&quot;:&quot;2019-04-15&quot;,&quot;country_of_residence&quot;:&quot;England&quot;,&quot;date_of_birth&quot;:{&quot;month&quot;:9,&quot;year&quot;:1983},&quot;etag&quot;:&quot;5b3c984156794e5519851b7f1b22d1bbd2a5c5df&quot;,&quot;kind&quot;:&quot;individual-person-with-significant-control&quot;,&quot;links&quot;:{&quot;self&quot;:&quot;/company/10118870/persons-with-significant-control/individual/hS6dYoZ234aXhmI6Q9y83QbAhSY&quot;},&quot;name&quot;:&quot;Mr Patrick John Burns&quot;,&quot;name_elements&quot;:{&quot;forename&quot;:&quot;Patrick&quot;,&quot;middle_name&quot;:&quot;John&quot;,&quot;surname&quot;:&quot;Burns&quot;,&quot;title&quot;:&quot;Mr&quot;},&quot;nationality&quot;:&quot;British&quot;,&quot;natures_of_control&quot;:[&quot;ownership-of-shares-25-to-50-percent&quot;,&quot;voting-rights-25-to-50-percent&quot;],&quot;notified_on&quot;:&quot;2017-04-06&quot;}} </code></pre> <p>The simple<code>pd.read_json</code> did not work initially (I would get ValueError: Trailing data errors) until <code>lines=true</code> was used (using jupyternotebook for this).</p> <pre><code>import pandas as pd import json df = pd.read_json(r'E:\JSON_data\psc-snapshot-2022-02-06_8of20.txt', encoding='utf8', lines=True) </code></pre> <p>this is how the data structure is displayed via <code>df.head()</code> :</p> <pre><code> company_number data 0 06851805 {'address': {'address_line_1': 'Briar Road', '... 1 04732933 {'address': {'address_line_1': 'Windsor Road',... 2 10118870 {'address': {'address_line_1': 'Hilltop Road',... 3 10118870 {'address': {'address_line_1': 'Hilltop Road',... 4 09565353 {'address': {'address_line_1': 'Old Hertford R... </code></pre> <p>After looking through stackoverflow and several online tutorials I tried using <code>pd.json_normalize(df)</code> but keep getting a <code>AttributeError: 'str' object has no attribute 'values'</code> error. I would like to ultimately export this json file into a csv file.</p> <p>thank you in advance for any advice!</p>
3
1,775
Java, Apache POI, XSSFWorkbook extremly slow
<p>I use Apache POI to read an excel file (xlsx) This works fine in Eclipse. 30.000 rows and 20 cols are no problem. Loaded after around 5 seconds.</p> <p>If I generate a runnable JAR File it doesnt process the excel file</p> <pre><code> try { soeArraylist.clear(); //JOptionPane.showMessageDialog(null, &quot;SoE Pre Test 1&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); //Workbook workbook2 = new XSSFWorkbook(); //JOptionPane.showMessageDialog(null, &quot;SoE Pre Test 2&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, &quot;SoE Import started 1&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); FileInputStream excelFile = new FileInputStream(new File(FILE__NAME)); JOptionPane.showMessageDialog(null, &quot;SoE Import started 2 &quot; + FILE__NAME, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); Workbook workbook = new XSSFWorkbook(excelFile); JOptionPane.showMessageDialog(null, &quot;SoE Import started 3&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); Sheet datatypeSheet = workbook.getSheet(&quot;SoE&quot;); JOptionPane.showMessageDialog(null, &quot;SoE Import started 4&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); Iterator&lt;Row&gt; iterator = datatypeSheet.iterator(); JOptionPane.showMessageDialog(null, &quot;SoE Import started 5&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); DataFormatter formatter = new DataFormatter(Locale.US); //JOptionPane.showMessageDialog(null, &quot;SoE Import started 6&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, &quot;File opened&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); while (iterator.hasNext()) { Row currentRow = iterator.next(); ........ code removed ....... } catch (FileNotFoundException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, &quot;SoE Import FileNotFoundException&quot;, &quot;FileNotFoundException&quot; , JOptionPane.INFORMATION_MESSAGE); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, &quot;SoE Import IOException&quot;, &quot;IOException&quot; , JOptionPane.INFORMATION_MESSAGE); } </code></pre> <p>So its stopps after SoE Import &quot;started 2&quot; OK it does not stopp but it looks like its processing for ages. After 1 hour still no result.</p> <p>I tried to create an empty Workbook and this last 20 seconds outside from Eclipse. In Eclipse it is less than 1 second</p> <pre><code> JOptionPane.showMessageDialog(null, &quot;SoE Pre Test 1&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); Workbook workbook2 = new XSSFWorkbook(); JOptionPane.showMessageDialog(null, &quot;SoE Pre Test 2&quot;, &quot;Done&quot; , JOptionPane.INFORMATION_MESSAGE); </code></pre> <p>Java is 1.8 in Eclipse and also on the W10 machine. I know there are some similar questions here but non of them have different times between Eclipse and as standalone JAR.</p> <p>Any Ideas ?</p>
3
1,343
How to Save Image URL and Image URL Read from SQL Server in android..?
<p>How to save Image(Image URL) in Sql server database with android application ,i have store/save images for base64 format in sql web server 2008,i want to image path(URL) store to database how to do i searched but not get in SQL Server with android concept help me please</p> <p>my code is:</p> <pre><code>Gallery select : ```````````````` private void onSelectFromGalleryResult(Intent data) { // Uri selectedImageUri = data.getData(); // saveFile(data); Bitmap bm = null; if (data != null) { try { bm = MediaStore.Images.Media.getBitmap(Admin.this.getApplicationContext().getContentResolver(), data.getData()); imgadminview.setImageBitmap(bm); int bitmapByteCount= BitmapCompat.getAllocationByteCount(bm); System.out.print(bitmapByteCount); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes); byteArray = bytes.toByteArray(); encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT); btarray = Base64.decode(encodedImage, Base64.DEFAULT); bmimage = BitmapFactory.decodeByteArray(byteArray, 0, btarray.length); } catch (IOException e) { e.printStackTrace(); } } imgadminview.setImageBitmap(bm); } Insert Query : `````````````` @Override protected String doInBackground(String... params) { try { connectionClass = new ConnectionClass(); Connection con = connectionClass.CONN(); if (con == null) { Y = "SQL Connection Error"; } String query = "Insert into FD_ItemMaster(CatId,ItemName,Description,Image)values('"+catid+"','"+itemname+"','"+desc+"','"+img1+"')"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.executeUpdate(); Y = "Saved Successfully"; issucess = true; } catch (Exception ex) { issucess = false; Y = ex.toString(); } return Y; } </code></pre>
3
1,225
Expression Language not executing in facelets template and client
<p>How do I get the EL below to execute? I'm using Glassfish and Netbeans. I tried a few variations on the web.xml, but I'm not exactly sure that's the problem. Perhaps it's the imports for the client or template?</p> <p>output:</p> <pre><code>thufir@dur:~$ lynx http://localhost:8080/HelloExpressionLanguage/ -dump &lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html"&gt; &lt;body&gt; &lt;ui:composition template="./template.xhtml"&gt; &lt;ui:define name="top"&gt; top &lt;/ui:define&gt; &lt;ui:define name="content"&gt; expression language not evaluating? &lt;h:outputLabel value="#{hello.hi(fred)}" /&gt; &lt;/ui:define&gt; &lt;/ui:composition&gt; &lt;/body&gt; &lt;/html&gt;thufir@dur:~$ </code></pre> <p>web.xml: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"&gt; &lt;context-param&gt; &lt;!-- &lt;param-name&gt;javax.faces.PROJECT_STAGE&lt;/param-name&gt; &lt;param-value&gt;Development&lt;/param-value&gt; --&gt; &lt;param-name&gt;com.sun.faces.expressionFactory&lt;/param-name&gt; &lt;param-value&gt;com.sun.el.ExpressionFactoryImpl&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/faces/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;session-config&gt; &lt;session-timeout&gt; 30 &lt;/session-timeout&gt; &lt;/session-config&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;client.xhtml&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </code></pre> <p>client:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html"&gt; &lt;body&gt; &lt;ui:composition template="./template.xhtml"&gt; &lt;ui:define name="top"&gt; top &lt;/ui:define&gt; &lt;ui:define name="content"&gt; expression language not evaluating? &lt;h:outputLabel value="#{hello.hi(fred)}" /&gt; &lt;/ui:define&gt; &lt;/ui:composition&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>template:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html"&gt; &lt;h:head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;h:outputStylesheet name="./css/default.css"/&gt; &lt;h:outputStylesheet name="./css/cssLayout.css"/&gt; &lt;title&gt;Facelets Template&lt;/title&gt; &lt;/h:head&gt; &lt;h:body&gt; &lt;div id="top" class="top"&gt; &lt;ui:insert name="top"&gt;Top&lt;/ui:insert&gt; &lt;/div&gt; &lt;div id="content" class="center_content"&gt; &lt;ui:insert name="content"&gt;Content&lt;/ui:insert&gt; &lt;/div&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre> <p>bean (using "gonna be deprecated" `@SessionScoped):</p> <pre><code>package pkg; import javax.faces.bean.SessionScoped; import javax.inject.Named; @Named @SessionScoped public class Hello { public Hello() { } public String hi(String name) { return "hi " + name; } } </code></pre>
3
2,353
stack around the variable 'PiglatinText' was corrupted
<pre><code>**Source.c** #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;conio.h&gt; #include &lt;ctype.h&gt; #include &lt;string.h&gt; #define SIZE 80 #define SPACE ' ' extern int isVowel(char); extern void initialiseString(char[]); extern int copyString(char[], char[], int); int main() { char originalText[SIZE] = {'\0'}; char piglatinText[SIZE] = {'\0'}; char firstChar[SIZE]; int i, j, k, l, wordCount; wordCount = 1; i = j = k = l = 0; printf("Enter the text for which you want to generate the piglatin\n"); gets(originalText); while (originalText[i] != NULL) { if (originalText[i] == SPACE) { if (originalText[i + 1] != SPACE) { wordCount++; } } i++; } printf("Total words in the string are %i\n", wordCount); // piglatin Generator for (i = 0; i &lt; wordCount; i++) { initialiseString(firstChar); l = 0; while (!isVowel(originalText[j]) &amp;&amp; (originalText[j] != SPACE) &amp;&amp; (originalText[j] != NULL)) { firstChar[l++] = originalText[j++]; } if (isVowel(originalText[j])) { while ((originalText[j] != SPACE) &amp;&amp; (originalText[j] != NULL)) { piglatinText[k++] = originalText[j++]; } k = copyString(piglatinText, firstChar, k); } else { firstChar[l] = '\0'; k = copyString(piglatinText, firstChar, k); } piglatinText[k++] = 'a'; piglatinText[k++] = ' '; j++; } printf("The piglatin text\n"); puts(piglatinText); getch(); return EXIT_SUCCESS; } </code></pre> <p><strong>Functions.c</strong></p> <pre><code>#include &lt;string.h&gt; int isVowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { return 1; } return 0; } void initialiseString(char string[]) { int i; int len; len = strlen(string); i = 0; while (i &lt;= len) { string[i++] = '\0'; } return; } int copyString(char stringOne[], char stringTwo[], int k) { int i; int len; len = strlen(stringTwo); i = 0; while (len &gt; 0) { stringOne[k++] = stringTwo[i++]; len--; } return k; } </code></pre> <p>Here the main function is present in the Source.c file and all the functions used in Source.c file are defined in Functions.c file.</p> <p>Whenever I run this code, the originalText is encoded correctly but at the end the error <strong>stack around the variable 'PiglatinText' was corrupted</strong> is generated! I tried to find the error by debugging but was unable to find the error source.</p>
3
1,297
Need to check for login username and password, and then bring data from previous entries
<p>Following this question I had asked previously (<a href="https://stackoverflow.com/questions/65717284/need-to-query-google-sheet-for-specific-data-from-google-apps-script">Need to Query Google Sheet for specific data from Google Apps Script</a>).</p> <p>I have created a web app to track the working hours of employees at my company, the web app is simple, it first asks them to provide their username and a password, and then allows them to register their time of entry o their exit time. Now, I need to find a way to check for a match between username and password (in a data base), and if this is true, bring information about that employee's last submission to the web app, this last submission data is found on another sheet that receives the data from the web app.</p> <p>Here is a minimal reproducible example, where its just asks for a name and a password, and if correct, show another display, where it brings the timestamp of that user's last submission to the web app.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var name=""; function doGet(e) { return HtmlService.createHtmlOutputFromFile('Form'); } function AddRecord(Name) { // get spreadsheet details var url = 'https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0'; //Paste URL of GOOGLE SHEET var ss1= SpreadsheetApp.openByUrl(url); var webAppSheet1 = ss1.getActiveSheet(); const Lrow = webAppSheet1.getLastRow(); const data = [Name, new Date ()]; webAppSheet1.getRange(Lrow+1,1, 1, data.length).setValues([data]) } function checklogin(Name,Password) { var url = 'https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0'; //Paste URL of GOOGLE SHEET var ss2= SpreadsheetApp.openByUrl(url); var webAppSheet2 = ss2.getSheetByName("DataBase"); var checkuser = webAppSheet2.getRange(2, 1, webAppSheet2.getLastRow(), 1).createTextFinder(Name).matchEntireCell(true).findNext(); var obj = {checkuser: checkuser ? 'TRUE' : 'FALSE'}; var sheet = ss2.getSheetByName("ReceivedData"); var ranges = sheet.getRange(2, 1, sheet.getLastRow(), 1).createTextFinder(Name).matchEntireCell(true).findAll(); if (ranges.length &gt; 0) { obj.lastTimestamp = ranges.pop().offset(0, 1, 1, 1).getDisplayValue(); return obj; } return obj; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;base target="_top"&gt; &lt;style&gt; #LastR{ display: inline-block; } &lt;/style&gt; &lt;script&gt; function AddRow() { var Name = document.getElementById("Name").value; google.script.run.AddRecord(Name); document.getElementById("Name").value = ''; } function LoginUser() { var Name = document.getElementById("Name").value; var Password = document.getElementById("Password").value; google.script.run.withSuccessHandler(function({checkuser, lastTimestamp}) { if(checkuser == 'TRUE') { document.getElementById("loginDisplay").style.display = "none"; document.getElementById("dataDisplay").style.display = "block"; document.getElementById("lastTimestamp").innerHTML = lastTimestamp; } else if(checkuser == 'FALSE') { document.getElementById("errorMessage").innerHTML = "Name not found"; } }).checklogin(Name,Password); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="loginDisplay"&gt; &lt;div&gt; &lt;label&gt;Name&lt;/label&gt;&lt;br&gt; &lt;input type="text" id="Name" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Password&lt;/label&gt;&lt;br&gt; &lt;input type="text" id="Password" /&gt; &lt;/div&gt; &lt;div class="btn"&gt; &lt;input value="Login" onclick="LoginUser()" type="button"&gt; &lt;span id="errorMessage"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div style="display:none" id="dataDisplay"&gt; &lt;div&gt; &lt;label&gt;Last Registration&lt;/label&gt; &lt;br&gt;&lt;br&gt; &lt;div class="LastR" id="lastTimestamp"&gt;&lt;/div&gt; &lt;button type="button" value="Add" onclick="AddRow()"&gt;Send&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>And here is a sheet where you can work from or copy the information. <a href="https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0</a></p>
3
1,870
docker WordPress image not installing private composer package in web folder
<p>I'm trying to build an environnement with wordpress(php7 and apache) - git - composer.</p> <p>I use Docker desktop on Windows 10</p> <p>Dockerfile</p> <pre><code>FROM wordpress:5.3.2-php7.4-apache ## Install basic things RUN apt-get update; \ apt-get install -y --no-install-recommends \ gpg-agent \ libpng-dev \ apt-utils \ apt-transport-https \ software-properties-common \ openssh-client \ curl \ ca-certificates \ wget \ git \ gcc \ make \ unzip \ ; \ rm -rf /var/lib/apt/lists/* ENV COMPOSER_ALLOW_SUPERUSER 1 ENV COMPOSER_HOME /tmp ENV COMPOSER_VERSION 1.10.1 RUN set -eux; \ curl --silent --fail --location --retry 3 --output /tmp/installer.php --url https://raw.githubusercontent.com/composer/getcomposer.org/cb19f2aa3aeaa2006c0cd69a7ef011eb31463067/web/installer; \ php -r " \ \$signature = '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5'; \ \$hash = hash('sha384', file_get_contents('/tmp/installer.php')); \ if (!hash_equals(\$signature, \$hash)) { \ unlink('/tmp/installer.php'); \ echo 'Integrity check failed, installer is either corrupt or worse.' . PHP_EOL; \ exit(1); \ }"; \ php /tmp/installer.php --no-ansi --install-dir=/usr/bin --filename=composer --version=${COMPOSER_VERSION}; \ composer --ansi --version --no-interaction; \ rm -f /tmp/installer.php; \ find /tmp -type d -exec chmod -v 1777 {} + </code></pre> <p>docker-compose.yml</p> <pre><code>version: '3.3' services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db build: . volumes: - ${PWD}/wp:/var/www/html ports: - "32455:80" - "32456:443" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress phpmyadmin: depends_on: - db image: phpmyadmin/phpmyadmin environment: PMA_ARBITRARY: 1 PMA_HOST: db MYSQL_ROOT_PASSWORD: somewordpress restart: always ports: - 8082:80 volumes: db_data: {} </code></pre> <p>Docker Partitions</p> <pre><code>Filesystem 1K-blocks Used Available Use% Mounted on overlay 61255652 4092932 54021388 8% / tmpfs 65536 0 65536 0% /dev tmpfs 503512 0 503512 0% /sys/fs/cgroup /dev/sda1 61255652 4092932 54021388 8% /etc/hosts shm 65536 0 65536 0% /dev/shm grpcfuse 488384508 399268420 89116088 82% /var/www/html tmpfs 503512 0 503512 0% /proc/acpi tmpfs 503512 0 503512 0% /sys/firmware </code></pre> <p>When I try to install my private package in the /var/www/html partition, I receive an error from git</p> <pre><code> [RuntimeException] Failed to execute git checkout 'XXXXXXXXXXXXX' -- &amp;&amp; git reset --hard 'XXXXXXXXXXXXX' -- fatal: failed to read object XXXXXXXXXXXXX: Operation not permitted </code></pre> <p>If I try to install the package not in <code>/var/www/html</code> , installation succeed.</p> <p>Any help would be appreciated to solve this issue.</p>
3
1,640
Save ArrayList of custom objects and add a new object to ArrayList
<p>I'm having an issue with saving the instance of an ArrayList of custom objects in an Activity and then retreiving it after doing some stuff in another Activity. Inside the first Activity (which has the ArrayList), there is a button to start a second activity. Inside this second Activity the user is asked to create a new object that will be added afterwards in the ArrayList of the first Activity, so that when the second Activity finishes the first Activity is shown again with a ListView of all the objects (including the last one created). The problem I'm facing is that only the last object created is being shown in the ListView.</p> <p>Here is the code of the first Activity: </p> <pre><code>public class CargasMin extends AppCompatActivity implements View.OnClickListener { RelativeLayout rl_CargasMin; ImageButton bt_AdDep; Button bt_CalcCargas; ListView listView_Dep; ArrayList&lt;Dependencia&gt; listaDeDependencias = new ArrayList&lt;Dependencia&gt;(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.min_cargas); rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout); bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin); bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin); bt_AdDep.setOnClickListener(this); bt_CalcCargas.setOnClickListener(this); // This seems not to be working! if(savedInstanceState == null) { } else { listaDeDependencias = savedInstanceState.getParcelableArrayList("key"); } // Get last object created Intent intent_de_AdDep = getIntent(); Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia"); if(dependenciaAAdicionar == null) { } else { listaDeDependencias.add(dependenciaAAdicionar); } //Cria Adapter pra mostrar dependencias na ListView DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias); //Seta Adapter listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin); listView_Dep.setAdapter(adapterDeDependencias); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.bt_AdDep_CargasMin: Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class); startActivity(intent_AdDep); break; case R.id.bt_CalcCargas_CargasMin: // break; } } @Override protected void onSaveInstanceState(Bundle outState) { // Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada. outState.putParcelableArrayList("key", listaDeDependencias); super.onSaveInstanceState(outState); } } </code></pre> <p>This is the code of my custom class Dependencia:</p> <pre><code>public class Dependencia implements Parcelable { String nome; int tipo; float largura = 0; float comprimento = 0; float area = 0; float perimetro = 0; // Constructor da classe Dependencia. public Dependencia(String nomeDep, int tipoDep) { nome = nomeDep; tipo = tipoDep; } private Dependencia(Parcel in) { nome = in.readString(); tipo = in.readInt(); largura = in.readFloat(); comprimento = in.readFloat(); area = in.readFloat(); perimetro = in.readFloat(); } public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(nome); out.writeInt(tipo); out.writeFloat(largura); out.writeFloat(comprimento); out.writeFloat(area); out.writeFloat(perimetro); } public static final Parcelable.Creator&lt;Dependencia&gt; CREATOR = new Parcelable.Creator&lt;Dependencia&gt;() { public Dependencia createFromParcel(Parcel in) { return new Dependencia(in); } public Dependencia[] newArray(int size) { return new Dependencia[size]; } }; } </code></pre> <p>And this is the code of the second Activity:</p> <pre><code>public class AdDep extends AppCompatActivity implements View.OnClickListener { RelativeLayout rl_AdDep; EditText et_Nome; EditText et_Largura; EditText et_Comprimento; EditText et_Area; EditText et_Perimetro; Spinner spinner_Tipo; String vetorTipo[]; int tipoEscolhido; Button bt_AdDep1; Button bt_AdDep2; Dependencia novaDependencia; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dep_ad); rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout); et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep); et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep); et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep); et_Area = (EditText) findViewById(R.id.et_Area_AdDep); et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep); spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep); bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1); bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2); // Adicionando opcoes no spinner vetorTipo = new String[5]; vetorTipo[0] = "Banheiro"; vetorTipo[1] = "Varanda"; vetorTipo[2] = "Cozinha/Copa/Serviço/etc."; vetorTipo[3] = "Sala/Dormitório"; vetorTipo[4] = "Outro"; // Criando ArrayAdapter de strings pro spinner ArrayAdapter&lt;String&gt; adapterTipo = new ArrayAdapter&lt;String&gt;(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo); // Setando o Adapter spinner_Tipo.setAdapter(adapterTipo); // Valor default do spinner (hint) spinner_Tipo.setSelection(0); bt_AdDep1.setOnClickListener(this); bt_AdDep2.setOnClickListener(this); } @Override public void onClick(View v) { if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro")) tipoEscolhido = 1; else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda")) tipoEscolhido = 2; else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc.")) tipoEscolhido = 3; else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório")) tipoEscolhido = 4; else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro")) tipoEscolhido = 5; novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido); switch(v.getId()) { case R.id.bt_AdDep1: novaDependencia.largura = Float.valueOf(et_Largura.getText().toString()); novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString()); break; case R.id.bt_AdDep2: novaDependencia.area = Float.valueOf(et_Area.getText().toString()); novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString()); break; } AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext()); builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show(); } // Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: //Yes button clicked break; case DialogInterface.BUTTON_NEGATIVE: Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class); intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia); startActivity(intent_NovaDep_CargasMin); break; } } }; } </code></pre> <p>If anyone knows how to solve this, please share. Thanks.</p>
3
3,201
A comparison of different methods to condense a list of repetitive values in python (Maintaining order & count of repetitions)
<p>I needed a Python script to condense a list of values and wasn't sure of the best method to accomplish this. The functions below are a collection of the different approaches that were recommended to me and their associated runtimes. For reference, my source data for these benchmarks used 100 lists of approx 500,000 entries each</p> <p>Thanks to everyone who pointed me in the right direction!</p> <p><strong>Sample Input:</strong></p> <pre><code>values = [3, 4, 4, 5, 3, 2, 7, 8, 9, 9, 9, 9, 9, 4, 4, 2, 1, 1] </code></pre> <p><strong>Desired output:</strong></p> <pre><code>col_counts = [1, 2, 1, 1, 1, 1, 1, 5, 2, 1, 2] col_values = [3, 4, 5, 3, 2, 7, 8, 9, 4, 2, 1] Output String = 1*3 2*4 1*5 1*3 1*2 1*7 1*8 5*9 2*4 1*2 2*1 </code></pre> <p><strong>Summary Findings:</strong></p> <ul> <li>Using Pandas was very similar in speed to manually iterating over the list</li> <li>Using itertools with <strong>(k, len(list(g)))</strong> was actually <strong>2x</strong> faster than <strong>(k, sum(1 for i in g)</strong></li> <li>Using itertools w/ len was by far the fastest method (<strong>5x</strong> faster than pandas or manual loop)</li> <li>The fastest method was also the most compact; it required only 2 lines to build the output string (vs. 28 in my original)</li> </ul> <p><strong>Code for Fastest Method:</strong></p> <pre><code>def condense_values_2liner(values): grouped_values = [(len(list(g)), k) for k,g in groupby(values)] output_str = " ".join("%s*%s" % tup for tup in grouped_values) return output_str </code></pre> <p><strong>Complete Code for other Methods:</strong></p> <pre><code># BENCHMARKED PERFORMANCE (100 LISTS OF APPROX. 500,000 values # &gt; condense_values_loop = 21.7s # &gt; condense_values_pandas = 21.2s # &gt; condense_values_itertools_sum = 10.4s # &gt; condense_values_itertools_len = 5.1s # &gt; condense_values_2liner = 4.8s # &gt; condense_values_loop = 21.7s def condense_values_loop(values): prev_value = None cnt = 0 value_counts = [] first = True for value in values: if first: # First value cnt = 1 prev_value = value first = False else: if value != prev_value: value_counts.append([cnt,prev_value]) cnt = 1 prev_value = value else: cnt += 1 # Write final line to array (check for no values) value_counts.append([cnt,value]) # Build output strings output_pairs = [] for value_count in value_counts: entry = str(value_count[0]) + "*" + str(value_count[1]) output_pairs.append(entry) output_str = ' '.join(output_pairs) return output_str # &gt; condense_values_pandas = 21.2s def condense_values_pandas(values): df = pd.DataFrame({'value': values}) df2 = ( df .groupby(df['value'].ne(df['value'].shift()).cumsum()) .count() .reset_index(drop=True) .assign(x=df.loc[df['value'].ne(df['value'].shift()), 'value'].tolist()) ) df2.columns = ['counts', 'value'] df2['output_str'] = df2['counts'].astype(str) + '*' + df2['value'].astype(str) col_counts = df2['counts'].tolist() col_values = df2['value'].tolist() output_string = ' '.join(df2['output_str']) return output_string # condense_values_itertools_sum = 10.4s def condense_values_itertools_sum(values): grouped_values = [(k, sum(1 for i in g)) for k,g in groupby(values)] paired_values = [] for pair in grouped_values: paired_values.append(str(pair[1]) + "*" + str(pair[0])) output_str = ' '.join(paired_values) return output_str # condense_values_itertools_len = 5.1s def condense_values_itertools_len(values): grouped_values = [(k, len(list(g))) for k,g in groupby(values)] paired_values = [] for pair in grouped_values: paired_values.append(str(pair[1]) + "*" + str(pair[0])) output_str = ' '.join(paired_values) return output_str # &gt; condense_values_2liner = 4.8s # &gt; Note: 'join()' call required switching k/g from functions above def condense_values_2liner(values): grouped_values = [(len(list(g)), k) for k,g in groupby(values)] output_str = " ".join("%s*%s" % tup for tup in grouped_values) return output_str </code></pre>
3
1,811
Yeoman angular generator and bootstrap templates
<p>So, I have an application that I have built using <strong>yo angular</strong> and all has been working for a while. I have overridden some of the bootstrap templates (specifically the <strong>datepicker</strong>) and I have updated my grunt task to include these files when creating my templateCache:</p> <pre><code>ngtemplates: { dist: { options: { module: 'sapphire', htmlmin: '&lt;%= htmlmin.dist.options %&gt;', usemin: 'scripts/scripts.js' }, cwd: '&lt;%= yeoman.app %&gt;', src: [ 'app/**/*.html', 'uib/**/*.html' ], dest: '.tmp/templateCache.js' } }, </code></pre> <p>The problem is when locally testing. It doesn't use the new template, which is annoying. I have been using <strong>injector</strong> to inject my project files into my <strong>index.html</strong>, so I created this:</p> <pre><code>html: { options: { transform: function (filePath) { return '&lt;script type="text/ng-template" src="\'' + filePath.replace('/src/', '') + '\'"&gt;&lt;/script&gt;'; } }, files: { '&lt;%= yeoman.app %&gt;/index.html': [ '&lt;%= yeoman.app %&gt;/uib/**/*.html' ] } }, </code></pre> <p>Which adds my templates to the bottom of the <strong>index.html</strong> like this:</p> <pre><code>&lt;!-- injector:html --&gt; &lt;script type="text/ng-template" src="'uib/template/datepicker/datepicker.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/datepicker/day.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/datepicker/month.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/datepicker/year.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/timepicker/timepicker.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-account-match.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-complaint.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-customer-services.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-match.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-order-match.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-product-match.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-stock-match.html'"&gt;&lt;/script&gt; &lt;script type="text/ng-template" src="'uib/template/typeahead/typeahead-user-match.html'"&gt;&lt;/script&gt; &lt;!-- endinjector --&gt; </code></pre> <p>These templates are put under the <strong>JavaScript</strong> files. I have tried them above and still it doesn't work. Does anyone know why?</p>
3
1,232
Using JAVA to save data to Oracle table with TIMESTAMP WITH ZONED TIME column
<p>I am trying to find a Java Time Type that can be persisted to a column of type TIMESTAMP WITH TIME ZONE in the Oracle DB. The Java type needs to have the Time Zone as part of it. Because of the way the application was written, the Java Calendar type was used (also, the Java Calendar type has Time Zone that is part of it)</p> <p><strong>TRIAL ONE:</strong></p> <p>I did try to use the Calendar directly (with no serializer) with this code:</p> <p>dateStr was in a pattern of: <code>"MM-dd-yyyy hh:mm:ss a"</code> ZoneLoc was for the timezone: ex: <code>America/Chicago</code>, <code>US/Eastern</code>, etc.</p> <pre><code>public Calendar convDateStrWithZoneTOCalendar(String dateStr, String ZoneLoc) throws Exception { String string = dateStr; String pattern = this.getPattern(); Date date = new SimpleDateFormat(pattern).parse(string); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); TimeZone tz = TimeZone.getTimeZone(ZoneLoc); calendar.setTimeZone( tz ); return calendar; } </code></pre> <p>when using this, the correct Zone Location was not set. For example, I would try to set ZoneLoc to US/Hawaii and when data was saved to the DB, it would be something like 23-SEP-19 10.03.11.000000 AM -05:00 And (-05:00) does not represent US/Hawaii</p> <p><strong>TRIAL TWO</strong></p> <p>It is for this reason why the attribute-conversion route was tried. In this case, there is an attempt to convert Calendar to ZoneDateTime. </p> <p>I had seen this in another message noting: </p> <blockquote> <p>Add @Convert(converter=OracleZonedDateTimeSeriliazer.class) on top of your createdOn attribute on ur Entity class.</p> </blockquote> <p>But, as mentioned above, Calendar is being used as part of the entity and not ZonedDateTime</p> <p><strong>the way the entity class is defined now. Before (when using the ( convDateStrWithZoneTOCalendar above), the "@Convert" items were not present</strong></p> <pre><code>@Entity @Table(name = "LAWNCORRJOB", schema = "ORAAPPS", uniqueConstraints = @UniqueConstraint(columnNames = { "TENANTID", "GENERATEDJOBNO" })) public class Lawncorrjob implements java.io.Serializable { private static final long serialVersionUID = -8207025830028821136L; .... @Convert( converter = OracleCalendarZoneDateTimeSerializer.class, disableConversion = false ) private Calendar schedfirstdayts; @Convert( converter = OracleCalendarZoneDateTimeSerializer.class, disableConversion = false ) private Calendar schedlastdayts; ... } </code></pre> <p><strong>the converter being used: converts Calendar to ZonedDateTime (under Oracle)</strong></p> <pre><code>@Converter(autoApply = true) public class OracleCalendarZoneDateTimeSerializer implements AttributeConverter&lt;Calendar, ZonedDateTime&gt; { @Override public ZonedDateTime convertToDatabaseColumn(Calendar attribute) { if (attribute == null) return null; // get the timezone TimeZone tz = attribute.getTimeZone(); // use the timezone to specify the area location // ex: For example, TimeZone.getTimeZone("GMT-8").getID() returns // "GMT-08:00". ZonedDateTime xzdt = ZonedDateTime.of(attribute.get(Calendar.YEAR), attribute.get(Calendar.MONTH), attribute.get(Calendar.DAY_OF_MONTH) + 1, attribute.get(Calendar.HOUR_OF_DAY), attribute.get(Calendar.MINUTE), attribute.get(Calendar.SECOND), attribute.get(Calendar.MILLISECOND), ZoneId.of(tz.getID())); return xzdt; } @Override public Calendar convertToEntityAttribute(ZonedDateTime dbData) { GregorianCalendar newcal = DateTimeUtils.toGregorianCalendar(dbData); return newcal; } } </code></pre> <p>But, when executing this code, I get an error:</p> <blockquote> <p>Error Message: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction CAUSE : javax.persistence.RollbackException: Error while committing the transaction",</p> </blockquote> <p>So, is there any way I can fix either option to get this all working?</p> <p>Any help, hints or advice is appreciated.</p> <p>TIA</p>
3
1,525
JQGrid 5.1 - getCell returns entire html instead of selected Combo box value
<p>My project is Spring MVC + Hibernate + MySQL and JSP and JQGrid 5.1 as a front end. I am facing typical situation where, in JQGrid <strong>delete row</strong> functionality, I want to pass two more parameters to controller in addition to 'oper' and 'id'. One parameter is string and I am able to pass it without any issue, however another parameter is a selected value from the combo box, here in the following code segment, I get the entire HTML instead of simple selected value of combo box item.</p> <p>resultant HTML which I am getting as a selected value of 'cmpcode' is as below:</p> <pre><code>&lt;select role="select" class="editable inline-edit-cell ui-widget-content ui-corner-all" id="3_cmpcode" name="cmpcode" rowid="3"&gt;null&lt;option value="1" role="option"&gt;Test Company&lt;/option&gt;&lt;option value="2" role="option"&gt;Test-2-new&lt;/option&gt;&lt;option value="3" role="option"&gt;Niyogi Enterprise&lt;/option&gt;&lt;option value="4" role="option"&gt;Test-4&lt;/option&gt;&lt;option value="5" role="option"&gt;SySoft Computers&lt;/option&gt;&lt;option value="6" role="option"&gt;Rohi-Nirag&lt;/option&gt;&lt;option value="7" role="option"&gt;TYB and Co&lt;/option&gt;&lt;/select&gt; </code></pre> <p>Code segment for delete row is as below:</p> <pre><code> { caption: "Delete Branch Master", msg: "Delete selected Branch?", bSubmit: "Delete", bCancel: "Cancel", reloadAfterSubmit:true, closeOnEscape:true, onclickSubmit : function(eparams) { var rowData = $("#list").jqGrid('getRowData', row_selected); var retarr = {'brcode':rowData['brcode'],'cmpcode':rowData['cmpcode']}; return retarr; } </code></pre> <p>Here, cmpcode is a combo box in JQGrid and its model is as below:</p> <pre><code>colModel:[ {name:'brcode',index:'brcode', width:50, editable:true, editrules:{required:true}, editoptions:{size:10}, formoptions:{elmprefix:'*'}}, {name:'brname',index:'brname', width:100, editable:true, editrules:{required:true}, editoptions:{size:30}, formoptions:{elmprefix:'*'}}, {name:'bradd1',index:'bradd1', width:100, editable:true, editoptions:{size:30, maxlength:60}, formoptions:{elmprefix:'*'}}, {name:'bradd2',index:'bradd2', width:100, editable:true, editoptions:{size:30, maxlength: 60}, formoptions:{elmprefix:'*'}}, {name:'brcity',index:'brcity', width:50, editable:true, editoptions:{size:20, maxlength:30}, formoptions:{elmprefix:'*'}}, {name:'brpin',index:'brpin', width:50, editable:true, editoptions:{size:20,maxlenght:6}, editrules:{required:true,number:true},formoptions:{elmprefix:'*'}}, {name:'bremail',index:'bremail', width:75, editable:true, editoptions:{size:30}, editrules:{required:true,email:true}, formoptions:{elmprefix:'*'}}, {name:'brcontactperson',index:'brcontactperson', width:75, editable:true, editoptions:{size:30}, formoptions:{elmprefix:'*'}}, {name:'cmpcode',index:'cmpcode',editable:true,edittype:'select',editoptions:{dataUrl:"/NioERPJ/admin/branchmstmgmt/listCmps"},formoptions:{elmprefix:'*'}} </code></pre> <p>I want to get selected value of combo box, which I am not getting, please guide me, I have also tried through 'getCell' method, but not getting value.</p>
3
1,467
Error: ```Uncaught ReferenceError: am4core is not defined``` while creating Amcharts 4 chart
<p>when creating a column chart using the Amcharts4 library I get the following error message:</p> <p><code>Uncaught ReferenceError: am4core is not defined</code></p> <p>My code is as follows:</p> <p><strong>JS</strong></p> <pre><code>am4core.ready(function() { // Themes begin am4core.useTheme(am4themes_animated); // Themes end // Create chart instance var chart = am4core.create(&quot;chartdiv&quot;, am4charts.XYChart); var chartData = [{ &quot;category&quot;: 2009, &quot;income&quot;: 23.5, &quot;url&quot;: &quot;#&quot;, &quot;description&quot;: &quot;click to drill-down&quot;, &quot;months&quot;: [{ &quot;category&quot;: 1, &quot;income&quot;: 1 }, { &quot;category&quot;: 2, &quot;income&quot;: 2 }, { &quot;category&quot;: 3, &quot;income&quot;: 1 }, { &quot;category&quot;: 4, &quot;income&quot;: 3 }] }, { &quot;category&quot;: 2010, &quot;income&quot;: 26.2, &quot;url&quot;: &quot;#&quot;, &quot;description&quot;: &quot;click to drill-down&quot;, &quot;months&quot;: [{ &quot;category&quot;: 1, &quot;income&quot;: 4 }, { &quot;category&quot;: 2, &quot;income&quot;: 3 }, { &quot;category&quot;: 3, &quot;income&quot;: 1 }, { &quot;category&quot;: 4, &quot;income&quot;: 4 }] }, { &quot;category&quot;: 2011, &quot;income&quot;: 30.1, &quot;url&quot;: &quot;#&quot;, &quot;description&quot;: &quot;click to drill-down&quot;, &quot;months&quot;: [{ &quot;category&quot;: 1, &quot;income&quot;: 2 }, { &quot;category&quot;: 2, &quot;income&quot;: 3 }, { &quot;category&quot;: 3, &quot;income&quot;: 1 }] }]; chart.data = chartData; // Create axes var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis()); categoryAxis.dataFields.category = &quot;category&quot;; categoryAxis.renderer.grid.template.location = 0; categoryAxis.renderer.minGridDistance = 30; categoryAxis.numberFormatter.numberFormat = &quot;#&quot;; categoryAxis.renderer.labels.template.adapter.add(&quot;dy&quot;, function(dy, target) { if (target.dataItem &amp;&amp; target.dataItem.index &amp; 2 == 2) { return dy + 25; } return dy; }); var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); // Create series var series = chart.series.push(new am4charts.ColumnSeries()); series.dataFields.valueY = &quot;income&quot;; series.dataFields.categoryX = &quot;category&quot;; series.name = &quot;Income&quot;; series.columns.template.tooltipText = &quot;{categoryX}: [bold]{valueY}[/]&quot;; series.columns.template.fillOpacity = .8; series.columns.template.propertyFields.url = &quot;url&quot;; var columnTemplate = series.columns.template; columnTemplate.strokeWidth = 2; columnTemplate.strokeOpacity = 1; var title = chart.titles.create(); title.text = &quot;Yearly Data&quot;; var resetLabel = chart.plotContainer.createChild(am4core.Label); resetLabel.text = &quot;[bold]&lt;&lt; Back to Yearly Data[/]&quot;; resetLabel.x = 20; resetLabel.y = 20; resetLabel.cursorOverStyle = am4core.MouseCursorStyle.pointer; resetLabel.hide(); resetLabel.events.on('hit', function(ev) { resetLabel.hide(); ev.target.baseSprite.titles.getIndex(0).text = &quot;Yearly Data&quot;; ev.target.baseSprite.data = chartData; }); series.columns.template.events.on(&quot;hit&quot;, function(ev) { if ('object' === typeof ev.target.dataItem.dataContext.months) { // update the chart title ev.target.baseSprite.titles.getIndex(0).text = ev.target.dataItem.dataContext.category + ' monthly data'; // set the monthly data for the clicked month ev.target.baseSprite.data = ev.target.dataItem.dataContext.months resetLabel.show(); } }, this); }); </code></pre> <p><strong>HTML</strong>:</p> <pre><code>&lt;body&gt; &lt;div class=&quot;titel&quot;&gt; &lt;p&gt; Title&lt;/p&gt; &lt;/div&gt; &lt;script src=&quot;https://www.cdn.amcharts.com/lib/4/core.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://www.cdn.amcharts.com/lib/4/index.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://www.cdn.amcharts.com/lib/4/themes/animated.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;./test_drill_down.js&quot;&gt;&lt;/script&gt; &lt;div id=&quot;chartdiv&quot;&gt; &lt;/div&gt; &lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But I do not understand why I get this error, the modules are loaded before the javascript chart script. I am using the same HTML file as I used in other graphs, and there it did work properly.</p> <p>What am I doing wrong?</p>
3
2,255
change image in every three days using php
<p>I am creating a wordpress widget. This will allow user to upload the image url of eight different picture. Now I want to change the image everty three days and start from begining after eight one for infinite time.</p> <p>I manage to get the start of the first image. let sat that is : 2014/07/28</p> <p>I have applied this logic:</p> <pre><code>$date = $start_date; $date = strtotime($date); $date = strtotime("+3 day", $date); $end_date = date('Y-m-d', $date); $begin = new DateTime( $start_date ); $end = new DateTime(''); $end = $end-&gt;modify( '+1 day' ); $interval = new DateInterval('P1D'); $daterange = new DatePeriod($begin, $interval ,$end); if($start_date &lt;= $end_date &amp;&amp; $end_date &gt; date('Y-m-d')) { $image_number = 1; }else{ $i = 1; $j = 1; foreach($daterange as $date){ if($i%3 == 0){ echo $image_number = $j; $j++; if($j &gt; 8){ $j = 1; } } $i++; } } </code></pre> <p>?> " alt=""></p> <p>Can anybody tell me what is wrong with the code.</p> <p>Thank you everybody in advance for your valuable time.</p>
3
1,172
OpenGL + Qt 4.8 is not drawing anything
<p>I've been trying to use OpenGL in Qt with shaders and a simple vertex array. I basically want a plain to be drawn in the middle of the screen but nothing appears when I run the program. I'm basing my code in the "Texture" example of Qt, everything looks the same to me, but It's not working!</p> <p>Here's the code of my glwidget.cpp:</p> <pre><code>#include "glwidget.h" GLWidget::GLWidget(QWidget *parent):QGLWidget(parent) { timer.start(10); //connect(&amp;timer, SIGNAL(timeout()), this, SLOT(updateGL())); Object aux; QVector3D auxV; auxV.setX(0.4); auxV.setY(0.4); auxV.setZ(1.0); aux.vertices.append(auxV); auxV.setX(0.4); auxV.setY(-0.4); auxV.setZ(1.0); aux.vertices.append(auxV); auxV.setX(-0.4); auxV.setY(-0.4); auxV.setZ(1.0); aux.vertices.append(auxV); auxV.setX(-0.4); auxV.setY(-0.4); auxV.setZ(1.0); aux.vertices.append(auxV); Objects.append(aux); } GLWidget::~GLWidget() { } void GLWidget::initializeGL() { #define PROGRAM_VERTEX_ATTRIBUTE 0 printf("Objects Size: %d\nObj1 Size: %d\n", Objects.size(), Objects.at(0).vertices.size()); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); //printf("Version: %s\n", glGetString(GL_VERSION)); vShader= new QGLShader (QGLShader::Vertex, this); vShader-&gt;compileSourceFile("../src/shaders/editorVshader.glsl"); fShader= new QGLShader (QGLShader::Fragment, this); fShader-&gt;compileSourceFile("../src/shaders/editorFshader.glsl"); editor= new QGLShaderProgram (this); editor-&gt;addShader(vShader); editor-&gt;addShader(fShader); editor-&gt;bindAttributeLocation("vertices", PROGRAM_VERTEX_ATTRIBUTE); editor-&gt;link(); editor-&gt;bind(); } void GLWidget::paintGL() { glClearColor(0.4765625, 0.54296875, 0.6171875, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -10.0f); glVertexPointer(3, GL_FLOAT, 0, Objects.at(0).vertices.constData()); glEnableClientState(GL_VERTEX_ARRAY); QMatrix4x4 auxM; auxM.ortho(-0.5, 0.5, 0.5, -0.5, 4.0, -15.0); auxM.translate(0.0f, 0.0f, -10.0f); editor-&gt;setUniformValue("modelmatrix", auxM); editor-&gt;enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE); //editor-&gt;enableAttributeArray(editor-&gt;attributeLocation("vertices")); //editor-&gt;setAttributeArray(editor-&gt;attributeLocation("vertices"), Objects.at(0).vertices.constData(), 3); editor-&gt;setAttributeArray (PROGRAM_VERTEX_ATTRIBUTE, Objects.at(0).vertices.constData()); glDrawArrays(GL_QUADS, 0, 4); } void GLWidget::resizeGL(int w, int h) { int side = qMin(w, h); glViewport((w - side) / 2, (h - side) / 2, side, side); //glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-0.5, 0.5, -0.5, 0.5, 4.0, -15.0); glMatrixMode(GL_MODELVIEW); updateGL(); } </code></pre> <p>And here are my vShader:</p> <pre><code>attribute highp vec4 vertices; attribute highp mat4x4 modelmatrix; void main (void) { gl_Position= modelmatrix*vertices; } </code></pre> <p>And my fShader:</p> <pre><code>void main(void) { gl_FragColor= vec4(0.0, 0.1, 1.0, 1.0); } </code></pre> <p>Do you see the error in there?</p>
3
1,443
Array queries give wrong answer
<p>I have a problem and I have no idea how to start, here it is:</p> <blockquote> <p>You are given a permutation of 1,2,...,n. You will be given q queries, each query being one of 2 types:</p> <p>Type 1: swap elements at positions i and j<br> Type 2: given a position i, print the length of the longest subarray containing the ith element such that the sum of its elements doesn't exceed n</p> <h3>Input</h3> <p>The first line contains 2 integers n and q (1≤n,q≤105).</p> <p>The next line contains the n integers of the permutation p1,…,pn (1≤pi≤n).</p> <p>The next q lines contain queries in the format:</p> <p>Type 1: 1 i j (1≤i,j≤n)<br /> Type 2: 2 i (1≤i≤n)</p> <h3>Output</h3> <p>For each query of type 2, print the required answer.</p> </blockquote> <p>Here is my code so far, but it gives me the wrong answer on the last few cases:</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; long long atMostSum(int arr[], int n, int k, int a) { int sum = arr[a]; int cnt = 1, maxcnt = 1; for (int i = 0; i &lt; n; i++) { if ((sum + arr[i]) &lt;= k) { sum += arr[i]; cnt++; } else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } maxcnt = std::max(cnt, maxcnt); } return maxcnt - 1; } int main(void) { int n, q; std::cin &gt;&gt; n &gt;&gt; q; int p[n]; for(int i = 0; i &lt; n ; i++) { std::cin &gt;&gt; p[i]; } for (int i = 0; i &lt; n; i ++) { int a; std::cin &gt;&gt; a; if (a == 2) { int m; std::cin &gt;&gt; m; std::cout &lt;&lt; atMostSum(p, n, n, m) &lt;&lt; &quot;\n&quot;; } else { int l, f; std::cin &gt;&gt; l &gt;&gt; f; int temp; temp = p[l]; p[l] = p[f]; p[f] = temp; } } } </code></pre> <h3>Sample Input</h3> <pre><code>3 3 1 2 3 2 1 2 2 2 3 </code></pre> <h3>Sample Output</h3> <pre><code>2 2 1 </code></pre>
3
1,044
compiler says member function not defined however it is included in the header file c++
<p>Compiler says member function not defined however it is included in the header file c++. I have about 10 functions and one function find_similar the compiler says undeclared variable on the tester implementation file. The purpose of the program is to check the validity of two entries from the main.cpp/test file. I made a program which checks the entries from the test file.</p> <p>CarInventory.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;iomanip&gt; #include &lt;string.h&gt; #include &quot;CarInventory.h&quot; using namespace std; using namespace sdds; void CarInventory::resetInfo() { m_type = nullptr; m_brand = nullptr; m_model = nullptr; m_year = 0; m_code = 0; m_price = 0; } CarInventory::CarInventory() { resetInfo(); } CarInventory::CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price) { resetInfo(); setInfo(type, brand, model, year, code, price); } CarInventory::CarInventory(const char* type, const char* brand, const char* model) { resetInfo(); setInfo(type, brand, model, 2022, 100, 1); } CarInventory::~CarInventory() { delete[] m_type; delete[] m_brand; delete[] m_model; } CarInventory&amp; CarInventory::setInfo(const char* type, const char* brand, const char* model, int year, int code, double price) { if (type == nullptr || brand == nullptr || model == nullptr || year &lt; 1990 || code &lt; 100 || price &lt; 0) { resetInfo(); } else { delete[] m_type; delete[] m_brand; delete[] m_model; m_type = new char[strlen(type) + 1]; strcpy_s(m_type, sizeof(type), type); m_brand = new char[strlen(brand) + 1]; strcpy_s(m_brand, sizeof(brand), brand); m_model = new char[strlen(model) + 1]; strcpy_s(m_model, sizeof(m_model), model); m_year = year; m_code = code; m_price = price; } return *this; } bool CarInventory::isValid() const { return m_type != nullptr &amp;&amp; m_brand != nullptr &amp;&amp; m_model != nullptr &amp;&amp; m_year &gt;= 1990 &amp;&amp; m_code &gt;= 100 &amp;&amp; m_price &gt;= 0; } bool sdds::CarInventory::find_similar(CarInventory car[], const int num_cars) { return false; } void CarInventory::printInfo() const { std::cout &lt;&lt; &quot;|&quot; &lt;&lt; std::setw(12) &lt;&lt; m_type &lt;&lt; &quot;|&quot; &lt;&lt; std::setw(18) &lt;&lt; m_brand &lt;&lt; &quot;|&quot; &lt;&lt; std::setw(18) &lt;&lt; m_model &lt;&lt; &quot;|&quot; &lt;&lt; std::setw(6) &lt;&lt; m_year &lt;&lt; &quot;|&quot; &lt;&lt; std::setw(6) &lt;&lt; m_code &lt;&lt; &quot;|&quot; &lt;&lt; std::setw(11) &lt;&lt; m_price &lt;&lt; &quot;|&quot; &lt;&lt; std::endl; } bool CarInventory::isSimilarTo(const CarInventory&amp; car) const { return m_type == car.m_type &amp;&amp; m_brand == car.m_brand &amp;&amp; m_model == car.m_model &amp;&amp; m_year == car.m_year; } namespace sdds { bool find_similar(CarInventory car[], const int num_cars) { for (int i = 0; i &lt; num_cars; i++) { for (int j = i + 1; j &lt; num_cars; j++) { if (car[i].isSimilarTo(car[j])) { return true; } } } return false; } } </code></pre> <p>Header File</p> <pre><code>#ifndef CARINVENTORY_H #define CARINVENTORY_H #define _CRT_SECURE_NO_WARNINGS namespace sdds { class CarInventory { char* m_type; char* m_brand; char* m_model; int m_year; int m_code; double m_price; void resetInfo(); public: CarInventory(); CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price); CarInventory(const char* type, const char* brand, const char* model); bool isSimilarTo(const CarInventory&amp; car) const; ~CarInventory(); CarInventory&amp; setInfo(const char* type, const char* brand, const char* model, int year, int code, double price); void printInfo() const; bool isValid() const; bool find_similar(CarInventory car[], const int num_cars); }; } #endif </code></pre> <p>main/tester file</p> <pre><code> #include&lt;iostream&gt; #include&lt;iomanip&gt; #include &quot;CarInventory.h&quot; using namespace std; using namespace sdds; int main() { const int num_cars = 6; bool invalid_data = false; CarInventory cars[num_cars] = { {}, {&quot;suv&quot;, &quot;volvo&quot;, &quot;xc90&quot;}, {&quot;Truck&quot;, &quot;Ford&quot;, &quot;F 150&quot;, 2021, 105, 55000}, {&quot;Sedan&quot;, &quot;BMW&quot;, &quot;M550i&quot;, 2022, 101, 91000}, {&quot;Truck&quot;, &quot;Tesla&quot;, &quot;Cybertruck&quot;, 2021, 102, 65000}, {&quot;Sedan&quot;, &quot;BMW&quot;, &quot;M550i&quot;} }; if (cars[2].setInfo(&quot;SUV&quot;, &quot;Volvo&quot;, &quot;XC90&quot;, 2019, 109, 80000).isValid()) { cout &lt;&lt; &quot;Information was set correctly!&quot; &lt;&lt; endl; } else { cout &lt;&lt; &quot;Information was set incorrectly!&quot; &lt;&lt; endl; } if (cars[1].setInfo(&quot;SUV&quot;, &quot;Volvo&quot;, &quot;XC90&quot;, 1234, 1, 1).isValid()) { cout &lt;&lt; &quot;Information was set correctly!&quot; &lt;&lt; endl; } else { cout &lt;&lt; &quot;Information was set incorrectly!&quot; &lt;&lt; endl; } cout &lt;&lt; setw(60) &lt;&lt; &quot;----- Car Inventory Information -----&quot; &lt;&lt; endl &lt;&lt; endl;; cout &lt;&lt; &quot;| Type | Brand | Model | Year | Code | Price |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;+------------+------------------+------------------+------+------+-----------+&quot; &lt;&lt; endl; for (int i = 0; i &lt; num_cars; i++) { if (cars[i].isValid()) cars[i].printInfo(); else invalid_data = true; } if (invalid_data) { cout &lt;&lt; endl; cout &lt;&lt; setfill('*') &lt;&lt; setw(60) &lt;&lt; &quot;*&quot; &lt;&lt; endl; cout &lt;&lt; &quot;* WARNING: There are invalid data in the inventory! *&quot; &lt;&lt; endl; cout &lt;&lt; setfill('*') &lt;&lt; setw(60) &lt;&lt; &quot;*&quot; &lt;&lt; endl; } if (find_similar)(cars, num_cars)) { cout &lt;&lt; endl; cout &lt;&lt; setfill('+') &lt;&lt; setw(60) &lt;&lt; &quot;+&quot; &lt;&lt; endl; cout &lt;&lt; &quot;+ WARNING: There are similar entries in the inventory! +&quot; &lt;&lt; endl; cout &lt;&lt; setfill('+') &lt;&lt; setw(60) &lt;&lt; &quot;+&quot; &lt;&lt; endl; } return 0; } </code></pre> <p>Error message: <a href="https://i.stack.imgur.com/ftilX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ftilX.png" alt="enter image description here" /></a></p>
3
3,195
list<lab_result_cash_view> does not contain a definition for 'Patient_Name ' and no extension method 'Patient_Name '
<p>I want to select data from multiple tables and view. I created the following class Orders tables:</p> <pre><code>public class Orders_Tables { public List&lt;Lab_Orders&gt; LabOrders { get; set; } public List&lt;Lab_orders_Cash&gt; LabOrdersCash { get; set; } public List&lt;Lab_Sample_status&gt; LabOrderStatus { get; set; } public List&lt;LAB_RESULTS&gt; LabResults { get; set; } public List&lt;LabTests&gt; labtests { get; set; } public List&lt;LAB_RESULTS_CLINIC_VIEW&gt; labViewResult { get; set; } public List&lt;LAB_RESULT_CASH_VIEW&gt; labCashView { get; set; } public List&lt;LAB_PARASITOLOGY_VIEW&gt; labparaview { get; set; } public List&lt;Lab_Hematology_Samples&gt; LabSamples { get; set; } public List&lt;Patients&gt; patients { get; set; } public Orders_Tables() { this.LabOrders = new List&lt;Lab_Orders&gt;(); this.LabOrdersCash = new List&lt;Lab_orders_Cash&gt;(); this.LabOrderStatus = new List&lt;Lab_Sample_status&gt;(); this.LabResults = new List&lt;LAB_RESULTS&gt;(); this.labtests = new List&lt;LabTests&gt;(); this.labViewResult = new List&lt;LAB_RESULTS_CLINIC_VIEW&gt;(); this.labCashView = new List&lt;LAB_RESULT_CASH_VIEW&gt;(); this.labparaview = new List&lt;LAB_PARASITOLOGY_VIEW&gt;(); this.LabSamples = new List&lt;Lab_Hematology_Samples&gt;(); this.patients = new List&lt;Patients&gt;(); } } </code></pre> <p>And this is the controller : </p> <pre><code>public ActionResult Cash(int id) { Orders_Tables tables = new Orders_Tables(); tables.labCashView = db.LAB_RESULT_CASH_VIEW.Where(c =&gt; c.order_number == id).ToList(); tables.labparaview = db.LAB_PARASITOLOGY_VIEW.Where(p =&gt; p.ORDER_ID == id).ToList(); return View(tables); } </code></pre> <p>Then I created empty view , the error when i try to select columns i cannot find it and the error appeared when i paste the column name , this is the view code :</p> <pre><code>@model IEnumerable&lt;AljawdahNewSite.Models.Orders_Tables&gt; @{ ViewBag.Title = "Cash"; Layout = "~/Views/Shared/_LayoutPatients.cshtml"; } &lt;div id="divprint"&gt; &lt;div style="margin-left:15px"&gt; &lt;hr /&gt; &lt;dl class="horizontal" style="border:solid"&gt; &lt;dt style="width: 20%;display: inline-block;color:blue;"&gt;@Html.DisplayNameFor(model =&gt; model.labCashView.Patient_Name)&lt;/dt&gt; &lt;dd style="width: 25%;display: inline-block;margin: 0px;margin-left:-50px"&gt;@Html.DisplayFor(model =&gt; model.FirstOrDefault().labCashView.Patient_Name)&lt;/dd&gt; &lt;dt style="width: 22%;display: inline-block;color:blue;"&gt;@Html.DisplayNameFor(model =&gt; model.labCashView.Customer_Name)&lt;/dt&gt; &lt;dd style="width: 25%;display: inline-block;margin: 0px;margin-left:0px"&gt;@Html.DisplayFor(model =&gt; model.FirstOrDefault().labCashView.Customer_Name)&lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; </code></pre> <p>The error appeared when i paste the column name : Patient_Name , Customer_Name and so on ...</p> <blockquote> <p><strong>list lab_result_cash_view does not contain a definition for 'Patient_Name ' and no extension method 'Patient_Name ' accepting a first argument of type 'list lab_result_cash_view could not be found are you missing a using directive or an assembly reference</strong></p> </blockquote> <p>How i will select column name in the view ? </p>
3
1,630
BOOST_ASSERT failure raised in boost::fiber on Visual Studio "Debug" build
<p>I run into issue with boost::fiber. My code is based on &quot;work_stealing.cpp&quot; example of boost::fiber. I decorated it a little bit. It can work now on Windows Subsystem Linux Ubuntu for both Debug and Release build. In fact, till last night it can work on Windows Visual Studio build... But today, we I attempt to run some test, a BOOST ASSERT failure raised on Debug build. The Release build can work...</p> <p>I don't know why... so, do anyone know something about this? Why it's only on Windows Debug build? What did I do wrong?</p> <p>I am using cmake as build tool, Visual Studio 2019 Community Edition as development tool. I also test on WSL Ubuntu 20.04 and macOS 10.15.x(cannot recall it...).</p> <p>Thank you.</p> <p>-Quan</p> <p>The failure raised from the below code of boost:</p> <pre><code>// &lt;boost&gt;/lib/fiber/src/scheduler.cpp ... void scheduler::detach_worker_context( context * ctx) noexcept { BOOST_ASSERT( nullptr != ctx); BOOST_ASSERT( ! ctx-&gt;ready_is_linked() ); #if ! defined(BOOST_FIBERS_NO_ATOMICS) BOOST_ASSERT( ! ctx-&gt;remote_ready_is_linked() ); #endif BOOST_ASSERT( ! ctx-&gt;sleep_is_linked() ); BOOST_ASSERT( ! ctx-&gt;terminated_is_linked() ); BOOST_ASSERT( ! ctx-&gt;wait_is_linked() ); // &lt;-- [THE ERROR RAISED FROM HERE!] BOOST_ASSERT( ctx-&gt;worker_is_linked() ); BOOST_ASSERT( ! ctx-&gt;is_context( type::pinned_context) ); ctx-&gt;worker_unlink(); BOOST_ASSERT( ! ctx-&gt;worker_is_linked() ); ctx-&gt;scheduler_ = nullptr; // a detached context must not belong to any queue } ... </code></pre> <p>And my code is like below (I removed some not-related parts...):</p> <pre><code>//coroutine.h class CoroutineManager { ... typedef std::unique_lock&lt;std::mutex&gt; lock_type; typedef boost::fibers::algo::work_stealing scheduler_algorithm; typedef boost::fibers::default_stack stack_type; ... void wait() { lock_type shutdown_lock(shutdown_mutex); shutdown_condition.wait(shutdown_lock, [this]() { return 1 == this-&gt;shutdown_flag; }); BOOST_ASSERT(1 == this-&gt;shutdown_flag); } void shutdown(bool wait = true) { lock_type shutdown_lock(shutdown_mutex); this-&gt;shutdown_flag = 1; shutdown_lock.unlock(); this-&gt;shutdown_condition.notify_all(); if (wait) { for (std::thread&amp; t : threads) { if (t.joinable()) { t.join(); } } } } ... template &lt;class TaskType&gt; void submit(const TaskType&amp; task) { boost::fibers::fiber(boost::fibers::launch::dispatch, std::allocator_arg, stack_type(this-&gt;stack_size), task).detach(); } ... void init() { if (verbose) spdlog::info(&quot;INIT THREAD({0}) STARTED.&quot;, std::this_thread::get_id()); for (int i = 0; i &lt; (this-&gt;thread_count - 1); ++i) { threads.push_back(std::thread(&amp;CoroutineManager::thread, this)); } boost::fibers::use_scheduling_algorithm&lt;scheduler_algorithm&gt;(this-&gt;thread_count); this-&gt;start_barrier.wait(); } void dispose() { if (verbose) spdlog::info(&quot;INIT THREAD({0}) DISPOSED.&quot;, std::this_thread::get_id()); } void thread() { if(verbose) spdlog::info(&quot;WORKER THREAD({0}) STARTED.&quot;, std::this_thread::get_id()); boost::fibers::use_scheduling_algorithm&lt;scheduler_algorithm&gt;(this-&gt;thread_count); this-&gt;start_barrier.wait(); this-&gt;wait(); if (verbose) spdlog::info(&quot;WORKER THREAD({0}) DISPOSED.&quot;, std::this_thread::get_id()); } ... }; - - - - - - - - - - - - - - - - - - - - - - - // coroutine_test.cpp ... int main(int argc, char* argv[]) { init_file_logger(&quot;coroutine_test.log&quot;); time_tracker tracker(&quot;[coroutine_test.main]&quot;); typedef std::thread::id tid_t; typedef boost::fibers::fiber::id fid_t; typedef boost::fibers::buffered_channel&lt;std::tuple&lt;tid_t, fid_t, int&gt;&gt; channel_t; CoroutineManager manager(std::thread::hardware_concurrency(), 1024 * 1024 * 8, true); const int N = 1; channel_t chan { 8 }; boost::fibers::barrier done_flag(2); manager.submit([&amp;chan, &amp;done_flag]() { std::tuple&lt;tid_t, fid_t, int&gt; p; while( boost::fibers::channel_op_status::success == chan.pop_wait_for(p, std::chrono::milliseconds(100))) { spdlog::info(&quot;[thead({0}) : fiber({1}) from {2}]&quot;, std::get&lt;0&gt;(p), std::get&lt;1&gt;(p), std::get&lt;2&gt;(p)); } done_flag.wait(); }); for (int i = 0; i &lt; N; ++i) { manager.submit([&amp;chan, i]() { for (int j = 0; j &lt; 1000; ++j) { chan.push(std::move(std::make_tuple(std::this_thread::get_id(), boost::this_fiber::get_id(), i))); boost::this_fiber::yield(); } }); } done_flag.wait(); spdlog::info(&quot;-START TO SHUTDOWN-&quot;); manager.shutdown(); spdlog::info(&quot;-END-&quot;); return 0; } </code></pre> <p>[UPDATE] <a href="https://i.stack.imgur.com/acOub.png" rel="nofollow noreferrer">Add a snapshot to explain my situation more clearly...</a></p>
3
2,134
Setup torque/moab cluster to use multiple cores per node with a single loop
<p>This is a followup on [<a href="https://stackoverflow.com/questions/17288379/how-to-set-up-dosnow-and-sock-cluster-with-torque-moab-scheduler/17299302?noredirect=1#comment44364759_17299302]">How to set up doSNOW and SOCK cluster with Torque/MOAB scheduler?</a></p> <p>I have a memory limited script that only uses 1 <code>foreach</code> loop but I'd like to get 2 iterations running on node1 and 2 iterations running on node2. The above linked question allows you to start a SOCK cluster to each node for the outer loop and then MC cluster for the inner loop and I think doesn't make use of the multiple cores on each node. I get the warning message <code>Warning message: closing unused connection 3 (&lt;-compute-1-30.local:11880)</code></p> <p>if I do <code>registerDoMC(2)</code> if I do this after <code>registerDoSNOW(cl)</code> Thanks.</p> <p>EDIT: The solution from the previous question works fine for the problem asked. see my example below for what I want.</p> <p>starting an interactive job with 2 nodes and 2cores per processor:</p> <pre><code>qsub -I -l nodes=2:ppn=2 </code></pre> <p>after starting R:</p> <pre><code>library(doParallel) f &lt;- Sys.getenv('PBS_NODEFILE') nodes &lt;- unique(if (nzchar(f)) readLines(f) else 'localhost') print(nodes) </code></pre> <p>here are the two nodes I"m running on:</p> <pre><code>[1] "compute-3-15" "compute-1-32" </code></pre> <p>start the sock cluster on these two nodes:</p> <pre><code>cl &lt;- makePSOCKcluster(nodes, outfile='') </code></pre> <p>i'm not sure why they both seem to be on <code>compute-3-15</code> .... ?</p> <pre><code>starting worker pid=25473 on compute-3-15.local:11708 at 16:54:17.048 starting worker pid=14746 on compute-3-15.local:11708 at 16:54:17.523 </code></pre> <p>but register the two nodes and run a single foreach loop:</p> <pre><code>registerDoParallel(cl) r=foreach(i=seq(1,6),.combine='c') %dopar% { Sys.info()[['nodename']]} print(r) </code></pre> <p>output of r indicates that both nodes were used though:</p> <pre><code> [1] "compute-3-15.local" "compute-1-32.local" "compute-3-15.local" [4] "compute-1-32.local" "compute-3-15.local" "compute-3-15.local" </code></pre> <p>now, what I'd really like is for that foreach loop to run on 4 cores, 2 on each node.</p> <pre><code>library(doMC) registerDoMC(4) r=foreach(i=seq(1,6),.combine='c') %dopar% { Sys.info()[['nodename']]} print(r) </code></pre> <p>the output indicates that only 1 node was used, but presumably both cores on that one node.</p> <pre><code>[1] "compute-3-15.local" "compute-3-15.local" "compute-3-15.local" [4] "compute-3-15.local" "compute-3-15.local" "compute-3-15.local" </code></pre> <p>How do I get a SINGLE foreach loop to use multiple cores on multiple nodes?</p>
3
1,062
Flower: Set SSL 'verify_mode'
<p><em>Using:</em> Flower 0.9.5 (installed Tornado 6.0.4), Celery 4.4.6, Python 3.7</p> <p>When starting <code>Flower</code> with</p> <pre><code>celery -A myProj flower </code></pre> <p>everything works as expected. Flower serves at <code>http://localhost:5555</code>.</p> <p>When starting <code>Flower</code> with</p> <pre><code>celery -A myProj flower --keyfile=/home/me/cert/key.pem --certfile=/home/me/cert/cert.pem </code></pre> <p>it serves at <code>https://localhost:5555</code> but when trying to access it, Chrome states <code>ERR_CONNECTION_RESET</code> and <code>Flower</code> logs</p> <pre><code>2020-09-16 17:19:37,421 - tornado.general - ERROR - Uncaught exception, closing connection. Traceback (most recent call last): File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 711, in _handle_events self._handle_read() File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 1498, in _handle_read self._do_ssl_handshake() File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 1458, in _do_ssl_handshake if not self._verify_cert(self.socket.getpeercert()): File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 1481, in _verify_cert assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL) UnboundLocalError: local variable 'verify_mode' referenced before assignment 2020-09-16 17:19:37,423 - asyncio - ERROR - Exception in callback None() handle: &lt;Handle cancelled&gt; Traceback (most recent call last): File &quot;/home/me/python/lib/python3.7/asyncio/events.py&quot;, line 88, in _run self._context.run(self._callback, *self._args) File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/platform/asyncio.py&quot;, line 139, in _handle_events handler_func(fileobj, events) File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 711, in _handle_events self._handle_read() File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 1498, in _handle_read self._do_ssl_handshake() File &quot;/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py&quot;, line 1458, in _do_ssl_handshake if not self._verify_cert(self.socket.getpeercert()): File &quot;/home/me/.env/lib/python/site-packages/tornado/iostream.py&quot;, line 1481, in _verify_cert assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL) UnboundLocalError: local variable 'verify_mode' referenced before assignment </code></pre> <p><strong>Note:</strong> Everything works when running Flower with</p> <pre><code>celery -B brokerURL flower --keyfile=/home/me/cert/key.pem --certfile=/home/me/cert/cert.pem </code></pre> <p>In <code>/home/me/.env/lib/python3.7/site-packages/tornado/iostream.py</code> there is:</p> <pre><code>def _verify_cert(self, peercert: Any) -&gt; bool: &quot;&quot;&quot;Returns ``True`` if peercert is valid according to the configured validation mode and hostname. The ssl handshake already tested the certificate for a valid CA signature; the only thing that remains is to check the hostname. &quot;&quot;&quot; if isinstance(self._ssl_options, dict): verify_mode = self._ssl_options.get(&quot;cert_reqs&quot;, ssl.CERT_NONE) elif isinstance(self._ssl_options, ssl.SSLContext): verify_mode = self._ssl_options.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL) # LINE 1481 if verify_mode == ssl.CERT_NONE or self._server_hostname is None: return True cert = self.socket.getpeercert() if cert is None and verify_mode == ssl.CERT_REQUIRED: gen_log.warning(&quot;No SSL certificate given&quot;) return False try: ssl.match_hostname(peercert, self._server_hostname) except ssl.CertificateError as e: gen_log.warning(&quot;Invalid SSL certificate: %s&quot; % e) return False else: return True </code></pre> <p>How can I pass <code>verify_mode = ssl.CERT_REQUIRED</code> to <code>tornado</code> via <code>Flower</code>? Setting it manually inside <code>_verify_cert</code> does work.</p>
3
1,742
React Native navigating between two screens back & forth
<p>I have <strong>Home</strong> screen where we search for an ItemCode, after we search ItemCode it will get details from API &amp; screen will navigate to <strong>Screen 1</strong>(Item Details Screen) &amp; from Screen 1 we have a search for ItemNutrients and after search it will get Nutrients &amp; Navigate to <strong>Screen 2</strong> (Nutrients Screen)</p> <p>In other words</p> <p>Home -&gt; Screen 1 (Item Details Screen) -&gt; Screen 2 (Nutrients Screen)</p> <p>After getting the necessary details from API from search for Item Details &amp; Nutrients, User can navigate between Item Details &amp; Nutrients back and forth..</p> <p>I could navigate from <strong>Screen 1</strong> (item Details) to <strong>Screen2</strong> (Nutrients Screen) and swipe back to <strong>Screen 1</strong> (item Details) but how could I swipe forward to look at <strong>Screen 2</strong> (Nutrients Screen) again without searching for nutrients in <strong>Screen 1</strong> as I already have the data from API for Nutrients.</p> <p>Any ideas on how to implement this ? this is basically navigate to <strong>Screen 1</strong> to <strong>Screen 2</strong> on search from Screen 1 or if <strong>Screen 2</strong> search is already done and we have data so swipe forward should navigate to <strong>Screen 2</strong>, I can have a button to navigate to <strong>Screen 2</strong>, the button on Screen 1 conditinally appears only when we have API data for Nutrients Screen and it will navigate to <strong>Screen 2</strong> on that button click, but i need swipe functionality as well to navigate forward</p> <p>I have Home, Screen 1, Screen 2 in stackNavigator, is it alright or i could use any other navigators to achieve this.</p> <p>I have researched how to do this and can't find it in the docs anywhere. Please let me know if I am missing it somewhere. Thanks!</p> <p>Nutrition Context:</p> <pre><code>import React, { createContext, useState, useEffect } from &quot;react&quot;; export const NutriSyncContext = createContext(); const DEFAULT_IS_NUTRI_SCANNED = false; export const NutriSyncContextProvider = ({ children }) =&gt; { const [isNutritionScanned, setisNutritionScanned] = useState( DEFAULT_IS_NUTRI_SCANNED ); // When we first mount the app we want to get the &quot;latest&quot; conversion data useEffect(() =&gt; { setisNutritionScanned(DEFAULT_IS_NUTRI_SCANNED); }, []); const nutrionScanClick = ({ navigation }) =&gt; { setisNutritionScanned(true); //navigation.navigate(&quot;NutritionFacts&quot;); }; const contextValue = { isNutritionScanned, setisNutritionScanned, nutrionScanClick, }; return ( &lt;NutriSyncContext.Provider value={contextValue}&gt; {children} &lt;/NutriSyncContext.Provider&gt; ); }; </code></pre> <p>inside navigation.js</p> <pre><code>const tabPNMS = createMaterialTopTabNavigator(); function tabPNMSStackScreen() { const { isNutritionScanned } = useContext(NutriSyncContext); console.log(isNutritionScanned); return ( &lt;tabPNMS.Navigator initialRouteName=&quot;PNMSNutrition&quot; tabBar={() =&gt; null}&gt; &lt;tabPNMS.Screen name=&quot;PNMSNutrition&quot; component={PNMSNutrition} /&gt; {isNutritionScanned ? ( &lt;tabPNMS.Screen name=&quot;NutritionFacts&quot; component={NutritionFacts} /&gt; ) : null} &lt;/tabPNMS.Navigator&gt; ); } </code></pre> <p>and In stack Navigation:</p> <pre><code>const SearchStack = createStackNavigator(); const SearchStackScreen = () =&gt; ( &lt;NutriSyncContextProvider&gt; &lt;SearchStack.Navigator initialRouteName=&quot;Search&quot; screenOptions={{ gestureEnabled: false, headerStyle: { backgroundColor: &quot;#101010&quot;, }, headerTitleStyle: { fontWeight: &quot;bold&quot;, }, headerTintColor: &quot;#ffd700&quot;, headerBackTitleVisible: false, //this will hide header back title }} headerMode=&quot;float&quot; &gt; &lt;SearchStack.Screen name=&quot;Search&quot; component={Search} options={({ navigation }) =&gt; ({ title: &quot;Search&quot;, headerTitleAlign: &quot;center&quot;, headerLeft: () =&gt; ( &lt;Entypo name=&quot;menu&quot; size={24} color=&quot;green&quot; onPress={() =&gt; navigation.dispatch(DrawerActions.toggleDrawer())} /&gt; ), })} /&gt; &lt;SearchStack.Screen name=&quot;NutriTabs&quot; options={() =&gt; ({ title: &quot;PNMS&quot;, headerTitleAlign: &quot;center&quot;, })} component={tabPNMSStackScreen} /&gt; &lt;/SearchStack.Navigator&gt; &lt;/NutriSyncContextProvider&gt; ); </code></pre> <p>I have NutriSyncContextProvider around the stack, but when I click the button on my page it will call nutrionScanClick method in context class it works just fine but when i do navigation.navigate to the NutritionFacts tab that is enabled i get error saying NutritionFacts tab doesn't exist</p> <p>I got it working below is the code:</p> <pre><code> const nutrionScanClick = () =&gt; { if (!isNutritionScanned) setisNutritionScanned(true); else { //Make a API call here for new data for the new scanned one's and then navigate navigation.navigate(&quot;NutritionFacts&quot;); } }; useEffect(() =&gt; { if (isNutritionScanned) { navigation.navigate(&quot;NutritionFacts&quot;); } }, [isNutritionScanned]); </code></pre>
3
2,099
SQL Populate a new table from a query
<p>​Hi Guys, I am really new to sql so i am sorry if this sounds stupid.</p> <p>I have a query that shows me all the female drivers from two tables (employee and role each table has 1000 rows in total)</p> <p><strong>employee table</strong></p> <pre><code> 1 Brendon Hayford Male 2 Appolonia Mawer Female 3 Stanly Loachhead Male 4 Kinny Hulcoop Male 5 Alyssa Vose Female 6 Gerrie Cradey Female 7 Katalin Coverly Female 8 Michelina Yukhov Female 9 Abbey Thunnerclif Male 10 Skippy Juett Male 11 Kizzee Bleythin Female 12 Shea Coxhell Male 13 Win Shilstone Male 14 Carita Giddy Female 15 Tiebout Creffield Male </code></pre> <p><strong>role table</strong></p> <pre><code>1 Mechanic 2 Admin 3 Mechanic 4 Admin 5 Admin 6 Mechanic 7 Driver 8 Mechanic 9 Admin 10 Driver 11 Admin 12 Driver 13 Admin 14 Mechanic 15 Mechanic </code></pre> <p><strong>Query</strong></p> <pre><code>SELECT role.idrole, employee.*, role.role FROM employee INNER JOIN role ON idrole=idemployee WHERE role.role=&quot;Driver&quot; AND employee.gender=&quot;Female&quot;; </code></pre> <p>this query return 161 rows of female drivers.</p> <pre><code>7 7 Katalin Coverly Female Driver 26 26 Jenilee Soeiro Female Driver 34 34 Rachel Tourner Female Driver 46 46 Joanne McCallister Female Driver 47 47 Maure Wingrove Female Driver 63 63 Bettina Mattecot Female Driver 74 74 Nelle MacRierie Female Driver 77 77 Elsinore Milius Female Driver 80 80 Emalia Hellewell Female Driver 82 82 Kerianne Pirkis Female Driver 95 95 Teena Pesak Female Driver 99 99 Harriot Seyffert Female Driver </code></pre> <p>I need a way to assign every 2 female drivers from this query to a team (example row 1 and row 2 are in team A row 3 and row 4 Team B etc)</p> <pre><code>7 7 Katalin Coverly Female Driver Team A 26 26 Jenilee Soeiro Female Driver Team A 34 34 Rachel Tourner Female Driver Team B 46 46 Joanne McCallister Female Driver Team B 47 47 Maure Wingrove Female Driver Team C 63 63 Bettina Mattecot Female Driver Team C 74 74 Nelle MacRierie Female Driver Team D 77 77 Elsinore Milius Female Driver Team D 80 80 Emalia Hellewell Female Driver Team E 82 82 Kerianne Pirkis Female Driver Team E 95 95 Teena Pesak Female Driver Team F 99 99 Harriot Seyffert Female Driver Team F... </code></pre> <p>any info or advice will be much appreciated.</p>
3
1,067
Why isn't my custom animation working correctly?
<p>My custom @keyframes animation is not working the way it should. </p> <p>There is no gap between <code>Block 1</code> and <code>Block 2</code> when rotating but there is a small gap between <code>Block 2</code> and <code>Block 3</code>, <code>Block 3</code> and <code>Block 4</code>, and, <code>Block 4</code> and <code>Block 1</code>.</p> <p>I cant understand why there is a gap between the above listed block or why there is no block between Block 1 and Block 2. What should I do to remove the gaps, I want it to look like a box without the gaps.</p> <p>Any other advice on the code is also appreciated. Below is the code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.main { width: 250px; height: 100px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .main&gt;div { width: 250px; height: 100px; position: absolute; text-align: center; line-height: 100px; color: #fff; font-weight: bold; font-family: monospace; font-size: 2em; transition: 1s; cursor: pointer; } .child1 { background: red; transform-origin: bottom; animation: animate1 8s infinite; } .child2 { background: blue; transform-origin: top; animation: animate2 8s infinite; } .child3 { background: yellow; transform-origin: bottom; animation: animate3 8s infinite; } .child4 { background: green; transform-origin: top; animation: animate4 8s infinite; } /*.main:hover .child1{ transform: translateY(-100%) rotateX(90deg); } .main:hover .child2{ transform: translateY(0%) rotateX(0deg); }*/ @keyframes animate1 { 0% { transform: translateY(0%) rotateX(0deg); } 25% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } 50% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } 75% { transform-origin: top; transform: translateY(100%) rotateX(90deg); } 100% { transform-origin: top; transform: translateY(0%) rotateX(0deg); } } @keyframes animate2 { 0% { transform: translateY(100%) rotateX(90deg); } 25% { transform-origin: top; transform: translateY(0%) rotateX(0deg); } 50% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } 75% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } 100% { transform-origin: top; transform: translateY(100%) rotateX(90deg); } } @keyframes animate3 { 0% { transform: translateY(-100%) rotateX(90deg); } 25% { transform-origin: top; transform: translateY(100%) rotateX(90deg); } 50% { transform-origin: top; transform: translateY(0%) rotateX(0deg); } 75% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } 100% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } } @keyframes animate4 { 0% { transform: translateY(-100%) rotateX(90deg); } 25% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } 50% { transform-origin: top; transform: translateY(100%) rotateX(90deg); } 75% { transform-origin: top; transform: translateY(0%) rotateX(0deg); } 100% { transform-origin: bottom; transform: translateY(-100%) rotateX(90deg); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="main"&gt; &lt;div class="child1"&gt;Block 1&lt;/div&gt; &lt;div class="child2"&gt;Block 2!&lt;/div&gt; &lt;div class="child3"&gt;Block 3&lt;/div&gt; &lt;div class="child4"&gt;Block 4&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
1,455
iTextSharp asp:DataGrid does not show up in PDF
<p>Converting a generated html page to pdf using iTextSharp, I cannot get the table created from the asp:DataGrid to show up in the PDF. The page's HTML output for the datagrid looks like this:</p> <pre><code>&lt;p&gt;Purchases:&lt;/p&gt; &lt;table rules="all" id="dg_Purchase" style="font-size: smaller; border-collapse: collapse;" border="1" cellspacing="0"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td&gt;Lot #&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;Title&lt;/td&gt; &lt;td align="right"&gt;Price&lt;/td&gt; &lt;td align="right"&gt;Buyer's Premium&lt;/td&gt; &lt;td align="right"&gt;Tax&lt;/td&gt; &lt;td align="right"&gt;Sub Total&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;118&lt;/td&gt; &lt;td&gt;&lt;input id="dg_Purchase_ctl02_CheckBox1" name="dg_Purchase$ctl02$CheckBox1" type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;Yih-Wen Kuo (1959, Taiwan)&lt;/td&gt; &lt;td align="right"&gt;$1,900.00&lt;/td&gt; &lt;td align="right"&gt;$332.50&lt;/td&gt; &lt;td align="right"&gt;$0.00&lt;/td&gt; &lt;td align="right"&gt;$2,232.50&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;119&lt;/td&gt; &lt;td&gt;&lt;input id="dg_Purchase_ctl03_CheckBox1" name="dg_Purchase$ctl03$CheckBox1" type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;Yih-Wen Kuo (1959, Taiwan)&lt;/td&gt; &lt;td align="right"&gt;$1,800.00&lt;/td&gt; &lt;td align="right"&gt;$315.00&lt;/td&gt; &lt;td align="right"&gt;$0.00&lt;/td&gt; &lt;td align="right"&gt;$2,115.00&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;Payments:&lt;/p&gt; &lt;table rules="all" id="dg_Payment" style="font-size: smaller; border-collapse: collapse;" border="1" cellspacing="0"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td style="width: 120px;"&gt;Payment Method&lt;/td&gt; &lt;td&gt;Date&lt;/td&gt; &lt;td align="right"&gt;Amount&amp;nbsp;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;Total&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td align="right"&gt;$0.00&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; </code></pre> <p>When the HTML page is viewed, the table looks exactly how it should. But when I generate the PDF, the table (or rather, everything within the table) is not shown. Only the border is visible, pretty much being just a 2 px straight line for each table.</p> <p>So in my normal script, after the entire page has loaded, the very last thing I do is:</p> <pre><code> StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); Render(writer); </code></pre> <p>The functions for iTextSharp are below:</p> <pre><code>protected override void Render(HtmlTextWriter writer) { MemoryStream mem = new MemoryStream(); StreamWriter twr = new StreamWriter(mem); HtmlTextWriter myWriter = new HtmlTextWriter(twr); base.Render(myWriter); myWriter.Flush(); myWriter.Dispose(); StreamReader strmRdr = new StreamReader(mem); strmRdr.BaseStream.Position = 0; string pageContent = strmRdr.ReadToEnd(); strmRdr.Dispose(); mem.Dispose(); writer.Write(pageContent); CreatePDFDocument(pageContent); } public void CreatePDFDocument(string strHtml) { string strFileName = HttpContext.Current.Server.MapPath("test.pdf"); // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create)); StringReader se = new StringReader(strHtml); HTMLWorker obj = new HTMLWorker(document); document.Open(); obj.Parse(se); document.Close(); ShowPdf(strFileName); } public void ShowPdf(string strFileName) { Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName); Response.ContentType = "application/pdf"; Response.WriteFile(strFileName); Response.Flush(); Response.Clear(); } </code></pre> <p>Again, everything on the page that is set programatically does show up in the PDF EXCEPT for the datagrid. Going off the borders, it appears that it is not a <code>width</code> issue. It just appears to be empty, is all. Any help would be greatly appreciated.</p>
3
1,969
mp.isPlaying() is throwing Fatal NullPointerException
<p>I have an application that plays sounds on button press.</p> <p>I'm trying to force the MediaPlayer to mute on incoming call and to continue at normal volume afterwards (in idle mode).</p> <p>I've wrote the below code to do exactly this, although it's crashing under NullPointerException on the following line.</p> <pre><code>if (mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_RINGING) { </code></pre> <p>Because of</p> <pre><code>mp.isPlaying() </code></pre> <p>Can anyone identify why this is happening? Later on in my code I reference mp to play sounds.</p> <pre><code> // Release any resources from previous MediaPlayer if (mp != null) { mp.release(); } // Create a new MediaPlayer to play this sound mp = MediaPlayer.create(this, resId); mp.setLooping(true); mp.start(); </code></pre> <p><strong>This is my on call mute and on idle resume code.</strong></p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { if (mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_RINGING) { mp.setVolume(0,0); } else if(mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_IDLE) { mp.setVolume(1,1); } else if(mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_OFFHOOK) { mp.setVolume(0,0); } super.onCallStateChanged(state, incomingNumber); } }; TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if(mgr != null) { mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } </code></pre> <p>I cannot understand why mp is Null if it's called later on in the application. If it's not playing will that return null? If so how would I get around this.</p> <p><strong>This is my whole activity as requested.</strong></p> <pre><code>import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity implements OnClickListener{ private MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { if (mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_RINGING) { mp.setVolume(0,0); } else if(mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_IDLE) { mp.setVolume(1,1); } else if(mp.isPlaying() &amp;&amp; state == TelephonyManager.CALL_STATE_OFFHOOK) { mp.setVolume(0,0); } super.onCallStateChanged(state, incomingNumber); } }; TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if(mgr != null) { mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } setVolumeControlStream(AudioManager.STREAM_MUSIC); Button button1=(Button)findViewById(R.id.button_1); Button button2=(Button)findViewById(R.id.button_2); Button button3=(Button)findViewById(R.id.button_3); Button button4=(Button)findViewById(R.id.button_4); Button button5=(Button)findViewById(R.id.button_5); Button button6=(Button)findViewById(R.id.button_6); Button button7=(Button)findViewById(R.id.button_7); Button button8=(Button)findViewById(R.id.button_8); final ImageView button_stop=(ImageView)findViewById(R.id.button_stop); ImageView button_rate=(ImageView)findViewById(R.id.button_rate); ImageView button_exit=(ImageView)findViewById(R.id.button_exit); button1.setOnClickListener(this); button2.setOnClickListener(this); button3.setOnClickListener(this); button4.setOnClickListener(this); button5.setOnClickListener(this); button6.setOnClickListener(this); button7.setOnClickListener(this); button8.setOnClickListener(this); button_stop.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(null!=mp){ mp.release(); button_stop.setImageResource(R.drawable.ic_action_volume_muted); } }}); button_exit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(0); finish(); }}); button_rate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String str ="https://play.google.com/store/apps/details?id=example"; startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str))); } ;{ }}); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("example") .setContentText("example."); // Creates an explicit intent for an Activity in your app final Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.setAction(Intent.ACTION_MAIN); notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); mBuilder.setOngoing(true); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. // Adds the back stack for the Intent (but not the Intent itself) PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int mId = 0; // mId allows you to update the notification later on. mNotificationManager.notify(mId, mBuilder.build()); } public void onClick(View v) { int resId; switch (v.getId()) { case R.id.button_1: resId = R.raw.birdsong; break; case R.id.button_2: resId = R.raw.electrifying_thunderstorms; break; case R.id.button_3: resId = R.raw.fan; break; case R.id.button_4: resId = R.raw.jungle_river; break; case R.id.button_5: resId = R.raw.pig_frogs; break; case R.id.button_6: resId = R.raw.predawn; break; case R.id.button_7: resId = R.raw.shower; break; case R.id.button_8: resId = R.raw.twilight; break; default: resId = R.raw.birdsong; break; } // Release any resources from previous MediaPlayer if (mp != null) { mp.release(); } // Create a new MediaPlayer to play this sound mp = MediaPlayer.create(this, resId); mp.setLooping(true); mp.start(); ImageView button_stop=(ImageView)findViewById(R.id.button_stop); button_stop.setImageResource(R.drawable.ic_action_volume_on); }{ } @Override protected void onDestroy() { if(null!=mp){ mp.release(); } super.onDestroy(); } } </code></pre> <p><strong>LOGCAT</strong></p> <pre><code>02-27 12:55:12.306: W/dalvikvm(887): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 02-27 12:55:12.326: E/AndroidRuntime(887): FATAL EXCEPTION: main 02-27 12:55:12.326: E/AndroidRuntime(887): java.lang.NullPointerException 02-27 12:55:12.326: E/AndroidRuntime(887): at me.soundasleep.app.MainActivity$1.onCallStateChanged(MainActivity.java:36) 02-27 12:55:12.326: E/AndroidRuntime(887): at android.telephony.PhoneStateListener$2.handleMessage(PhoneStateListener.java:369) 02-27 12:55:12.326: E/AndroidRuntime(887): at android.os.Handler.dispatchMessage(Handler.java:99) 02-27 12:55:12.326: E/AndroidRuntime(887): at android.os.Looper.loop(Looper.java:137) 02-27 12:55:12.326: E/AndroidRuntime(887): at android.app.ActivityThread.main(ActivityThread.java:5041) 02-27 12:55:12.326: E/AndroidRuntime(887): at java.lang.reflect.Method.invokeNative(Native Method) 02-27 12:55:12.326: E/AndroidRuntime(887): at java.lang.reflect.Method.invoke(Method.java:511) 02-27 12:55:12.326: E/AndroidRuntime(887): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 02-27 12:55:12.326: E/AndroidRuntime(887): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 02-27 12:55:12.326: E/AndroidRuntime(887): at dalvik.system.NativeStart.main(Native Method) 02-27 12:55:12.358: W/ActivityManager(292): Force finishing activity me.soundasleep.app/.MainActivity 02-27 12:55:12.366: W/WindowManager(292): Failure taking screenshot for (328x583) to layer 21010 02-27 12:55:12.656: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property 02-27 12:55:12.886: W/ActivityManager(292): Activity pause timeout for ActivityRecord{4132e3e0 u0 me.soundasleep.app/.MainActivity} 02-27 12:55:13.149: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property 02-27 12:55:16.186: I/Process(887): Sending signal. PID: 887 SIG: 9 02-27 12:55:16.206: I/ActivityManager(292): Process EXAMPLE (pid 887) has died. </code></pre>
3
4,552
Gradle: Using includeFlat to let project depend on local project
<p>I've got the following setup, with workspace being a normal directory containing my programs and Lib/App being Gradle projects created with the <code>gradle init</code> wizard.</p> <pre><code>\-- workspace +-- Lib +-- settings.gradle \-- lib +-- src\main\java\com\msgprograms\lib \-- Library.java \-- build.gradle \-- App +-- settings.gradle \-- app +-- src\main\java\com\msgprograms\app \-- App.java \-- build.gradle </code></pre> <p>I'm now trying to get <code>App</code> to use <code>Lib</code> as a library, but after about two hours of research I still can't get it to do so. As I plan to use <code>Lib</code> in a number of other projects in the future, I don't want to make it a part of <code>App</code> in any form. It wouldn't make sense to do that for me and it makes it easier to find the library in my workspace this way. I've tried the solutions detailed <a href="https://stackoverflow.com/questions/36479097/gradle-local-project-dependency">here</a>, as they seemed the most promising, but to no avail.</p> <p>Here are the build and settings files.</p> <pre><code>////////////////////// // App\app\build.gradle plugins { id 'application' } repositories { mavenCentral() } dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2' implementation 'com.google.guava:guava:31.0.1-jre' } application { mainClass = 'com.msgprograms.app.App' } tasks.named('test') { useJUnitPlatform() } ////////////////////// // App\settings.gradle rootProject.name = 'Appl' include('app') </code></pre> <pre><code>////////////////////// // Lib\lib\build.gradle plugins { id 'java-library' } repositories { mavenCentral() } dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2' api 'org.apache.commons:commons-math3:3.6.1' implementation 'com.google.guava:guava:31.0.1-jre' } tasks.named('test') { useJUnitPlatform() } ////////////////////// // Lib\settings.gradle rootProject.name = 'Libr' include('lib') </code></pre> <p>...and here are the sources:</p> <pre><code>// App\app\src\main\java\com\msgprograms\app\App.java package com.msgprograms.app; public class App { public String getGreeting() { return &quot;Hello World!&quot;; } public static void main(String[] args) { System.out.println(new App().getGreeting()); System.out.println(Library.someLibraryFunction()); } } </code></pre> <pre><code>// Lib\lib\src\main\java\com\msgprograms\lib\Library.java package com.msgprograms.lib; public class Library { public boolean someLibraryMethod() { return true; } } </code></pre> <p>While adding <code>includeFlat 'Libr'</code> to<code>App\settings.gradle</code> seems like the thing to use, I cannot for the life of me figure out how to <code>import com.msgprograms.lib.Library</code> successfully. The relevant answer doesn't go into enough detail to be of use, the linked docs are not helping and the other answers to the post linked above aren't helpful either.</p> <p>How do I let gradle projects depend on another local library-type project?</p>
3
1,206
Getting errors when trying to compile program using boost and ncurses libraries
<p>I have just started to write a server and client for an assignment but can't get my client code to compile. The server compiles just fine using just the boost library but in my client code I am using boost and ncurses. </p> <p>I am using <code>g++ battleship_client.cc -lboost_system -lncurses</code> when trying to compile.</p> <p>I have googled like crazy but I haven't found a solution. I should also note that I am on a mac and that I am using vscode. I have changed my includePath to look like this:</p> <pre><code>"includePath": [ "${workspaceFolder}/**", "/usr/local/Cellar/boost/1.68.0_1/", "/usr/local/Cellar/ncurses/6.1/" ], </code></pre> <p>battleship_client.cc:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;ncurses.h&gt; #include &lt;boost/asio.hpp&gt; using namespace std; using boost::asio::ip::tcp; void draw_top_matrix(vector&lt;vector&lt;int&gt; &gt; &amp;board, int cur_row, int cur_col) { for (int j=0;j&lt;4;j++) { move(0,2*j); printw("+-"); } move(0,2*4); printw("+"); for (int i=0;i&lt;4;i++) { for (int j=0;j&lt;4;j++) { move(2*i+1,2*j); printw("|"); move(2*i+1,2*j+1); if (board[i][j] == 0) { printw(" "); } else { printw("X"); } } move(2*i+1,2*4); printw("|"); for (int j=0;j&lt;4;j++) { move(2*i+2,2*j); printw("+-"); } move(2*i+2,2*4); printw("+"); } move(2*cur_row+1,2*cur_col+1); } void init(vector&lt;vector&lt;int&gt; &gt; &amp;board) { int rows; int cols; int cur_row = 0; int cur_col = 0; for(int i = 0; i &lt; 4; i++) { vector&lt;int&gt; temp; for(int j = 0; j &lt; 4; j++) { temp.push_back(0); } board.push_back(temp); } initscr(); clear(); getmaxyx(stdscr, rows, cols); cbreak(); keypad(stdscr, TRUE); refresh(); draw_top_matrix(board, 0, 0); endwin(); } int main(int argc, char *argv[]) { int port = atoi(argv[3]); vector&lt;vector&lt;int&gt; &gt; board; boost::asio::io_service my_service; tcp::resolver resolver(my_service); tcp::socket socket(my_service); socket.connect(tcp::endpoint(boost::asio::ip::address::from_string(argv[2]), port)); init(board); return 0; } </code></pre> <p>The errors I am getting:</p> <pre><code> In file included from battleship_client.cc:4:0: /usr/local/include/boost/asio/basic_socket_streambuf.hpp:595:7: error: 'stdscr' is not a type int timeout() const ^ /usr/local/include/boost/asio/basic_socket_streambuf.hpp:595:7: error: expected identifier before ')' token int timeout() const ^ /usr/local/include/boost/asio/basic_socket_streambuf.hpp: In member function 'std::basic_streambuf&lt;char&gt;::int_type boost::asio::basic_socket_streambuf&lt;Protocol, Clock, WaitTraits&gt;::underflow()': /usr/local/include/boost/asio/basic_socket_streambuf.hpp:479:42: error: expected primary-expression before ')' token socket().native_handle(), 0, timeout(), ec_) &lt; 0) ^ /usr/local/include/boost/asio/basic_socket_streambuf.hpp: In member function 'std::basic_streambuf&lt;char&gt;::int_type boost::asio::basic_socket_streambuf&lt;Protocol, Clock, WaitTraits&gt;::overflow(std::basic_streambuf&lt;char&gt;::int_type)': /usr/local/include/boost/asio/basic_socket_streambuf.hpp:538:42: error: expected primary-expression before ')' token socket().native_handle(), 0, timeout(), ec_) &lt; 0) ^ /usr/local/include/boost/asio/basic_socket_streambuf.hpp: In member function 'void boost::asio::basic_socket_streambuf&lt;Protocol, Clock, WaitTraits&gt;::connect_to_endpoints(EndpointIterator, EndpointIterator)': /usr/local/include/boost/asio/basic_socket_streambuf.hpp:656:39: error: expected primary-expression before ')' token socket().native_handle(), timeout(), ec_) &lt; 0) </code></pre>
3
1,948
Java - When updating JLabel's icon, the new icon is put behind the old icon
<p>What I am trying to do is create a gui that allows you to select an image, display the image, and then perfom actions on it for a school project. This is what happens on startup. <a href="https://i.stack.imgur.com/vuBNX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vuBNX.png" alt="enter image description here"></a> Perfect! However, when I update the icon, it puts the new icon behind it: <a href="https://i.stack.imgur.com/23tC6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/23tC6.png" alt="enter image description here"></a></p> <p>Here is the code I'm using on my Jlabel: </p> <pre><code>ImageIcon imageIcon = new ImageIcon(); try { imageIcon = new ImageIcon(ImageIO.read(new File("/Users/ryanauger/Repos/JavaGUI/GUI/Images/cameraIcon.png"))); } catch (IOException e2) { // TODO Auto-generated catch block imageIcon = new ImageIcon(); e2.printStackTrace(); } JLabel lblNewLabel = new MyJLabel(imageIcon); lblNewLabel.setBounds(0, 6, 600, 600); frame.getContentPane().add(lblNewLabel); JButton btnNewButton = new JButton("Pick Image File"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser jfc; jfc = new JFileChooser(); File f = new File(System.getProperty("user.dir")); jfc.setCurrentDirectory(f); jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); jfc.showOpenDialog(btnNewButton); File selFile = jfc.getSelectedFile(); try { lblNewLabel.setIcon(new ImageIcon(ImageIO.read(new File(selFile.getAbsolutePath())))); } catch (IOException e1) { // TODO Auto-generated catch block System.out.println(selFile.getAbsolutePath()); e1.printStackTrace(); } } }); </code></pre> <p>I am brand new to java, so any help is appreciated. Thanks!</p> <p>EDIT: Here is the code for MyJLabel: </p> <pre><code>class MyJLabel extends JLabel { ImageIcon imageIcon; public MyJLabel(ImageIcon icon) { super(); this.imageIcon = icon; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(imageIcon.getImage(),0,0,getWidth(),getHeight(),this); } } </code></pre>
3
1,148
Disable Scroll in Relation to Overlay
<p>Goal:<br> When you click on the picture a overlay should display and the scroll should not affect the user interface. </p> <p>Problem:<br> When the page is long and you disable the scroll the content of the page in relation to overlay will be moved towards to the right side. When you have many picture, it will not be very user-friendly.</p> <p>I have tried the solution from this <a href="https://stackoverflow.com/questions/8701754/just-disable-scroll-not-hide-it">page</a> and this <a href="https://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily?rq=1">page</a> but they doesn't work in relation to this source code below.</p> <p>I also have tried this <a href="https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling">page</a> but it did't work at all. This link as a proposal. <code>jsbin.com/poyejulijo/edit?html,output</code></p> <p>I have tried different solution but I failed.</p> <p>Info:<br> *Using jQuery and Bootstrap v.3<br> *The overlay with scroll should be working in relation to the latest version of IE, FF and Chrome. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function openNav(a) { document.getElementById("myNav").style.width = "100%"; var p = document.getElementById("p1"); p.src = a.getElementsByTagName('img')[0].src; var d = document.getElementById("div12"); d.innerHTML = d.innerHTML + 'sdfsdf'; document.body.classList.add("noScroll"); } function closeNav() { document.getElementById("myNav").style.width = "0%"; document.body.classList.remove("noScroll"); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay { height: 100%; width: 0; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0,0,0); background-color: rgba(0,0,0, 0.7); overflow-x: hidden; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; margin-top: 30px; } .overlay a { padding: 8px; text-decoration: none; font-size: 36px; color: #818181; display: block; } .overlay a:hover, .overlay a:focus { color: #f1f1f1; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; } body.noScroll { /* ...or body.dialogShowing */ overflow: hidden; } @media screen and (max-height: 450px) { .overlay a {font-size: 20px} .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.css" rel="stylesheet"/&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="myNav" class="overlay"&gt; &lt;a href="javascript:void(0)" class="closebtn" onclick="closeNav()"&gt;&amp;times;&lt;/a&gt; &lt;div class="overlay-content"&gt; &lt;img id="p1" src="" /&gt; &lt;div id="div12"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;nav class="navbar navbar-fixed-top navbar-inverse"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;Project name&lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="collapse navbar-collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#about"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- /.nav-collapse --&gt; &lt;/div&gt;&lt;!-- /.container --&gt; &lt;/nav&gt;&lt;!-- /.navbar --&gt; &lt;div class="container"&gt; &lt;div class="row row-offcanvas row-offcanvas-right"&gt; &lt;div class="col-xs-12 col-sm-9"&gt; &lt;p class="pull-right visible-xs"&gt; &lt;button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas"&gt;Toggle nav&lt;/button&gt; &lt;/p&gt; &lt;div class="jumbotron"&gt; &lt;h1&gt;Hello, world!&lt;/h1&gt; &lt;p&gt;This is an example to show the potential of an offcanvas layout pattern in Bootstrap. Try some responsive-range viewport sizes to see it in action.&lt;/p&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6 col-lg-4"&gt; &lt;h2&gt;Heading&lt;/h2&gt; &lt;p&gt; &lt;div style="font-size:30px;cursor:pointer" onclick="openNav(this)"&gt; &lt;img src="http://www.partycity.com/images/products/en_us/gateways/candy-2015/candy-by-type/candy-by-type-lollipops.jpg" /&gt; &lt;/div&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;img onclick="openNav(this)" src="http://www.partycity.com/images/products/en_us/gateways/candy-2015/candy-by-type/candy-by-type-lollipops.jpg" /&gt; &lt;/p&gt; &lt;p&gt;&lt;a class="btn btn-default" href="#" role="button"&gt;View details &amp;raquo;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt;&lt;!--/.col-xs-6.col-lg-4--&gt; &lt;/div&gt;&lt;!--/row--&gt; &lt;/div&gt;&lt;!--/.col-xs-12.col-sm-9--&gt; &lt;div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar"&gt; &lt;div class="list-group"&gt; &lt;a href="#" class="list-group-item active"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;a href="#" class="list-group-item"&gt;Link&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;&lt;!--/.sidebar-offcanvas--&gt; &lt;/div&gt;&lt;!--/row--&gt; &lt;hr&gt; &lt;footer&gt; &lt;p&gt;&amp;copy; 2016 Company, Inc.&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt;&lt;!--/.container--&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;</code></pre> </div> </div> </p>
3
3,513
CGAL::Surface_mesh_parameterization: write the vertices to off in the original order
<p>I am trying to modify <code>CGAL-4.13/examples/Surface_mesh_parameterization/lscm.cpp</code> so that the order of the vertices in the resulting off file is the same as in the input file.</p> <h2> Update: Example </h2> <p>Take a file <code>input.off</code> with the following simple content:</p> <pre><code>OFF 4 2 0 -0.9310345 0.4333333 0 -1 0.4333333 0 -0.9310345 0.5 0 -1 0.5 0 3 1 0 2 3 2 3 1 </code></pre> <p>When I call the standard <code>lscm</code> from CGAL with</p> <pre><code>/path/to/CGAL-4.13-build/examples/Surface_mesh_parameterization/lscm input.off </code></pre> <p>I obtain <code>coords.off</code> containing</p> <pre><code>OFF 4 2 0 -1 0.5 0 -0.931034 0.5 0 -0.931034 0.433333 0 -1 0.433333 0 3 3 2 1 3 1 0 3 </code></pre> <p>and <code>uvmap.off</code> with</p> <pre><code>OFF 4 2 0 -0.0166567 0.982769 0 1 1 0 1.01666 0.0172311 0 0 0 0 3 3 2 1 3 1 0 3 </code></pre> <p>The files <code>coords.off</code> and <code>uvmap.off</code> contain the vertices and their parameter pairs in the same order (which is <em>different</em> from that in <code>input.off</code>). Instead, I would like the parameters in <code>uvmap.off</code> to be in the order corresponding to <code>input.off</code>. In particular, I want <code>uvmap.off</code> to look like this:</p> <pre><code>OFF 4 2 0 1.01666 0.0172311 0 0 0 0 1 1 0 -0.0166567 0.982769 0 3 1 0 2 3 2 3 1 </code></pre> <p>Basically, this renders <code>coords.off</code> redundant, as I can use <code>input.off</code> in its role.</p> <h2> Effort at a solution </h2> <p>From what I understand, this might be possible to achieve by calling <code>output_uvmap_to_off(...)</code> with 6 parameters instead of 4 (both versions can be found in <code>CGAL-4.13/include/CGAL/Surface_mesh_parameterization/IO/File_off.h</code>). As one of these parameters is a <code>VertexIndexMap</code>, I should probably also use </p> <pre><code>CGAL::Surface_mesh_parameterization::LSCM_parameterizer_3&lt; TriangleMesh_, BorderParameterizer_, SolverTraits_ &gt;::parameterize(...) </code></pre> <p>instead of</p> <pre><code>CGAL::Surface_mesh_parameterization::parameterize(...) </code></pre> <p>used in the example.</p> <p>Here is a minimal (not really working) example. It is derived from <code>lscm.cpp</code> but I threw away a lot of things to remain concise.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;CGAL/Simple_cartesian.h&gt; #include &lt;CGAL/Surface_mesh.h&gt; #include &lt;CGAL/boost/graph/Seam_mesh.h&gt; #include &lt;CGAL/Surface_mesh_parameterization/IO/File_off.h&gt; #include &lt;CGAL/Surface_mesh_parameterization/parameterize.h&gt; #include &lt;CGAL/Surface_mesh_parameterization/Two_vertices_parameterizer_3.h&gt; #include &lt;CGAL/Surface_mesh_parameterization/LSCM_parameterizer_3.h&gt; #include &lt;CGAL/Polygon_mesh_processing/measure.h&gt; #include &lt;boost/foreach.hpp&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; typedef CGAL::Simple_cartesian&lt;double&gt; Kernel; typedef Kernel::Point_2 Point_2; typedef Kernel::Point_3 Point_3; typedef CGAL::Surface_mesh&lt;Kernel::Point_3&gt; SurfaceMesh; typedef boost::graph_traits&lt;SurfaceMesh&gt;::edge_descriptor SM_edge_descriptor; typedef boost::graph_traits&lt;SurfaceMesh&gt;::halfedge_descriptor SM_halfedge_descriptor; typedef boost::graph_traits&lt;SurfaceMesh&gt;::vertex_descriptor SM_vertex_descriptor; typedef SurfaceMesh::Property_map&lt;SM_halfedge_descriptor, Point_2&gt; UV_pmap; typedef SurfaceMesh::Property_map&lt;SM_edge_descriptor, bool&gt; Seam_edge_pmap; typedef SurfaceMesh::Property_map&lt;SM_vertex_descriptor, bool&gt; Seam_vertex_pmap; typedef CGAL::Seam_mesh&lt;SurfaceMesh, Seam_edge_pmap, Seam_vertex_pmap&gt; Mesh; typedef boost::graph_traits&lt;Mesh&gt;::vertex_descriptor vertex_descriptor; typedef boost::graph_traits&lt;Mesh&gt;::halfedge_descriptor halfedge_descriptor; typedef boost::graph_traits&lt;Mesh&gt;::face_descriptor face_descriptor; namespace SMP = CGAL::Surface_mesh_parameterization; int main(int argc, char** argv) { std::ifstream in_mesh((argc&gt;1) ? argv[1] : "data/lion.off"); if(!in_mesh){ std::cerr &lt;&lt; "Error: problem loading the input data" &lt;&lt; std::endl; return EXIT_FAILURE; } SurfaceMesh sm; in_mesh &gt;&gt; sm; Seam_edge_pmap seam_edge_pm = sm.add_property_map&lt;SM_edge_descriptor, bool&gt;("e:on_seam", false).first; Seam_vertex_pmap seam_vertex_pm = sm.add_property_map&lt;SM_vertex_descriptor, bool&gt;("v:on_seam", false).first; Mesh mesh(sm, seam_edge_pm, seam_vertex_pm); UV_pmap uv_pm = sm.add_property_map&lt;SM_halfedge_descriptor, Point_2&gt;("h:uv").first; halfedge_descriptor bhd = CGAL::Polygon_mesh_processing::longest_border(mesh, CGAL::Polygon_mesh_processing::parameters::all_default()).first; typedef SMP::Two_vertices_parameterizer_3&lt;Mesh&gt; Border_parameterizer; typedef SMP::LSCM_parameterizer_3&lt;Mesh, Border_parameterizer&gt; Parameterizer; // Here's where the big changes start. SurfaceMesh::Property_map&lt;SM_halfedge_descriptor, int&gt; vimap = sm.add_property_map&lt;SM_halfedge_descriptor, int&gt;("h:vi").first; SurfaceMesh::Property_map&lt;SM_halfedge_descriptor, bool&gt; vpmap = sm.add_property_map&lt;SM_halfedge_descriptor, bool&gt;("h:vp").first; Parameterizer parameterizer; parameterizer.parameterize(mesh, bhd, uv_pm, vimap, vpmap); const char* uvmap_file = "uvmap.off"; std::ofstream uvmap_out(uvmap_file); SMP::IO::output_uvmap_to_off(mesh,sm.vertices(),sm.faces(),uv_pm,vimap,uvmap_out); return EXIT_SUCCESS; } </code></pre> <p>This does not compile, complaining about a required conversion on line 131 in File_off.h.</p> <h2> Actual questions </h2> <ul> <li>Is <code>vimap</code> initialized correctly?</li> <li>Is this the reasonable direction towards my goal of writing the vertices in the same order?</li> <li>If yes, how do I pass the correct arguments to <code>output_uvmap_to_off(...)</code>? For instance, it asks for a <code>VertexContainer</code> and I provide a <code>Vertex_range</code> (hence the compilation error, I suppose). Shall I just collect the vertices as suggested <a href="https://stackoverflow.com/questions/48809669/how-to-get-the-vertices-and-the-faces-of-a-polygon-mesh-with-cgal">here</a> or <a href="https://stackoverflow.com/questions/39521720/cgal-read-vertices-and-triangles-from-mesh">here</a> or is there a more elegant way?</li> <li>If no, what is the right course of action?</li> </ul>
3
2,669
Slow sql select with index on postgres
<p>I have a production database which is replicated to a another host using londist. The table looks like</p> <pre><code># \d+ usermessage Table "public.usermessage" Column | Type | Modifiers | Description -------------------+-------------------+-----------+------------- id | bigint | not null | subject | character varying | | message | character varying | | read | boolean | | timestamp | bigint | | owner | bigint | | sender | bigint | | recipient | bigint | | dao_created | bigint | | dao_updated | bigint | | type | integer | | replymessageid | character varying | | originalmessageid | character varying | | replied | boolean | | mheader | boolean | | mbody | boolean | | Indexes: "usermessage_pkey" PRIMARY KEY, btree (id) "usermessage_owner_key" btree (owner) "usermessage_recipient_key" btree (recipient) "usermessage_timestamp_key" btree ("timestamp") "usermessage_type_key" btree (type) Has OIDs: no </code></pre> <p>If executed on the replicated database, the select is fast as expected, if executed on the production host it's horrible slow. To make things more strange, not all timestamps are slow, some of them are fast on both hosts. The filesystem and the storage behind the production host is fine and not under heavy usage. Any ideas?</p> <pre><code>replication# explain analyse SELECT COUNT(id) FROM usermessage WHERE owner = 1234567 AND timestamp &gt; 1362077127010; QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------- Aggregate (cost=263.37..263.38 rows=1 width=8) (actual time=0.059..0.060 rows=1 loops=1) -&gt; Bitmap Heap Scan on usermessage (cost=259.35..263.36 rows=1 width=8) (actual time=0.055..0.055 rows=0 loops=1) Recheck Cond: ((owner = 1234567) AND ("timestamp" &gt; 1362077127010::bigint)) -&gt; BitmapAnd (cost=259.35..259.35 rows=1 width=0) (actual time=0.054..0.054 rows=0 loops=1) -&gt; Bitmap Index Scan on usermessage_owner_key (cost=0.00..19.27 rows=241 width=0) (actual time=0.032..0.032 rows=33 loops=1) Index Cond: (owner = 1234567) -&gt; Bitmap Index Scan on usermessage_timestamp_key (cost=0.00..239.82 rows=12048 width=0) (actual time=0.013..0.013 rows=0 loops=1) Index Cond: ("timestamp" &gt; 1362077127010::bigint) Total runtime: 0.103 ms (9 rows) production# explain analyse SELECT COUNT(id) FROM usermessage WHERE owner = 1234567 AND timestamp &gt; 1362077127010; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Aggregate (cost=267.39..267.40 rows=1 width=8) (actual time=47536.590..47536.590 rows=1 loops=1) -&gt; Bitmap Heap Scan on usermessage (cost=263.37..267.38 rows=1 width=8) (actual time=47532.520..47536.579 rows=3 loops=1) Recheck Cond: ((owner = 1234567) AND ("timestamp" &gt; 1362077127010::bigint)) -&gt; BitmapAnd (cost=263.37..263.37 rows=1 width=0) (actual time=47532.334..47532.334 rows=0 loops=1) -&gt; Bitmap Index Scan on usermessage_owner_key (cost=0.00..21.90 rows=168 width=0) (actual time=0.123..0.123 rows=46 loops=1) Index Cond: (owner = 1234567) -&gt; Bitmap Index Scan on usermessage_timestamp_key (cost=0.00..241.22 rows=12209 width=0) (actual time=47530.255..47530.255 rows=5255617 loops=1) Index Cond: ("timestamp" &gt; 1362077127010::bigint) Total runtime: 47536.668 ms (9 rows) </code></pre>
3
1,871
WPF View-ModelView Binding Need Help Please
<p>I have been playing around and looking around on how to Bind a modelview to a view, but i cant seem to work it out. I have a view called Search and I want to bind it to SearchModelView. View has one button and one textbox and looks:</p> <p></p> <pre><code>&lt;Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" &gt; &lt;ComboBox Height="23" HorizontalAlignment="Left" Margin="12,40,0,0" Name="comboBox1" VerticalAlignment="Top" Width="174" /&gt; &lt;Label Content="Client:" Height="28" HorizontalAlignment="Left" Margin="0,12,0,0" Name="label1" VerticalAlignment="Top" Width="71" /&gt; &lt;Label Content="Client Reference:" Height="28" HorizontalAlignment="Left" Margin="0,69,0,0" Name="label2" VerticalAlignment="Top" Width="117" /&gt; &lt;TextBox x:Name="clientRefTxt" Text="{Binding Path=ClientRef, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" Height="23" HorizontalAlignment="Left" Margin="12,103,0,0" VerticalAlignment="Top" Width="174" /&gt; &lt;Button Content="Search Debtors" Height="23" HorizontalAlignment="Left" Margin="12,140,0,0" Name="button1" VerticalAlignment="Top" Width="89" Command="{Binding Path=SearchCommand}"/&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>And I want it to bind to SearchViewModel:</p> <p>namespace Master.ViewModel {</p> <pre><code>public class SearchViewModel:WorkspaceViewModel { RelayCommand _searchCommand; readonly Search _search; #region Search Properties public string ClientRef { get { MessageBox.Show("GET CLIENTREF"); return _search.ClientRef; } set { MessageBox.Show("SET CLIENTREF"); if (value == _search.ClientRef) return; _search.ClientRef = value; base.OnPropertyChanged("ClientRef"); } } #endregion public ICommand SearchCommand { get { MessageBox.Show("SEARCHCOMMAND"); if (_searchCommand == null) { _searchCommand = new RelayCommand( param=&gt; this.Search(), param=&gt; this.CanSearch ); } return _searchCommand; } } public void Search() { MessageBox.Show("SEARCHING"); } bool CanSearch { get { return true; } } } </code></pre> <p>}</p> <p>I removed all the assemblies at the top but assume that they are all there. Also note that SearchViewModel is in a separate dll, not in the exe with the View. Any help would be great or at least a pointer in the write direction, I have already read the msdn article on MVVM and that didnt help...I kinda need a better rundown on binding those too pieces. Thanks in Advance. P.S. Some more details: SearchViewModel belongs to Master.ViewModel SearchView is part of GUI.View I have and idea how the binded objects work, im not to sure on how to bind the view to the viewmodel</p>
3
1,303
List sort implementation
<p>Have some problems with my list and sorting feature. I create class Variation and Variations. I trade Variations class as collection list of my Variation to separate it. Now when i have create collection i would like to sort by Variation property position, hovever i get error. Can you help me out? Below all necessary information.</p> <p>Variation class:</p> <pre><code>Public Class Variation Property ID As Integer Property Name As String Property Erstellungsdatum As Date Property Position As SByte Sub New() End Sub Sub New(id As Integer) _ID = id End Sub Sub New(id As Integer, name As String) _ID = id _Name = name End Sub Sub New(name As String, position As Integer) _Name = name _Position = position End Sub Sub New(id As Integer, name As String, position As SByte) _ID = id _Name = name _Position = position End Sub Sub New(id As Integer, name As String, erstellungsdatum As Date) _ID = id _Name = name _Erstellungsdatum = erstellungsdatum End Sub End Class </code></pre> <p>class Variations:</p> <pre><code>Public Class Variations Implements IDisposable Implements IComparer(Of Variation) Public MyVariationsCollection As List(Of Variation) Sub New() MyVariationsCollection = New List(Of Variation) End Sub Public Function AddToCollection(ByVal variation As Variation) As Boolean MyVariationsCollection.Add(variation) Return True End Function Public Sub RemoveFromCollection(index As Integer) If Not IsNothing(MyVariationsCollection.Item(index)) Then MyVariationsCollection.RemoveAt(index) End If End Sub Public Function Compare(x As Variation, y As Variation) As Integer Implements IComparer(Of Variation).Compare If x.Position &gt; y.Position Then Return 1 End If If x.Position &lt; y.Position Then Return -1 End If Return 0 End Function End Class </code></pre> <p>in the code i am doing:</p> <pre><code>Private variations As New Variations variations.AddToCollection(New BusinessLayer.Variation(Id, Name, StartPosition)) </code></pre> <p>now i would like to sort this list by e.g Position which i implemented in Variations and i would like it to be there and not in Variation class as i want trade Variations class as collection of Variation object to separate if you know what i mean.</p> <p>however if i do:</p> <pre><code>_variations.MyVariationsCollection.Sort() </code></pre> <p>then i get error:</p> <pre><code> --------------------------- myprog --------------------------- System.InvalidOperationException: You can not compare two elements in the array. ---&gt; System.ArgumentException: At least one object must implement IComparable element w System.Collections.Comparer.Compare(Object a, Object b) w System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) w System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit) w System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) --- Koniec śladu stosu wyjątków wewnętrznych --- w System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) w System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) w System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer) w Cenea.UserControl1..ctor(Variations variations, Artikel mainArtikel) w C:\Users\Robert\Desktop\Cenea\Cenea\UserControl1.vb:wiersz 26 w Cenea.FrmMain.btnVariationProcees_Click(Object sender, EventArgs e) w C:\Users\Robert\Desktop\Cenea\Cenea\FrmMain.vb:wiersz 450 w System.Windows.Forms.Control.OnClick(EventArgs e) w DevComponents.DotNetBar.ButtonX.OnClick(EventArgs e) w DevComponents.DotNetBar.ButtonX.OnMouseUp(MouseEventArgs e) w System.Windows.Forms.Control.WmMouseUp(Message&amp; m, MouseButtons button, Int32 clicks) w System.Windows.Forms.Control.WndProc(Message&amp; m) w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg) w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) w Cenea.ProgStart.main() w C:\Users\Robert\Desktop\Cenea\Cenea\ProgStart.vb:wiersz 14 --------------------------- OK --------------------------- </code></pre> <p><strong>Final solution:</strong></p> <pre><code>Public Class Variation Implements IComparable(Of Variation) ... Public Function CompareTo(pother As Variation) As Integer Implements IComparable(Of Variation).CompareTo Return String.Compare(Me.Position, pother.Position) End Function ... </code></pre> <p>Variations :</p> <pre><code>Imports BusinessLayer Public Class Variations Implements IDisposable Public collection As List(Of Variation) Sub New() collection = New List(Of Variation) End Sub Public Function AddToCollection(ByVal variation As Variation) As Boolean collection.Add(variation) Return True End Function Public Sub RemoveFromCollection(index As Integer) If Not IsNothing(collection.Item(index)) Then collection.RemoveAt(index) End If End Sub Public Sub SortByPosition() collection.Sort() End Sub #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: dispose managed state (managed objects). End If ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below. ' TODO: set large fields to null. End If Me.disposedValue = True End Sub ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class </code></pre>
3
2,552
PhpStorm print the script of php instead of html page
<p>I'm developping a project of a generator of CV in HTML/PHP/CSS/SQL on a local server. When I use the chrome option to run a php file on PHPStorm, it prints the code between the two php tags and not the html page. It started today, before that all worked perfecty well.</p> <pre><code> &lt;html lang=&quot;fr&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; rel=&quot;stylesheet&quot;&gt; &lt;title&gt;Page d'inscription&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;grid-container&quot;&gt; &lt;div class = &quot;carre_acceuil&quot;&gt; &lt;div class = &quot;titre_acceuil&quot;&gt; Inscription &lt;/div&gt; &lt;form method=&quot;post&quot; action=&quot;inscrire.php&quot;&gt; &lt;div class = &quot;formulaire_acceuil&quot;&gt; &lt;label&gt; &lt;input type = &quot;text&quot; name = &quot;prenom&quot; placeholder=&quot;Prenom&quot; required class=&quot;input_acceuil&quot;&gt;&lt;br&gt;&lt;br&gt; &lt;input type = &quot;text&quot; name = &quot;nom&quot; placeholder =&quot;Nom&quot; required class=&quot;input_acceuil&quot;&gt;&lt;br&gt;&lt;br&gt; &lt;input type = &quot;email&quot; name = &quot;email&quot; placeholder =&quot;Adresse email&quot; required class=&quot;input_acceuil&quot;&gt;&lt;br&gt;&lt;br&gt; &lt;input type = &quot;password&quot; name = &quot;password&quot; placeholder =&quot;Mot de passe&quot; required class=&quot;input_acceuil&quot;&gt;&lt;br&gt;&lt;br&gt; &lt;/label&gt; &lt;input type=&quot;submit&quot; value=&quot;S'inscrire&quot; class=&quot;bouton&quot;&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>And the file &quot;inscrire.php&quot; is here:</p> <pre><code> &lt;?php $nom = $_POST[&quot;nom&quot;]; $nom = ucfirst(strtolower($nom)); $prenom = $_POST[&quot;prenom&quot;]; $prenom = ucfirst(strtolower($prenom)); $email = $_POST[&quot;email&quot;]; $password = crypt($_POST[&quot;password&quot;]); //se connecter a la base de donee $bdd = new PDO(&quot;mysql:host=localhost;dbname=ifd1_gestion_cv;charset=utf8&quot;, &quot;root&quot;, &quot;&quot;); // Créer une requête INSERT INTO pour insérer un étudiant $req = $bdd-&gt;prepare(&quot;INSERT INTO comptes (nom, prenom, email, password) VALUES (?,?,?,?);&quot;); // Exécuter la requête $req-&gt;execute([ucfirst($nom), ucfirst($prenom), $email, $password]); header(&quot;Location: index.php&quot;); ?&gt; </code></pre>
3
1,417
jquery validate firing unhighlight function imediately after highlight
<p>despite my problem is similar <a href="https://stackoverflow.com/questions/22903707/jquery-validate-is-firing-both-highlight-and-unhighlight-in-chrome">with this</a></p> <p>the proposed solution did not work for me. Let me explain what happens. As the title suggests unhiglight is called right after highlight.</p> <p>and this happens only under one scenario only: <strong>using remote method of email</strong>. If the ajax call returns true(after hitting the submit button)(email does not exist) error class is added and immediately replaced by valid class in the fields that are not filled(required)...</p> <p>if I hit submit again the problem does not appear...if some fields are not filled error class is attached properly.</p> <p>What differentiates first from second submit(and if email is not changed) is the fact that ajax call for the email is not made.</p> <p>So if ajax call is made(for the email) and returns true the above problem appears. The code for the showerrors method found in the above Soverflow post does not help.</p> <p><strong>I must emphasize that if I remove the remote method for the email the problem is fixed</strong></p> <p>here is the code inside validate():</p> <pre><code> $('#bizuserform').validate({ showErrors: function (errorMap, errorList) { var errors = this.numberOfInvalids(); if (errors) { var message = errors == 1 ? '1 field is miissing!!!' : errors + ' fields are missing!!!'; $(&quot;#error_general span&quot;).empty().html(message); $(&quot;#error_general&quot;).show(); } else { $(&quot;#error_general&quot;).hide(); } this.defaultShowErrors(); }, highlight: function(element, errorClass, validClass) { if($(element).attr(&quot;id&quot;)=='staffclient_yes') { $('#staffclient_yes').parent().addClass(errorClass); } if($(element).attr(&quot;id&quot;)=='medical') { $('#medical').parent().addClass(errorClass); } $(element).addClass(errorClass).removeClass(validClass); }, unhighlight: function(element, errorClass, validClass) { if($(element).attr(&quot;id&quot;)=='staffclient_yes') { $('#staffclient_yes').parent().removeClass(errorClass); } if($(element).attr(&quot;id&quot;)=='medical') { $('#medical').parent().removeClass(errorClass); } $(element).removeClass(errorClass).addClass(validClass); }, onfocusout: false, submitHandler: function(form,event) { event.preventDefault(); //ajax request here...ommited for brevity }, rules:{ name: { required: function () { return $('#coname').is(':blank'); }, normalizer: function( value ) { return $.trim( value );} }, lastname: { required: function () { return $('#coname').is(':blank'); }, normalizer: function( value ) { return $.trim( value );} }, coname: { required: function () { return $('#name,#lastname').is(':blank'); }, normalizer: function( value ) { return $.trim( value );} }, buztype:{required:true }, med_spec:{ required: function(element) {return $('#medical').is(':checked');} }, password:{ required:true, password:true, normalizer: function( value ) { return $.trim( value );} }, address:{ required: true, normalizer: function( value ) { return $.trim( value );} }, city:{ required: true, normalizer: function( value ) { return $.trim( value );} }, municipality:{ required: true, normalizer: function( value ) { return $.trim( value );} }, email:{required: true, email: true, remote: { url: &quot;email_validity.php&quot;,//if I remove the remote method here problem is fixed type: &quot;post&quot; }, normalizer: function( value ) { return $.trim( value );} }, phone:{required:true, normalizer: function( value ) { return $.trim( value );}, digits: true, rangelength: [10, 14] }, staff_to_client:{ required: &quot;#staf_eng:visible&quot; } }, messages:{ buztype:'', staff_to_client:'', med_spec:'', coname:&quot;&quot;, name:'', lastname:'', password:{required:&quot;&quot; }, address:'', city:'', municipality:'', email:{required:&quot;&quot;, email:'not valid email', remote:'email allready exists.' }, phone:{required:&quot;&quot;, rangelength:'phonenumber messasge.', digits:'only digits here' }, staff_to_client:{ required: &quot;&quot; } } }); </code></pre>
3
2,219
Execute non-query question with dataset results
<p>I have a fun project that involves VB.net winform app. This applications uses datasets for the forms. Three tables will be effected Shift_Log (SL), Problem_Log (PL) and Service_Request (SR). If the user changes the log dates on the (SL) so that the (PL) no longer agrees with the error time. I need to remove the foreign key from the (PL) and (SR) tables. I have not tested this yet. I have a couple of questions before I do.</p> <ol> <li><p>What if there are no records to update in the second update (SR)sql command?</p> </li> <li><p>do I need to refresh the Dataset after this is executed.</p> <pre><code> Public Function UPD_PL_Check(ByVal Shift_Key As String, ByVal SL_Begin As DateTime, SL_End As DateTime) As Integer ' Get rows from Laser Status Info Dim query As String = &quot;SELECT Status_Key FROM [dbo].[Laser_Status_Info] &quot; &amp; &quot; WHERE [Shift_FKey] = &quot; &amp; Shift_Key &amp; &quot; AND [Err_time] NOT Between &quot; &amp; SL_Begin &amp; &quot; AND &quot; &amp; SL_End &amp; &quot;;&quot; Dim dt As DataTable = New DataTable() Using conn As SqlConnection = New SqlConnection(My.Settings.LaserMaintLogConnectionString) conn.Open() Try Dim da As SqlDataAdapter = New SqlDataAdapter(query, conn) da.Fill(dt) Catch ex As Exception MessageBox.Show(&quot;Error occured! : &quot; &amp; ex.Message) Finally conn.Close() End Try End Using Dim rowsAffected As Integer = dt?.Rows.Count If rowsAffected = 0 Then Return rowsAffected ' Update the Problem log For Each i In dt?.Rows Using conn As SqlConnection = New SqlConnection(My.Settings.LaserMaintLogConnectionString) conn.Open() Dim Status_Key As String = dt.Rows(i)(&quot;Status_Key&quot;) Try Dim PL_query As String = &quot;UPDATE [dbo].[Laser_Status_Info] &quot; &amp; &quot; SET [Shift_FKey] = '' &quot; &amp; &quot; WHERE [Status_Key] = '&quot; &amp; Status_Key &amp; &quot;';&quot; Using Cmd As New SqlCommand(query, conn) rowsAffected = Cmd.ExecuteNonQuery() End Using Catch ex As Exception MessageBox.Show(&quot;Error occured! : &quot; &amp; ex.Message) End Try ' Update Service request Try Dim PL_query As String = &quot;UPDATE [dbo].[Laser_Maint_Log] &quot; &amp; &quot; SET [SR_Shift_Key] = '' &quot; &amp; &quot; WHERE [SR_Status_Key] = '&quot; &amp; Status_Key &amp; &quot;';&quot; Using Cmd As New SqlCommand(query, conn) rowsAffected = Cmd.ExecuteNonQuery() End Using Catch ex As Exception MessageBox.Show(&quot;Error occured! : &quot; &amp; ex.Message) End Try conn.Close() End Using Next Return rowsAffected </code></pre> <p>End Function</p> </li> </ol>
3
1,294
Adding trend lines across groups and setting tick labels in a grouped violin plot or box plot
<p>I have <code>xy</code> grouped data that I'm plotting using <code>R</code>'s <code>ggplot2</code> <code>geom_violin</code> adding regression trend lines:</p> <p>Here are the data:</p> <pre><code>library(dplyr) library(plotly) library(ggplot2) set.seed(1) df &lt;- data.frame(value = c(rnorm(500,8,1),rnorm(600,6,1.5),rnorm(400,4,0.5),rnorm(500,2,2),rnorm(400,4,1),rnorm(600,7,0.5),rnorm(500,3,1),rnorm(500,3,1),rnorm(500,3,1)), age = c(rep(&quot;d3&quot;,500),rep(&quot;d8&quot;,600),rep(&quot;d24&quot;,400),rep(&quot;d3&quot;,500),rep(&quot;d8&quot;,400),rep(&quot;d24&quot;,600),rep(&quot;d3&quot;,500),rep(&quot;d8&quot;,500),rep(&quot;d24&quot;,500)), group = c(rep(&quot;A&quot;,1500),rep(&quot;B&quot;,1500),rep(&quot;C&quot;,1500))) %&gt;% dplyr::mutate(time = as.integer(age)) %&gt;% dplyr::arrange(group,time) %&gt;% dplyr::mutate(group_age=paste0(group,&quot;_&quot;,age)) df$group_age &lt;- factor(df$group_age,levels=unique(df$group_age)) </code></pre> <p>And my current plot:</p> <pre><code>ggplot(df,aes(x=group_age,y=value,fill=age,color=age,alpha=0.5)) + geom_violin() + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) + geom_smooth(data=df,mapping=aes(x=group_age,y=value,group=group),color=&quot;black&quot;,method='lm',size=1,se=T) + theme_minimal() </code></pre> <p><a href="https://i.stack.imgur.com/LrTt7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LrTt7.png" alt="enter image description here" /></a></p> <p>My questions are:</p> <ol> <li>How do I get rid of the <code>alpha</code> part of the <code>legend</code>?</li> <li>I would like the <code>x-axis</code> <code>ticks</code> to be <code>df$group</code> rather than <code>df$group_age</code>, which means a <code>tick</code> per each <code>group</code> at the center of that <code>group</code> where the label is <code>group</code>. Consider a situation where not all <code>group</code>s have all <code>age</code>s - for example, if a certain <code>group</code> has only two of the <code>age</code>s and I'm pretty sure <code>ggplot</code> will only present only these two <code>age</code>s, I'd like the <code>tick</code> to still be centered between their two <code>age</code>s.</li> </ol> <p>One more question:</p> <p>It would also be nice to have the p-values of each fitted slope plotted on top of each <code>group</code>.</p> <p>I tried:</p> <pre><code>library(ggpmisc) my.formula &lt;- value ~ group_age ggplot(df,aes(x=group_age,y=value,fill=age,color=age,alpha=0.5)) + geom_violin() + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) + geom_smooth(data=df,mapping=aes(x=group_age,y=value,group=group),color=&quot;black&quot;,method='lm',size=1,se=T) + theme_minimal() + stat_poly_eq(formula = my.formula,aes(label=stat(p.value.label)),parse=T) </code></pre> <p>But I get the same plot as above with the following <code>warning</code> message:</p> <pre><code>Warning message: Computation failed in `stat_poly_eq()`: argument &quot;x&quot; is missing, with no default </code></pre>
3
1,351
how to load child1.qml page on to main.qml page calling from another_child.qml page
<p><strong>In my MyHeader.qml cannot load the MyChild2.qml.</strong> How to load child qml page on to mmain.qml page calling from another child qml page as shown below.</p> <ul> <li><p>TestProject Folder</p> <ul> <li><p>qml Folder</p> <ul> <li>Main.qml</li> <li><p>MyChild1.qml</p></li> <li><p>mainui Folder</p> <ul> <li>MyHeader.qml</li> <li>MyChild2.qml</li> </ul></li> </ul></li> </ul></li> </ul> <hr> <pre><code>import QtQuick 2.10 import QtQuick.Controls 2.2 import "." // Main.qml ApplicationWindow { id: rootApp Loader { id: loaderPage anchors.fill: parent } MyChild1 { } } // MyChild1.qml import QtQuick 2.10 import QtQuick.Controls 2.2 import "." Page { id: myItem1 anchors.fill: parent MyHeader { anchors.top: parent.top } } // MyChild2.qml import QtQuick 2.10 import QtQuick.Controls 2.2 import "." Page { id: myItem2 anchors.fill: parent Rectangle { anchors.fill: parent color: "#000000" } } // MyHeader.qml import QtQuick 2.10 import QtQuick.Controls 2.2 import "." Rectangle { id: myHeader width: parent.width height: dp(30) color: "lightblue" Text { id: loadQML text: "Load QML" color: "#000000" font.pixelSize: dp(20) MouseArea { anchors.fill: parent onClicked: { myItem1.visible = false loaderPage.source = "MyChild2.qml" loaderPage.Top } } } } </code></pre> <hr> <p>Using the Loader and Connection I am getting Cannot assign to non-existent property "onPageChanged"</p> <pre><code>import QtQuick 2.10 import "mainui" ApplicationWindow { id: rootApp signal pageChanged(int page); Loader { id:rootLoader anchors.fill: parent source: "mainui/Page1.qml" Connections { target: rootLoader.item onPageChanged: { switch(page) { case 1: rootLoader.source = "mainui/Page1.qml"; break; case 2: rootLoader.source = "mainui/Page2.qml"; break; } } } } } // APP </code></pre>
3
1,201
Button To Perform 2 Actions VIA PHP POST
<p>I have this PHP script that performs two functions:</p> <ol> <li>Increases the count in an XML tag of prayer_warriors by 1.</li> <li>Sends a push notification to the proper user.</li> </ol> <p>In my app, I can POST, and all the functions of the script get carried out. The script code is:</p> <pre><code>&lt;?php $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $title = $_POST['title']; $deviceToken = $_POST['iostoken']; $xml = simplexml_load_file("/Test.xml") or die("Not loaded!\n"); $responses = $xml-&gt;xpath("//channel/item[title = '$title' and first_name = '$first_name' and last_name = '$last_name']/prayer_warriors"); $responses[0][0] = $responses[0] + 1; echo($responses); $xml-&gt;asXML("Test.xml"); // Put your device token here (without spaces): // Put your private key's passphrase here: $passphrase = 'Passphrase'; // Put your alert message here: $message = 'Someone just pledged to pray for you!'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client( 'ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array( 'alert' =&gt; $message, 'sound' =&gt; 'default' ); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) echo 'Message not delivered' . PHP_EOL; else echo 'Message successfully delivered' . PHP_EOL; // Close the connection to the server fclose($fp); ?&gt; </code></pre> <p>I use the following to POST to this PHP from a web page. It will trigger the part to send a push notification, but will NOT increase the prayer_warrior count by 1.</p> <pre><code>$title = $item-&gt;title; $first_name = $item-&gt;first_name; $last_name = $item-&gt;last_name; $iostoken = $item-&gt;iostoken; Echo "&lt;form action=\"http://Url.php\" method=\"post\"&gt;"; Echo "&lt;input type=\"hidden\" name=\"first_name\" value=".$first_name."&gt;"; Echo "&lt;input type=\"hidden\" name=\"last_name\" value=".$last_name."&gt;"; Echo "&lt;input type=\"hidden\" name=\"title\" value=".$title."&gt;"; Echo "&lt;input type=\"hidden\" name=\"iostoken\" value=".$iostoken."&gt;"; Echo "&lt;input type=\"submit\" name=\"submit\" value=\"Pledge to pray\" /&gt;"; Echo "&lt;/form&gt;"; </code></pre> <p>Any ideas why it would do this?</p>
3
1,057
Java lottery repeat program
<p>I need this lottery program to repeat itself a certain number of times and then stop, but I am having trouble on where to place the for loop (if that's what I should use). How can I display the percentage of times 0, 1, 2, 3, 4 or 5 numbers matched out of all the runs?</p> <pre><code> package assignment5; import javax.swing.JOptionPane; import java.util.Random; public class assignment5 { public static void main(String[] args) { lottery pic=new lottery(); pic.Get_player_numbers(); pic.Get_jackpot_number(); pic.Check_winner (); pic.Write_data(); } } class lottery { int[] picks= new int[5]; int[] cpick=new int[5]; int i; int j,c; int match=0; void Get_player_numbers () { int ctemp,cdupflag=0; for(j=0;j&lt;=4;++j) { //YOU DO NOT NEED THE CNUMBERFLAG //IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1 cdupflag=0; while(cdupflag==0) { ctemp = (int)Math.round(Math.random()*99)+1; cdupflag=1; for(c=0;c&lt;=j;++c) { if(ctemp==cpick[c]) { cdupflag=0; } }//inner for loop if(cdupflag==1) cpick[j]=ctemp; } } String Jackpot="User Lottery numbers are: "+"\n"; //String computer = ""; for(j=0;j&lt;=4;++j) { if(j==4) Jackpot=Jackpot+cpick[j]; else Jackpot=Jackpot+cpick[j]+"-"; } JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE); } //void jackpot() void Get_jackpot_number() { int ctemp,cdupflag=0; for(j=0;j&lt;=4;++j) { //YOU DO NOT NEED THE CNUMBERFLAG //IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1 cdupflag=0; while(cdupflag==0) { ctemp = (int)Math.round(Math.random()*99)+1; cdupflag=1; for(c=0;c&lt;=j;++c) { if(ctemp==cpick[c]) { cdupflag=0; } }//inner for loop if(cdupflag==1) cpick[j]=ctemp; } } String Jackpot="Computer Lottery numbers are: "+"\n"; //String computer = ""; for(j=0;j&lt;=4;++j) { if(j==4) Jackpot=Jackpot+cpick[j]; else Jackpot=Jackpot+cpick[j]+"-"; } JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE); } void Check_winner () { for(int i=0;i&lt;=4;++i) { for(int j=0;j&lt;=4;++j) { if(picks[i]==cpick[j]) { match=match+1; } } } } void Write_data () { String print = ""; if(match==0) { print=print+"There is no match"+"\n"; print=print+"please try again "+"\n"; } else if(match==1) { print=print+"There is one match"+"\n"; print=print+"You won 100 Dollars "+"\n"; } else if(match==2) { print=print+"There are two matches"+"\n"; print=print+"You won 1,000 Dollars"+"\n"; } else if(match==3) { print=print+"There are three matches"+"\n"; print=print+"You won 10,000 Dollars "+"\n"; } else if(match==4) { print=print+"There are four matches"+"\n"; print=print+"You won 100,000 Dollars "+"\n"; } else if(match==5) { print=print+"There are five matches"+"\n"; print=print+"You won 1,000,000 Dollars"+"\n"; } JOptionPane.showMessageDialog(null,print,"Output:",JOptionPane.INFORMATION_MESSAGE); }} //end of class lottery </code></pre>
3
2,341
Android Ksoap Passing Object as Parameter Error
<p>I am communicating with a web-service by sending an Object along with the request.</p> <p>This is the format of the request to the web-service.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Body&gt; &lt;UpdateLocation xmlns="http://tempuri.org/"&gt; &lt;location&gt; &lt;Id&gt;int&lt;/Id&gt; &lt;TabletId&gt;int&lt;/TabletId&gt; &lt;SpeedVisibility&gt;boolean&lt;/SpeedVisibility&gt; &lt;BeltVisibility&gt;boolean&lt;/BeltVisibility&gt; &lt;LightVisibility&gt;boolean&lt;/LightVisibility&gt; &lt;ProjectorVisibility&gt;boolean&lt;/ProjectorVisibility&gt; &lt;DefStart&gt;int&lt;/DefStart&gt; &lt;DefEnd&gt;int&lt;/DefEnd&gt; &lt;DefPickerCount&gt;int&lt;/DefPickerCount&gt; &lt;DefSlotCount&gt;int&lt;/DefSlotCount&gt; &lt;ServerIP&gt;string&lt;/ServerIP&gt; &lt;WebURL&gt;string&lt;/WebURL&gt; &lt;/location&gt; &lt;/UpdateLocation&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>This is my java code to make the request.</p> <pre><code>private void updateSettingsOnServer() { SoapObject request = new SoapObject(NAMESPACE, METHOD_UPDATE_SETTINGS); Location serverObject = new Location(currentLocation.databaseId, currentLocation.tabletId, currentLocation.isSpeedVisible, currentLocation.isBeltVisible, currentLocation.isLightVisible, currentLocation.isProjectorVisible, currentLocation.slotStarting, currentLocation.slotEnding, prefPickerCount, prefSlotCount, prefServerIPString, prefWebURL); PropertyInfo pi = new PropertyInfo(); pi.setName("serverObject"); pi.setValue(serverObject); pi.setType(serverObject.getClass()); request.addProperty(pi); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); envelope.addMapping(NAMESPACE,"Location",new Location().getClass()); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); try { androidHttpTransport.call(SOAP_ACTION_UPDATE_SETTINGS, envelope); SoapObject result=(SoapObject)envelope.getResponse(); //To get the data. tempText.setText("Received :" + result.toString()); } catch(Exception e) { tempText.setText("Error"); //Toast.makeText(context, "Error", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } </code></pre> <p>I made my custom class KVMSerializable in the following manner.</p> <pre><code>class Location implements KvmSerializable { public Location(int id, int tabletid, boolean speed, boolean belt, boolean light, boolean projector, int start, int end, int picker, int slot, String server, String web) { databaseId =id; tabletId = tabletid; isSpeedVisible = speed; isBeltVisible = belt; isLightVisible = light; isProjectorVisible = projector; slotStarting = start; slotEnding = end; pickerCounting = picker; slotCounting = slot; serverUrlLink = server; webUrlLink = web; } public Location() { // TODO Auto-generated constructor stub } boolean isSpeedVisible, isLightVisible, isBeltVisible, isProjectorVisible; int slotStarting, slotEnding , pickerCounting, slotCounting; int databaseId, tabletId; String serverUrlLink, webUrlLink; public Object getProperty(int arg0) { // TODO Auto-generated method stub switch(arg0) { case 0: return databaseId; case 1: return tabletId; case 2: return isSpeedVisible; case 3: return isBeltVisible; case 4: return isLightVisible; case 5: return isProjectorVisible; case 6: return slotStarting; case 7: return slotEnding; case 8: return pickerCounting; case 9: return slotCounting; case 11: return serverUrlLink; case 12: return webUrlLink; } return null; } public int getPropertyCount() { // TODO Auto-generated method stub return 12; } public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo info) { // TODO Auto-generated method stub switch(arg0) { case 0: info.type = PropertyInfo.INTEGER_CLASS; info.name = "databaseId"; break; case 1: info.type = PropertyInfo.INTEGER_CLASS; info.name = "tabletId"; break; case 2: info.type = PropertyInfo.BOOLEAN_CLASS; info.name = "isSpeedVisible"; break; case 3: info.type = PropertyInfo.BOOLEAN_CLASS; info.name = "isBeltVisible"; break; case 4: info.type = PropertyInfo.BOOLEAN_CLASS; info.name = "isLightVisible"; break; case 5: info.type = PropertyInfo.BOOLEAN_CLASS; info.name = "isProjectorVisible"; break; case 6: info.type = PropertyInfo.INTEGER_CLASS; info.name = "slotStarting"; break; case 7: info.type = PropertyInfo.STRING_CLASS; info.name = "slotEnding"; break; case 8: info.type = PropertyInfo.STRING_CLASS; info.name = "pickerCounting"; break; case 9: info.type = PropertyInfo.INTEGER_CLASS; info.name = "slotCounting"; break; case 11: info.type = PropertyInfo.STRING_CLASS; info.name = "serverUrlLink"; break; case 12: info.type = PropertyInfo.STRING_CLASS; info.name = "webUrlLink"; break; default:break; } } public void setProperty(int index, Object value) { // TODO Auto-generated method stub switch(index) { case 0: databaseId = Integer.parseInt(value.toString()); break; case 1: tabletId = Integer.parseInt(value.toString()); break; case 2: isSpeedVisible = Boolean.parseBoolean(value.toString()); break; case 3: isBeltVisible = Boolean.parseBoolean(value.toString()); break; case 4: isLightVisible = Boolean.parseBoolean(value.toString()); break; case 5: isProjectorVisible = Boolean.parseBoolean(value.toString()); break; case 6: slotStarting = Integer.parseInt(value.toString()); break; case 7: slotEnding = Integer.parseInt(value.toString()); break; case 8: pickerCounting = Integer.parseInt(value.toString()); break; case 9: slotCounting = Integer.parseInt(value.toString()); break; case 10: serverUrlLink = (value.toString()); break; case 11: webUrlLink = (value.toString()); break; default: break; } } } </code></pre> <p>But, unfortunately, it is not working.</p> <p>I am getting this <strong>error</strong>. I looked around a lot but still haven't been able to find a solution to this.</p> <pre><code>SoapFault - faultcode: 'soap:Server' faultstring: 'Server was unable to process request. ---&gt; Object reference not set to an instance of an object.' faultactor: 'null' detail </code></pre> <p>Please help/suggest me how to fix the error.</p>
3
3,084
php mysql: Duplicate entry on production but not on dev
<p>Oke, i've been busting my head on this one.</p> <p>I'm gonna try and keep things short, however, if you need more info, don't hesitate to ask.</p> <p>I've written an import repo for an external firm, so we can import their data into our service.</p> <h2>quick overview of implemented logic?</h2> <p>ftp, grab xml file, parse it with simple_xml and do db stuff using laravel eloquent component.</p> <p>on my dev machine, every run gets parsed fully and all data is inserted correctly into the database.</p> <h2>problem</h2> <p>when i try the same thing on my production server. I'm receiving a duplicate entry error, always on the same exact record. (unless i'm using another file)</p> <h2>pre script setup to help detect the error</h2> <p>on each run i do the following:</p> <ul> <li>make sure i'm using the exact same files on both dev and prod environment... (i've disabled the ftpgrab and uploaded manually to the correct location) </li> <li>truncate all the related tables so i'm always starting with empty! tables.</li> <li>i've manually triple-zillion checked for duplicates in the xml, but they're not in there.... and the fact that my dev machine parses the file correctly confirms this.</li> </ul> <h2>what i tried</h2> <p>at this point, i've got no more clues as to how i'm supposed to debug this properly.</p> <p>by now, i've checked so many things (most of them i can't even remember), all of which seemed pretty unrelated to me, but i had to try them. those things include:</p> <ul> <li>automatic disconnects due to browser</li> <li>mysql wait timeouts</li> <li>php script timeouts</li> <li>memory settings</li> </ul> <p>none of them seem to help (which was exactly what i was expecting)</p> <h2>another fact</h2> <p>my php version on my dev is 5.4.4 and the version on the production server is 5.3.2 (i know this is bad practise, but i'm not using any new features, it's really dead easy code, though it has quite a few lines :-) )</p> <p>i've been suspecting this to be the cause, but</p> <p>i've now switched to 5.3.14 on my dev... still the import runs without an issue</p> <p>the changes from 5.3.2 to 5.3.14 are probably pretty minor</p> <p>i've tried to manually compile the exact same php version, but i'm to inexperienced to properly do this. moreover, it probably wouldn't have the exact same specs anyway (i think it's pretty impossibly to ./configure exactly the same, considering the use of MacOs vs Ubuntu? especially for a noob like me) So i've abandoned this path.</p> <p>I've tried to find the differences in the php versions, but i can't seem to stumble upon anything that might be the cause to all this. there was a change related to non-numeric keys in arrays (or strings for that matter) in version 5.4.4 (i think) but since i've now come to the conclusion that 5.3.14 also works, this definitely is not the issue. --- looking around insecurely hoping not having said anything downright stupid ---</p> <h2>quick thought while writing this:</h2> <p>the thing is, even though i'm getting the duplicate error statement. The record did get inserted into the database. moreover, the error gets triggered when having processed about 2700 (of total 6000) records. the bound data to the query is actually the data of the second record in the xml file.)</p> <p>I'm sincerely hoping anyone could put me on the right track for this issue :( If you made it this far, but don't have a clue about what's going on, thx for reading and sticking to it.</p> <p>If you might have clue, please enlighten me!</p>
3
1,038
Unnamed Pipes in UNIX child message doesn't get received by father while sending a string in C
<p>I have two processes that I have created with two unnamed pipes, but I can't figure out why I can't send messages from the sons to the father. It appears that the father doesn't receive the string. The son is sending the right string; it just doesn't reach destination, can't figure out why ... Can you explain to me?</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;sys/wait.h&gt; #include &lt;sys/types.h&gt; #include &lt;stdio.h&gt; #include &lt;strings.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; #include &lt;errno.h&gt; #include &lt;time.h&gt; #define max_chars_string 1000 #define n_childs 2 pid_t childs[n_childs]; int channel[n_childs][2]; void read_lines(char * filename, char (*pointer)[max_chars_string],int init_read,int n_lines); void get_strings_hash(char (*pointer_strings)[max_chars_string],char (*pointer_hashes)[max_chars_string],int total_lines); void worker(int mypipe,char filename[],int n_lines){ // meter as funcoes de ler passwords no filho int resources[2];// numero de linhas que cada processo tem de ler int i = 0; //definicao arrays char strings_hashes[n_lines][max_chars_string];//aray de string com as strings lidas do ficheiro char * pointer_strings = &amp;strings_hashes[0][0];//ponteiro para o inicio do array das hashes read_lines(filename,strings_hashes,0,n_lines); // le as strings do ficheiro e passa para o array for(i = 0;i&lt;n_lines;i++){ printf("%s \n",strings_hashes[i]); } printf("[%d] My parent is: %d\n", getpid(), getppid()); //open pipe to write and close pipe to read close(channel[mypipe][0]); i = 0; int incr = 0; while (i&lt;n_lines) { printf("[Son] Password sent e %s: \n",strings_hashes[incr]); write(channel[mypipe][1], strings_hashes[incr], strlen(strings_hashes[incr])); incr++; i++; } exit(0); } int main(int argc, char **argv) { char *filename; int status;//status do processos filho int resources[2];// numero de linhas que cada processo tem de ler int n_lines; //numero de linhas do ficheiro int i = 0; // Create a pipe filename = (char*)malloc(strlen(argv[1])*sizeof(char)+1); if(argc !=3){ fprintf(stderr, "Usage : %s [text_file] [cores]",argv[0]); exit(0); } strcpy(filename,argv[1]); char get_file [strlen(filename)]; strcpy(get_file,filename); // start the processes for(i = 0; i &lt;atoi(argv[2]);i++){ pipe(channel[i]); childs[i] = fork(); if(childs[i] == -1){ perror("Failed to fork"); return 1; } if (childs[i] == 0) { worker(i,get_file,n_lines); } close(channel[i][1]); } i = 0; int k = 0; int fd; fd_set read_set; FD_ZERO(&amp;read_set); char string_lida [30]; // working father printf("[%d] I'm the father!\n", getpid()); printf("[Father]orking ...\n"); //unammed_pipes connection while(k&lt;n_childs){ FD_SET(channel[0][0], &amp;read_set); for(i=0;i&lt;n_childs;i++){ FD_SET(channel[i][0], &amp;read_set); if(fd&lt;channel[i][0]){ fd=channel[i][0]; } } if(select(fd+1,&amp;read_set,NULL,NULL,NULL)&gt;0){ for(i=0;i&lt;n_childs;i++){ if(FD_ISSET(channel[i][0], &amp;read_set)){ read(channel[i][0],string_lida,strlen(string_lida)); printf("[Father]pipe %d - string lida:%s\n",i,string_lida); k++; } } } fd=1; } // //waiting for childs ... for(i=0;i&lt;n_childs;i++){ wait(&amp;status); printf("waiting for childs \n"); } return 0; } void get_strings_hash(char (*pointer_strings)[max_chars_string],char (*pointer_hashes)[max_chars_string],int total_lines)//vai ao array de strings e corta a parte de hash e mete num array { int i = 0; char *strings; char *hash; for(i = 0;i&lt;total_lines;i++){ strings = (char*)malloc(strlen(pointer_strings)*sizeof(char)+1); strcpy(strings,*pointer_strings); hash = (char*)malloc(strlen(pointer_strings)*sizeof(char)+1); find_hash(strings,hash); strcpy(*pointer_hashes,hash); pointer_hashes++; pointer_strings++; } } void read_lines(char * filename, char (*pointer)[max_chars_string],int init_read,int n_lines){ FILE *fp; char str[max_chars_string]; int i =0; if((fp = fopen(filename, "r"))==NULL) { printf("Cannot open file.\n"); exit(1); } if(init_read&gt;0 &amp;&amp; init_read&lt;=n_lines){ for(i = 0;i&lt;init_read;i++){ fgets(str, sizeof str, fp); for(i = init_read;i&lt;n_lines;i++){ fgets(str, sizeof str, fp); strcpy(*pointer, str); //copia para a posicao actula do ponteiro pointer++; } } } if(init_read&lt;=n_lines &amp;&amp; init_read==0){ for(i = init_read;i&lt;n_lines;i++){ fgets(str, sizeof str, fp); strcpy(*pointer, str); //copia para a posicao actula do ponteiro pointer++; } } fclose(fp); } </code></pre>
3
3,368
Required in contact form fails
<p>I have tried to create an simple contact form using AngularJS</p> <p>code >></p> <pre><code>&lt;div class='main'&gt; &lt;h2&gt;AngularJS Form Validation&lt;/h2&gt; &lt;form name="myForm" ng-controller="Ctrl"&gt; &lt;table&gt; &lt;tr&gt;&lt;td&gt;Username&lt;/td&gt;&lt;td&gt; &lt;input type="text" name="s_word" ng-model="m_word" ng-pattern="word" required ng-trim="false"&gt; &lt;span class="error" ng-show="myForm.s_word.$error.required"&gt;Required!&lt;/span&gt; &lt;span class="error" ng-show="myForm.s_word.$error.pattern"&gt;Single word only!&lt;/span&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt; URL&lt;/td&gt;&lt;td&gt; &lt;input type="url" name="in_url" ng-model="m_url" required&gt; &lt;span class="error" ng-show="myForm.in_url.$error.required"&gt;Required!&lt;/span&gt; &lt;span class="error" ng-show="myForm.in_url.$error.url"&gt;Not valid url!&lt;/span&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Email &lt;/td&gt;&lt;td&gt;&lt;input type="email" placeholder="Email" name="email" ng-model="m_email" ng-minlength=3 ng-maxlength=20 required /&gt; &lt;span class="error" ng-show="myForm.email.$error.required"&gt;Required!&lt;/span&gt; &lt;span class="error" ng-show="myForm.email.$error.minlength"&gt;Not less that 3 char&lt;/span&gt; &lt;span class="error" ng-show="myForm.email.$error.email"&gt;Invalid Email!&lt;/span&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt; Phone&lt;/td&gt;&lt;td&gt; &lt;input type="text" placeholder="33-333-33333" name="phone" ng-pattern="ph_numbr" ng-model="m_phone" /&gt; &lt;span class="error" ng-show="myForm.phone.$error.required"&gt;Required!&lt;/span&gt; &lt;span class="error" ng-show="myForm.phone.$error.minlength"&gt;Not less that 10 char&lt;/span&gt; &lt;span class="error" ng-show="myForm.phone.$error.maxlength"&gt;Not More than 11 char&lt;/span&gt; &lt;span class="error" ng-show="myForm.phone.$error.pattern"&gt;Pls Match Pattern [12-236-23658 ]&lt;/span&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt; Message&lt;/td&gt;&lt;td&gt;&lt;input type="text" placeholder="Message here" name="Message" ng-pattern="Msg" ng-model="m_message" ng-minlength=20 /&gt; &lt;span class="error" ng-show="myForm.Message.$error.required"&gt;Required!&lt;/span&gt;&lt;/td&gt; &lt;tr&gt;&lt;td&gt; &lt;button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true"&gt;Submit&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; &lt;/div&gt; .main{ margin: 10px auto; width:350px; border: 1px solid #ccc; padding: 20px; } .error{ color:red; } function Ctrl($scope) { $scope.m_word = ''; $scope.word = /^\s*\w*\s*$/; $scope.m_url = 'http://example.com'; $scope.ph_numbr = /^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/; $scope.Msg = ''; } </code></pre> <p><a href="http://code.angularjs.org/1.2.9/angular.min.js" rel="nofollow">http://code.angularjs.org/1.2.9/angular.min.js</a> Angular link is granted from above link Above I have provided full code of form. In my Chrome, phone number and message is required is not working.</p> <p>Get me out of here anyone please.</p>
3
2,261
Taking exception.stack prints correctly until attempting to parse the string in ReactJS
<p>I am working on a project where I am trying to parse an exception object which I retrieve from the exception object created in a catch, using <code>exception.stack</code>.</p> <p>Below is the code to parse the stacktrace</p> <pre><code>getLineNoFromStacktrace(stack) { console.log(&quot;The stack is&quot;); console.log(stack); const stackSplit = stack.split(/\r?\n/); console.log(stackSplit); console.log(&quot;Stack line 1: &quot;); console.log(stack); /*stack = stack.replace(&quot;http://&quot;); stack = stack.replace(&quot;https://&quot;); //Get the first colon (:), after this is the line number)*/ const lineInfo = stack.substring(stack.indexOf(&quot;:&quot;)+1); console.log(&quot;Line info: &quot; + lineInfo); //Now what we have left, the colon next is the end of the line number return lineInfo.substring(0, lineInfo.indexOf(&quot;:&quot;)); } </code></pre> <p>The method above I print the stack which prints out correctly as I am expecting as below:</p> <pre><code>The stack is index.js:199 TypeError: Cannot read property 'toString' of null at sendHandledException (Home.js:18) at HTMLUnknownElement.callCallback (react-dom.development.js:3945) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994) at invokeGuardedCallback (react-dom.development.js:4056) at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070) at executeDispatch (react-dom.development.js:8243) at processDispatchQueueItemsInOrder (react-dom.development.js:8275) at processDispatchQueue (react-dom.development.js:8288) at dispatchEventsForPlugins (react-dom.development.js:8299) at react-dom.development.js:8508 at batchedEventUpdates$1 (react-dom.development.js:22396) at batchedEventUpdates (react-dom.development.js:3745) at dispatchEventForPluginEventSystem (react-dom.development.js:8507) at attemptToDispatchEvent (react-dom.development.js:6005) at dispatchEvent (react-dom.development.js:5924) at unstable_runWithPriority (scheduler.development.js:646) at runWithPriority$1 (react-dom.development.js:11276) at discreteUpdates$1 (react-dom.development.js:22413) at discreteUpdates (react-dom.development.js:3756) at dispatchDiscreteEvent (react-dom.development.js:5889) </code></pre> <p>The next line is I perform a split on the new line characeters \r and \n and then log out the array that is created</p> <pre><code>0: &quot;TypeError: Cannot read property 'toString' of null&quot; 1: &quot; at sendHandledException (http://localhost:3000/static/js/main.chunk.js:642:24)&quot; 2: &quot; at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/0.chunk.js:8078:18)&quot; 3: &quot; at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/0.chunk.js:8127:20)&quot; 4: &quot; at invokeGuardedCallback (http://localhost:3000/static/js/0.chunk.js:8187:35)&quot; 5: &quot; at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/static/js/0.chunk.js:8202:29)&quot; 6: &quot; at executeDispatch (http://localhost:3000/static/js/0.chunk.js:12437:7)&quot; 7: &quot; at processDispatchQueueItemsInOrder (http://localhost:3000/static/js/0.chunk.js:12469:11)&quot; 8: &quot; at processDispatchQueue (http://localhost:3000/static/js/0.chunk.js:12482:9)&quot; 9: &quot; at dispatchEventsForPlugins (http://localhost:3000/static/js/0.chunk.js:12493:7)&quot; 10: &quot; at http://localhost:3000/static/js/0.chunk.js:12704:16&quot; 11: &quot; at batchedEventUpdates$1 (http://localhost:3000/static/js/0.chunk.js:26389:16)&quot; 12: &quot; at batchedEventUpdates (http://localhost:3000/static/js/0.chunk.js:7876:16)&quot; 13: &quot; at dispatchEventForPluginEventSystem (http://localhost:3000/static/js/0.chunk.js:12703:7)&quot; 14: &quot; at attemptToDispatchEvent (http://localhost:3000/static/js/0.chunk.js:10186:7)&quot; 15: &quot; at dispatchEvent (http://localhost:3000/static/js/0.chunk.js:10104:23)&quot; 16: &quot; at unstable_runWithPriority (http://localhost:3000/static/js/0.chunk.js:37465:16)&quot; 17: &quot; at runWithPriority$1 (http://localhost:3000/static/js/0.chunk.js:15484:14)&quot; 18: &quot; at discreteUpdates$1 (http://localhost:3000/static/js/0.chunk.js:26406:18)&quot; 19: &quot; at discreteUpdates (http://localhost:3000/static/js/0.chunk.js:7888:16)&quot; 20: &quot; at dispatchDiscreteEvent (http://localhost:3000/static/js/0.chunk.js:10070:7)&quot; </code></pre> <p>As you can see above, when I log out the stack where I've split by line, the output is completely different so I no longer have the data that I originally had when I first printed the console.</p> <p>How can I parse this exception.stack and maintain the original the content that first logged at the start of the method.</p>
3
1,894
How to use the OnClickListener attribute for button by its ID in android java
<p>I am trying to achieve the same result by id for every button, using onClickListener. This is the link to the original code where onClick is used for all buttons without creating id for reference. The reason why I intended to create id for every button unlike in the original code is I felt the original code is kinda simplified but I thought to challenge myself to see if the same result can be achieved by using reference, though I know its complexity. But I am trying to do things differently and not just blindly copy-paste the code :)</p> <p>Any help is highly appreciated!</p> <p>p.s. Please consider code related to button code only as I am getting error in that part and I haven't yet gone any beyond in the original code.</p> <p>[<a href="https://gist.github.com/udacityandroid/4edd7beac8465acc07ca][1]" rel="nofollow noreferrer">https://gist.github.com/udacityandroid/4edd7beac8465acc07ca][1]</a></p> <p>Attached is my code using ids for buttons.`</p> <pre><code> **activity_main.xml** &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"&gt; &lt;TextView android:id="@+id/Team_Name_A" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="Team A" android:gravity="center_horizontal" /&gt; &lt;TextView android:id="@+id/Scored_Points" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="0" android:padding="20dp" android:gravity="center_horizontal" /&gt; &lt;Button android:id="@+id/Beyond_Three_Point_Line" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="+3 Points" android:onClick="addThreeForTeamA"/&gt; &lt;Button android:id="@+id/Within_Three_Point_Line" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="+2 Points" android:onClick="addTwoForTeamA"/&gt; &lt;Button android:id="@+id/Foul_Free_Throw" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Free Throw!" android:onClick="addOneForTeamA"/&gt; &lt;/Linear **MainActivity.java** package com.example.scorebasket; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void addThreeForTeamA (View view){ Button button1 = (Button) findViewById(R.id.Beyond_Three_Point_Line); button1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { } }); public void addTwoForTeamA (View view){ Button button2 = (Button) findViewById(R.id.Within_Three_Point_Line); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { } }); public void addOneForTeamA (View view){ Button button3 = (Button) findViewById(R.id.Foul_Free_Throw); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { } }); } /** * Displays the given score for Team A * */ public void scoreEarnedByTeamA(int score) { TextView scoreView = (TextView) findViewById(R.id.Scored_Points); scoreView.setText(String.valueOf(score)); } } </code></pre>
3
1,328
php cURL doesnt print out anything
<p>I am trying to send a HTML form POST data with a cURL, but it seems the response is always empty. I first save all the POST data in an array, and use an implode function. When I echo out the implode string it does return the values, but after the cURL it's just empty.</p> <p>This is the setup. I call this function after submitting the form</p> <pre><code>$this-&gt;OCIcURL($this-&gt;request-&gt;post); public function OCIcURL($post) { $data_oci = array(); $items_oci = array(); $counter = 0; $data_oci['~caller'] = 'CTLG'; foreach ($post['item'] as $key =&gt; $value) { $counter++; $data_oci['NEW_ITEM-DESCRIPTION[' . $counter . ']'] = $value; $data_oci['NEW_ITEM-MATNR[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-QUANTITY[' . $counter . ']'] = $post['amount'][$counter]; $data_oci['NEW_ITEM-UNIT[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-PRICE[' . $counter . ']'] = $post['price'][$counter]; $data_oci['NEW_ITEM-CURRENCY[' . $counter . ']'] = $this-&gt;session-&gt;data['currency']; $data_oci['NEW_ITEM-PRICEUNIT[' . $counter . ']'] = 1; $data_oci['NEW_ITEM-LEADTIME[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-VENDOR[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-VENDORMAT[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-MANUFACTCODE[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-MANUFACTMAT[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-MATGROUP[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-SERVICE[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-CONTRACT[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-CONTRACT_ITEM[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-EXT_QUOTE_ID[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-EXT_QUOTE_ITEM[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-EXT_PRODUCT_ID[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-ATTACHMENT[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-ATTACHMENT_TITLE[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-ATTACHMENT_PURPOSE[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-EXT_SCHEMA_TYPE[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-EXT_CATEGORY_ID[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-CUST_FIELD1[' . $counter . ']'] = 21; $data_oci['NEW_ITEM-PARENT_ID[' . $counter . ']'] = ""; $data_oci['NEW_ITEM-ITEM_TYPE[' . $counter . ']'] = ""; } foreach ($data_oci as $key =&gt; $value) { $items_oci[] = $key . '=' . $value; } $string_oci = implode('&amp;', $items_oci); </code></pre> <p>If I echo out the <code>$string_oci</code> I do get a result. After this I use the cURL to send the string to a link.</p> <pre><code> $url = "http://localhost/test.php"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $string_oci); curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $response = curl_exec($ch); var_dump($response); } </code></pre> <p>The var_dump is always empty, returning <code>string(0) ""</code>. I also tried this on the live website, same result.</p> <p>I used this piece of code to see any errors, but it seems it there arent any error at all, but the <code>var_dump</code> is always empty.</p> <pre><code> if (curl_exec($ch) === FALSE) { print_r(curl_getinfo($ch)); die("Curl error: " . curl_error($ch)); } else { curl_close($ch); } </code></pre>
3
1,912
To setup bootstrap on yii
<p>I installed the Yii-Bootstrap and keep it in the protected/extensions folder. After that i extract the zip file and named it bootstrap. As the documentation of <a href="http://www.cniska.net/yii-bootstrap/setup.html" rel="nofollow">http://www.cniska.net/yii-bootstrap/setup.html</a>.</p> <p>I change the file config/main.php like this.But i cant get the result. If i did the wrong thing, Please suggest me here how can i use the bootstrap on yii.</p> <pre><code>&lt;?php // uncomment the following to define a path alias // Yii::setPathOfAlias('local','path/to/local-folder'); // This is the main Web application configuration. Any writable // CWebApplication properties can be configured here. Yii::setPathOfAlias('bootstrap', dirname(__FILE__).'/extensions/bootstrap'); return array( 'basePath'=&gt;dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=&gt;'Tantra Songs', 'theme'=&gt;'bootstrap', // requires you to copy the theme under your themes directory // preloading 'log' component 'preload'=&gt;array('log','application.ext.bootstrap.*'), // autoloading model and component classes 'import'=&gt;array( 'application.models.*', 'application.components.*', 'application.ext.bootstrap.*', 'application.modules.user.models.*', 'application.modules.user.components.*', ), 'modules'=&gt;array( // uncomment the following to enable the Gii tool 'gii'=&gt;array( 'generatorPaths'=&gt;array( 'bootstrap.gii', ), ), 'user'=&gt;array( # encrypting method (php hash function) 'hash' =&gt; 'md5', # send activation email 'sendActivationMail' =&gt; true, # allow access for non-activated users 'loginNotActiv' =&gt; false, # activate user on registration (only sendActivationMail = false) 'activeAfterRegister' =&gt; false, # automatically login from registration 'autoLogin' =&gt; true, # registration path 'registrationUrl' =&gt; array('/user/registration'), # recovery password path 'recoveryUrl' =&gt; array('/user/recovery'), # login form path 'loginUrl' =&gt; array('/user/login'), # page after login 'returnUrl' =&gt; array('/user/profile'), # page after logout 'returnLogoutUrl' =&gt; array('/user/login'), ), ), // application components 'components'=&gt;array( 'user'=&gt;array( // enable cookie-based authentication 'allowAutoLogin'=&gt;true, ), 'bootstrap'=&gt;array( 'class'=&gt;'bootstrap.components.Bootstrap', ), // uncomment the following to enable URLs in path-format 'urlManager'=&gt;array( 'urlFormat'=&gt;'path', 'rules'=&gt;array( '&lt;controller:\w+&gt;/&lt;id:\d+&gt;'=&gt;'&lt;controller&gt;/view', '&lt;controller:\w+&gt;/&lt;action:\w+&gt;/&lt;id:\d+&gt;'=&gt;'&lt;controller&gt;/&lt;action&gt;', '&lt;controller:\w+&gt;/&lt;action:\w+&gt;'=&gt;'&lt;controller&gt;/&lt;action&gt;', ), ), /* 'db'=&gt;array( 'connectionString' =&gt; 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db', ),*/ // uncomment the following to use a MySQL database 'db'=&gt;array( 'connectionString' =&gt; 'mysql:host=localhost;dbname=nt_songs', 'emulatePrepare' =&gt; true, 'username' =&gt; 'root', 'password' =&gt; 'root', 'charset' =&gt; 'utf8', 'tablePrefix' =&gt; 'nt_', ), 'errorHandler'=&gt;array( // use 'site/error' action to display errors 'errorAction'=&gt;'site/error', ), 'log'=&gt;array( 'class'=&gt;'CLogRouter', 'routes'=&gt;array( array( 'class'=&gt;'CFileLogRoute', 'levels'=&gt;'error, warning', ), // uncomment the following to show log messages on web pages /* array( 'class'=&gt;'CWebLogRoute', ), */ ), ), ), ); </code></pre>
3
1,851
It doesn't load from Firebase on the Fragment Activity ('FragmentOne' is clear and it shouldn't be)
<p>I made a Recycler View on a Fragment , wired it with the Firebase, but it won't show anything on the activity , doesn't load from Firebase.. I verified the code and the procedure a thousand times , I really don't know what to do , maybe its a problem in my code or connections..</p> <p>Fragment class :</p> <pre><code>public class FragmentUnu extends Fragment { View v; FirebaseDatabase mDatabase; DatabaseReference mRef; RecyclerView mRecycler; RecyclerView.LayoutManager layoutManager; FirebaseRecyclerAdapter &lt; FragmentUnuModel, FragmentUnuViewHolder &gt; adapter; public FragmentUnu() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); v = inflater.inflate(R.layout.unu_fragment, container, false); mRecycler = (RecyclerView) v.findViewById(R.id.fragment_unu_recycler); mRecycler.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getActivity()); mRecycler.setLayoutManager(layoutManager); mDatabase = FirebaseDatabase.getInstance(); mRef = mDatabase.getReference("FragmentId"); FirebaseRecyclerOptions &lt; FragmentUnuModel &gt; options = new FirebaseRecyclerOptions.Builder &lt; FragmentUnuModel &gt; () .setQuery(mRef, FragmentUnuModel.class) .build(); adapter = new FirebaseRecyclerAdapter &lt; FragmentUnuModel, FragmentUnuViewHolder &gt; (options) { @NonNull @Override public FragmentUnuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.unu_fragment_item, parent, false); return new FragmentUnuViewHolder(itemView); } @Override protected void onBindViewHolder(@NonNull FragmentUnuViewHolder fragmentUnuViewHolder, int i, @NonNull FragmentUnuModel fragmentUnuModel) { fragmentUnuViewHolder.denumire.setText(fragmentUnuModel.getDenumire()); fragmentUnuViewHolder.descriere.setText(fragmentUnuModel.getDescriere()); fragmentUnuViewHolder.pret.setText(fragmentUnuModel.getPret()); Picasso.with(getActivity().getBaseContext()).load(fragmentUnuModel.getImagine()).into(fragmentUnuViewHolder.img); } }; return v; } @Override public void onStart() { super.onStart(); adapter.startListening(); mRecycler.setAdapter(adapter); } @Override public void onStop() { super.onStop(); adapter.stopListening(); } } </code></pre> <p>This is my MainActivity class with the fragments :</p> <pre><code>public class Food extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private ViewPagerAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.food_activity); tabLayout = (TabLayout) findViewById(R.id.tabs); viewPager = (ViewPager) findViewById(R.id.viewpager); adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.AddFragment(new FragmentUnu(), "Unu"); adapter.AddFragment(new FragmentDoi(), "Doi"); adapter.AddFragment(new FragmentTrei(), "Trei"); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); } } </code></pre> <p>I don't have any erros in the debugger</p>
3
1,260
Stop Gridview Value to change when I click on Edit buitton
<p>I need help with this Gridview issue. I build a dropdown search on the Gridview base on the ID as shown by the image below</p> <p><a href="https://i.stack.imgur.com/Jc964.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jc964.jpg" alt="enter image description here"></a></p> <p>The problem I have is when I click the Edit button to update the Gridview the value of the Gridview change and go back to the first value in the table as shown by the image below</p> <p><a href="https://i.stack.imgur.com/0JLBn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0JLBn.jpg" alt="enter image description here"></a></p> <p>C# Code GridViewMYD88_RowUpdating</p> <pre><code> protected void GridViewMYD88_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridViewMYD88.Rows[e.RowIndex]; Label TestID = (Label)GridViewMYD88.Rows[e.RowIndex].FindControl("lblId"); Label SampleBranchID = (Label)GridViewMYD88.Rows[e.RowIndex].FindControl("lblSampleBranchID"); string TechniqueforMYD88 = (row.FindControl("txtTechniqueforMYD88") as TextBox).Text; string MYD88ExonsAnalyzed = (row.FindControl("txtMYD88ExonsAnalyzed") as TextBox).Text; string SequenceofEntireMYD88 = (row.FindControl("txtSequenceofEntireMYD88") as TextBox).Text; string MYD88MutationStatus = (row.FindControl("txtMYD88MutationStatus") as TextBox).Text; string NumberofMYD88Mutations = (row.FindControl("txtNumberofMYD88Mutations") as TextBox).Text; string MYD88pL265PMutation = (row.FindControl("txtMYD88pL265PMutation") as TextBox).Text; string OtherMYD88MutationDescription = (row.FindControl("txtOtherMYD88MutationDescription") as TextBox).Text; string MYD88VAFPercentage = (row.FindControl("txtMYD88VAFPercentage") as TextBox).Text; string MYD88RefAllelesReads = (row.FindControl("txtMYD88RefAllelesReads") as TextBox).Text; string MYD88VariantAllelesReads = (row.FindControl("txtMYD88VariantAllelesReads") as TextBox).Text; string MYD88OverallReadDepth = (row.FindControl("txtMYD88OverallReadDepth") as TextBox).Text; using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString)) { con.Open(); using (SqlCommand sc = new SqlCommand(@"UPDATE MutationResults SET TechniqueforMYD88=@TechniqueforMYD88, MYD88ExonsAnalyzed=@MYD88ExonsAnalyzed, SequenceofEntireMYD88=@SequenceofEntireMYD88, MYD88MutationStatus=@MYD88MutationStatus, NumberofMYD88Mutations=@NumberofMYD88Mutations, MYD88pL265PMutation=@MYD88pL265PMutation, OtherMYD88MutationDescription=@OtherMYD88MutationDescription, MYD88VAFPercentage=@MYD88VAFPercentage, MYD88RefAllelesReads=@MYD88RefAllelesReads, MYD88VariantAllelesReads=@MYD88VariantAllelesReads, MYD88OverallReadDepth=@MYD88OverallReadDepth WHERE ID=@TestID and SampleBranchID=@SampleBranchID", con)) { sc.Parameters.AddWithValue("@TestID", TestID.Text); sc.Parameters.AddWithValue("@SampleBranchID", SampleBranchID.Text); sc.Parameters.AddWithValue("@TechniqueforMYD88", TechniqueforMYD88); sc.Parameters.AddWithValue("@MYD88ExonsAnalyzed", MYD88ExonsAnalyzed); sc.Parameters.AddWithValue("@SequenceofEntireMYD88", SequenceofEntireMYD88); sc.Parameters.AddWithValue("@MYD88MutationStatus", MYD88MutationStatus); sc.Parameters.AddWithValue("@NumberofMYD88Mutations", NumberofMYD88Mutations); sc.Parameters.AddWithValue("@MYD88pL265PMutation", MYD88pL265PMutation); sc.Parameters.AddWithValue("@OtherMYD88MutationDescription", OtherMYD88MutationDescription); sc.Parameters.AddWithValue("@MYD88VAFPercentage", MYD88VAFPercentage); sc.Parameters.AddWithValue("@MYD88RefAllelesReads", MYD88RefAllelesReads); sc.Parameters.AddWithValue("@MYD88VariantAllelesReads", MYD88VariantAllelesReads); sc.Parameters.AddWithValue("@MYD88OverallReadDepth", MYD88OverallReadDepth); sc.ExecuteScalar(); } con.Close(); } GridViewMYD88.EditIndex = -1; this.BindGridMutationResults(); } </code></pre> <p>Any help how to solve this issue. Thanks</p>
3
1,968
XMLNodeList null reference even after checking the next innertext value in advance
<p>I am trying to get the value from the next item, for example, if the next item is null, or doesnt exist, it will proceed to printing. The main problem i am having lies only at this part</p> <p>Main Question : </p> <pre><code>try { numCheck = productList[j+1]["Number"].InnerText; } catch (Exception ex) { numCheck = string.Empty; } if (numCheck != null) { try { mainNumber = Data.getFullItemDetail(productList[j + 1]["Number"].InnerText); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } </code></pre> <p>I did a check before i tried if else just to make sure the value exist, however, even after it detects that it has a value, this line will throw an error NullReference</p> <pre><code>mainNumber = Data.getFullItemDetail(productList[j + 1]["Number"].InnerText); </code></pre> <p>FULL Code just in case: </p> <pre><code>XmlDocument xml = new XmlDocument(); xml.LoadXml(productItems); XmlNodeList productList = xml.SelectNodes("/Products/Product"); for (int j = 0; j &lt; productList.Count; j++) { itemCount++; int i = j + 1; string item = productList[j]["Number"].InnerText; number = Data.getFullItemDetail(item); try { #region mainItem if (number == 0) { itemCount++; itemName = productList[j]["Name"].InnerText; try { numCheck = productList[i]["Number"].InnerText; } catch (Exception ex) { numCheck = string.Empty; } if (numCheck != null) { try { mainNumber = Data.getFullItemDetail(productList[i]["Number"].InnerText); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } if (mainNumber == 0) { foreach (string condimentItem in condiment) { condimentText += condimentItem.ToString() + "\n"; } string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n"; //print here, because the next item is another main item. }; try { p.Print(); } catch (Exception ex) { throw new Exception("Exception Occured While Printing", ex); } } else { MessageBox.Show("Error"); } } else { foreach (string condimentItem in condiment) { condimentText += condimentItem.ToString() + "\n"; } string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n"; } } #endregion #region CondimentItem else if (number == 4) { condiment.Add(productList[j]["Name"].InnerText); try { numCheck = productList[i]["Number"].InnerText; } catch (Exception ex) { numCheck = string.Empty; } //Check next item. if (numCheck == null) { foreach (string condimentItem in condiment) { condimentText += condimentItem.ToString() + "\n"; } string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n"; //print here, because the next item is another main item. } else { mainNumber = Data.getFullItemDetail(productList[i]["Number"].InnerText); if (mainNumber == 0) { foreach (string condimentItem in condiment) { condimentText += condimentItem.ToString() + "\n"; } string text = condimentText + itemName + "\n" + employeeNum + "\n" + terminalNum + "\n"; //print here, because the next item is another main item. } } } #endregion } catch (Exception ex) { MessageBox.Show(ex.ToString()); } </code></pre> <p>Edited : Data.getFullItemDetail only returns 1 int value.</p> <pre><code> public static int getFullItemDetail(string number) { int num = Convert.ToInt32(number); int numReturn; using (SqlConnection conn = getConnectionSAP()) { SqlCommand comm = new SqlCommand("select belongcond from ------ where number = " + num, conn); conn.Open(); SqlDataReader dr = comm.ExecuteReader(); while (dr.Read()) { num = Convert.ToInt32(dr["-------"]); } comm.Clone(); comm.Dispose(); } num = Convert.ToInt32(num.ToString().Substring(0, 1)); return num; } </code></pre>
3
3,973
Rendering Backbone.js view with template variable undefined in the model
<p>Is it possible from a backbone.js view to render an underscore.js template with a variable that is not defined in the related Backbone.js model?</p> <p>take the <code>can't find variable: username</code> error.</p> <p>the template to be rendered:</p> <pre><code>&lt;div class="content" id="content"&gt; &lt;div id="form"&gt; &lt;form action=""&gt; &lt;input id="username" type="text" placeholder="Username" name="username" value= &lt;%=username%&gt; &gt; &lt;input id="password" type="password" placeholder="Password" name="password" &gt; &lt;ul class="table-view"&gt; &lt;li class="table-view-cell"&gt; Remember me &lt;div class="toggle active"&gt; &lt;div class="toggle-handle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;button id="logbtn" class="btn btn-primary btn-block"&gt;Login&lt;/button&gt; &lt;/form&gt; &lt;button id="renregbtn" class="btn btn-positive btn-block"&gt;Register&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>rendering line from the view:</p> <pre><code>this.$el.html( this.template_login( this.loginModel ) ); </code></pre> <p>line form the loginModel model file:</p> <pre><code>define([ 'underscore', 'backbone', ], function(_, Backbone) { var LoginModel = Backbone.Model.extend({ urlRoot: '/login', initialize: function(){ this.fetch(); }, }); return LoginModel; }); </code></pre> <p>I set the model manually. But still take the can't find variable error as in the first render case.</p> <p>same model above:</p> <pre><code>define([ 'underscore', 'backbone', ], function(_, Backbone) { var LoginModel = Backbone.Model.extend({ urlRoot: '/login', defaults: { username: "abc", }, initialize: function(){ this.fetch(); }, }); return LoginModel; }); </code></pre> <p>Both cases result in:</p> <pre><code>ReferenceError: Can't find variable: username </code></pre> <p>Only if I give an hardcoded model json into the template_login it works.</p> <pre><code>this.$el.html( this.template_login( {username: "Joe"} ) ); </code></pre>
3
1,100
cannot insert any string into mysql
<p>I have a problem with inserting strings into mysql. I can insert numbers but cant strings. Can anybody look at this? Thanks for your help.</p> <p>My table(episodes) looks like</p> <pre><code>id int(11) notnull serie int(11) notnull name varchar(255) notnull comment varchar(255) notnull embed varchar(255) notnull </code></pre> <p>And here is the PHP code:</p> <pre><code>&lt;?php require_once "config.php"; $connect = mysql_connect( "$db_host", "$db_user", "$db_pw") or die(mysql_error()); mysql_select_db("$db_name") or die( mysql_error() ); if(isset($_POST['pridatdiel'])) { mysql_query("INSERT INTO `episodes` (`id`, `serie`, `name`, `comment`, `embed`) VALUES ('', '$cisloserie', '$menodielu', '$popis', '$embed')"); header("refresh: 0;"); } function stripinput($text) { if (!is_array($text)) { $text = stripslash(trim($text)); $text = preg_replace("/(&amp;amp;)+(?=\#([0-9]{2,3});)/i", "&amp;", $text); $search = array("&amp;", "\"", "'", "\\", '\"', "\'", "&lt;", "&gt;", "&amp;nbsp;"); $replace = array("&amp;amp;", "&amp;quot;", "&amp;#39;", "&amp;#92;", "&amp;quot;", "&amp;#39;", "&amp;lt;", "&amp;gt;", " "); $text = str_replace($search, $replace, $text); } else { foreach ($text as $key =&gt; $value) { $text[$key] = stripinput($value); } } return $text; } if(isset($_POST['menodielu'])) {$menodielu = stripinput($_POST['menodielu']);} if(isset($_POST['cisloserie'])) {$cisloserie = stripinput($_POST['cisloserie']);} if(isset($_POST['popis'])) {$popis = stripinput($_POST['popis']);} if(isset($_POST['embed'])) {$embed = stripinput($_POST['embed']);} echo ' &lt;form method="post"&gt; meno dielu&lt;input type="text" name="menodielu"&gt; &lt;select name="cisloserie"&gt;'; $data = mysql_query("SELECT * FROM `series`") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { echo "&lt;option value=".$info['serie_id']."&gt;".$info['serie_id']."&lt;/option&gt;"; } echo ' &lt;/select&gt; popis&lt;input type="text" name="popis"&gt; embed&lt;input type="text" name="embed"&gt; &lt;input type="submit" value="pridať diel" name="pridatdiel"&gt; &lt;/form&gt; '; ?&gt; </code></pre>
3
1,110
Video doesn't play first time on Android
<p>I have an Augmented Reality scene which downloads an AssetBundle containing a video. The video is set to Play on Awake so that it plays as soon as it is downloaded and instantiated. On iOS the all works perfectly, however on Android, the AssetBundle downloads and instantiates but only shows the white plane and doesn't play the video. However, if you exit the scene or the App and try again, it works the second time as it's supposed to.</p> <p>Unity version: 2020.1.11f1 Device: Samsung S8 &amp; Samsung Tab S5 e</p> <p>This is the script I'm using to download and cache the AssetBundle:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using UnityEngine.Video; namespace UnityLibrary{ public class VideoLoader : MonoBehaviour { public string assetBundleURL; public void Awake(){ Caching.compressionEnabled = false; } public void Start() { StartCoroutine(DownloadAndCache(assetBundleURL)); } IEnumerator DownloadAndCache(string bundleURL, string assetName = ""){ while(!Caching.ready){ yield return null; } UnityWebRequest www = UnityWebRequest.Get(bundleURL + ".manifest?r=" + (Random.value * 9999999)); Debug.Log("Loading manifest: " + bundleURL + ".manifest"); yield return www.SendWebRequest(); while(!www.isDone) Debug.Log("BUNDLE IS DOWNLOADING"); if(www.isDone) Debug.Log("BUNDLE DOWNLOAD COMPLETE"); if(www.isNetworkError == true){ Debug.Log("www.error: " + www.error); www.Dispose(); www=null; yield break; } Hash128 hashString = (default(Hash128)); if(www.downloadHandler.text.Contains("ManifestFileVersion")){ var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray()) [5]; hashString = Hash128.Parse(hashRow.Split(':')[1].Trim()); if(hashString.isValid == true){ if(Caching.IsVersionCached(bundleURL, hashString) == true){ Debug.Log("Bundle with this hash is already cached!"); } else{ Debug.Log("No cached version found for this hash..."); } } else{ Debug.Log("Invalid hash: " + hashString); yield break; } } else{ Debug.LogError("Manifest doesnt contain string 'Manifest version': " + bundleURL + ".manifest"); yield break; } www = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL + "?r=" + (Random.value * 9999999), hashString, 0); yield return www.SendWebRequest(); if(www.error !=null){ Debug.LogError("www.error: " + www.error); www.Dispose(); www = null; yield break; } AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle; GameObject bundlePrefab = null; if(assetName == ""){ bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]); }else{ bundlePrefab = (GameObject)bundle.LoadAsset(assetName); } if(bundlePrefab !=null){ var tiles = Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity); tiles.transform.SetParent(gameObject.transform, false); Debug.Log("VIDEO GO!"); } www.Dispose(); www = null; Resources.UnloadUnusedAssets(); bundle.Unload(false); bundle = null; } } }</code></pre> </div> </div> </p>
3
1,372
multiple model not load in same controller in codeigniter
<p>i want to run multiple model in same controller but its show below error </p> <blockquote> <p>Severity: Notice</p> <p>Message: Undefined property: Home::$Company</p> <p>Filename: controllers/Home.php</p> <p>Line Number: 23</p> </blockquote> <pre><code>&lt;?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home extends CI_Controller { public function __construct() { parent::__construct (); $this-&gt;load-&gt;model('Product'); $this-&gt;load-&gt;model('Company'); //$this-&gt;load-&gt;model(array('Product','Company')); } public function index() { $Product = $this-&gt;Product-&gt;getProduct(10); if($Product) { $data['Product'] = $Product; } $Company = $this-&gt;Company-&gt;getCompany(10); if($Company) { $data['Company'] = $Company; } $this-&gt;load-&gt;view('Home',$data); } } </code></pre> <p>//Company Model</p> <p> <pre><code>class Company extends CI_Controller { function getCompany($limit=null,$start=0) { $data = array(); $query = $this-&gt;db-&gt;query('SELECT * FROM user as u,category as c,sub_category as sc WHERE c.Category_Id=u._Category_Id and u._Sub_Category_Id=sc.Sub_Category_Id ORDER by rand() limit '.$start.','.$limit); $res = $query-&gt;result(); return $res; } function getOneCompany($id) { $this-&gt;db-&gt;where('User_Id',$id); $query = $this-&gt;db-&gt;get('user'); $res = $query-&gt;result(); return $res; } } </code></pre> <p>// Product model <pre><code>class Product extends CI_Controller { function getProduct($limit=null,$start=0) { $data = array(); $query = $this-&gt;db-&gt;query('SELECT * FROM product as p,user as u,category as c,sub_category as sc WHERE p._User_Id = u.User_Id and c.Category_Id=u._Category_Id and u._Sub_Category_Id=sc.Sub_Category_Id ORDER by rand() limit '.$start.','.$limit); $res = $query-&gt;result(); return $res; } function getOneProduct($id) { $this-&gt;db-&gt;where('User_Id',$id); $query = $this-&gt;db-&gt;get('user'); $res = $query-&gt;result(); return $res; } } </code></pre>
3
1,086
Run plsql procedure from concurrent on Oracle
<p>I am trying to create a stored procedure that send parameter input into table. When I tried to compile my store procedure from SQL Developer it was running well,but i want to run this procedure from Concurrent in Oracle EBS 12. </p> <p>However, this is the Error Message :</p> <blockquote> <p>Cause: FDPSTP failed due to ORA-06550: line 1, column 7: PLS-00201: identifier 'RUN_THIS_THING' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored .</p> </blockquote> <p>And this is my code : </p> <pre><code>create or replace PROCEDURE RUN_THIS_THING (errbuf out varchar2,retcode out varchar2, P_RUN_FROM IN NUMBER, P_RUN_TO IN NUMBER, P_USER IN VARCHAR2) IS BEGIN declare cursor c_header is select aia.party_id, aia.INVOICE_ID, aia.INVOICE_NUM, AIA.VENDOR_ID, AIA.INVOICE_CURRENCY_CODE, aia.INVOICE_AMOUNT, aia.DESCRIPTION, aia.INVOICE_DATE, aia.INVOICE_RECEIVED_DATE, AIA.GL_DATE, AIA.DOC_SEQUENCE_VALUE from AP.ap_invoices_all aiA where AIA.DOC_SEQUENCE_VALUE BETWEEN P_RUN_FROM AND P_RUN_TO; h_rec c_header%rowtype; begin open c_header; loop fetch c_header into h_rec; exit when c_header%notfound; BEGIN insert into RUN_TEMP ( INVOICE_ID , LAST_UPDATE_DATE , LAST_UPDATED_BY , VENDOR_ID , PARTY_ID , INVOICE_NUM , TTDV_NUM , CURRENCY , INVOICE_AMOUNT , INVOICE_DATE , INVOICE_RECEIVED_DATE , GL_DATE , DESCRIPTION ) values ( h_rec.INVOICE_ID, sysdate, p_user, h_rec.VENDOR_ID, h_rec.party_id, h_rec.INVOICE_NUM, h_rec.DOC_SEQUENCE_VALUE, h_rec.INVOICE_CURRENCY_CODE, h_rec.INVOICE_AMOUNT, h_rec.INVOICE_DATE, h_rec.INVOICE_RECEIVED_DATE, h_rec.GL_DATE , h_rec.DESCRIPTION ); END; end loop; close c_header; commit; end; END; </code></pre> <p>It fails look like the procedure does not compile and I have already tried to grant my user execute rights to that package. It did not work. What else can I look at? What else could be causing this? Thanks!</p>
3
1,325
Reuseable button in vuejs
<p>BaseButton.vue is reuseable component event listeners This can be passed down to an inner component via v-on=&quot;$listeners&quot; that emits function value in the parent is trigger</p> <pre><code> &lt;div&gt; &lt;button v-bind=&quot;$attrs&quot; v-on=&quot;$listeners&quot;&gt; &lt;slot name=&quot;iconPrepend&quot;&gt;&lt;/slot&gt; {{ buttonLabel }} &lt;slot name=&quot;iconAppend&quot;&gt;&lt;/slot&gt; &lt;/button&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { props: { loading: { type: Boolean, // default: &quot;&quot;, }, variant: { type: String, default: &quot;&quot;, }, iconPrepend: { type: String, default: &quot;&quot;, }, disabled: { type: Boolean, // default:'' }, buttonLabel: { type: String, default: &quot;&quot;, }, }, methods: { // onClick() { // this.$emit(&quot;click&quot;); // }, }, }; &lt;/script&gt; </code></pre> <p>This is the newAccountholder.vue file i've imported BaseButton.vue in the newAccountholder.vue file. The BaseButton I've used as save button and next button as when I've clicked on next button is not calling next button but the save button is calling</p> <pre><code> &lt;v-form style=&quot;width: 75%&quot; @submit.prevent=&quot;submit&quot; autocomplete=&quot;off&quot;&gt; &lt;v-window v-model=&quot;steps&quot;&gt; &lt;v-window-item :value=&quot;0&quot;&gt; &lt;v-card-text&gt; &lt;div class=&quot;d-flex align-center mb-4 mt-4&quot;&gt; &lt;v-avatar size=&quot;35&quot; color=&quot;#91CA59&quot; class=&quot;&quot;&gt; &lt;v-icon color=&quot;#ffffff&quot;&gt;mdi-human-greeting&lt;/v-icon&gt; &lt;/v-avatar&gt; &lt;span class=&quot;heading-md px-6&quot;&gt; Personal Informations &lt;/span&gt; &lt;/div&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;First Name&quot; ref=&quot;firstNameFocus&quot; required v-model=&quot;dataFromInputs.first_name&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Last Name&quot; v-model=&quot;dataFromInputs.last_name&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;CNIC&quot; v-model=&quot;dataFromInputs.cnic&quot; type=&quot;number&quot; required &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Phone Number&quot; v-model=&quot;dataFromInputs.contact&quot; type=&quot;number&quot; required &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-autocomplete :items=&quot;genderOptions&quot; v-model=&quot;dataFromInputs.gender&quot; label=&quot;Gender&quot; required &gt;&lt;/v-autocomplete&gt; &lt;/v-col&gt; &lt;v-col sm=&quot;12&quot; md=&quot;4&quot;&gt; &lt;v-file-input v-model=&quot;dataFromInputs.profile&quot; chips label=&quot;Photo&quot; append-icon=&quot;mdi-image&quot; @change=&quot;selectImage&quot; accept=&quot;image/png, image/jpeg, image/bmp&quot; &gt;&lt;/v-file-input&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;v-row&gt; &lt;v-col md=&quot;6&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Current Address&quot; v-model=&quot;dataFromInputs.current_address&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;6&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Permanent Address&quot; v-model=&quot;dataFromInputs.permanent_address&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;/v-card-text&gt; &lt;/v-window-item&gt; &lt;v-window-item :value=&quot;1&quot;&gt; &lt;v-card-text class=&quot;algin-center&quot;&gt; &lt;div class=&quot;d-flex align-center mb-8 mt-4&quot;&gt; &lt;v-avatar size=&quot;35&quot; color=&quot;#91CA59&quot; class=&quot;&quot;&gt; &lt;v-icon color=&quot;#ffffff&quot;&gt;mdi-account-circle &lt;/v-icon&gt; &lt;/v-avatar&gt; &lt;span class=&quot;algin-start heading-md px-6&quot; &gt;Account Information&lt;/span &gt; &lt;/div&gt; &lt;!-- &lt;div class=&quot;d-flex justify-end &quot;&gt; --&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;A/C No&quot; v-model=&quot;dataFromInputs.acc_no_id&quot; type=&quot;number&quot; required :disabled=&quot;editAccountDetails ? true : false&quot; &gt;&lt;/v-text-field&gt; &lt;!-- &lt;/validation-provider&gt; --&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;A/C Balance&quot; v-model=&quot;dataFromInputs.acc_balance&quot; type=&quot;number&quot; required :disabled=&quot;editAccountDetails ? true : false&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-menu ref=&quot;menu2&quot; v-model=&quot;menu2&quot; :close-on-content-click=&quot;false&quot; :return-value.sync=&quot;date2&quot; transition=&quot;scale-transition&quot; offset-y min-width=&quot;auto&quot; &gt; &lt;template v-slot:activator=&quot;{ on, attrs }&quot;&gt; &lt;v-text-field v-model=&quot;dataFromInputs.opening_date&quot; label=&quot;A/C Opening Date&quot; prepend-icon=&quot;mdi-calendar&quot; v-bind=&quot;attrs&quot; v-on=&quot;on&quot; required :readonly=&quot;disableAndReadonly&quot; &gt;&lt;/v-text-field&gt; &lt;/template&gt; &lt;v-date-picker v-model=&quot;dataFromInputs.opening_date&quot; :max=&quot;new Date().toISOString().substr(0, 10)&quot; @input=&quot;menu2 = false&quot; &gt;&lt;/v-date-picker&gt; &lt;/v-menu&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;/v-card-text&gt; &lt;/v-window-item&gt; &lt;v-window-item :value=&quot;2&quot;&gt; &lt;v-card-text&gt; &lt;div class=&quot;d-flex align-center mb-8 mt-4&quot;&gt; &lt;v-avatar size=&quot;35&quot; color=&quot;#91CA59&quot;&gt; &lt;v-icon color=&quot;#ffffff&quot;&gt;mdi-check-circle-outline&lt;/v-icon&gt; &lt;/v-avatar&gt; &lt;span class=&quot;algin-start heading-md px-3&quot;&gt; Confirm Informations &lt;/span&gt; &lt;/div&gt; &lt;v-row&gt; &lt;v-col sm=&quot;12&quot; md=&quot;6&quot;&gt; &lt;v-file-input v-model=&quot;dataFromInputs.signature&quot; chips label=&quot;Signature&quot; accept=&quot;image/*&quot; append-icon=&quot;mdi-signature-image&quot; @change=&quot;selectSignatureFile&quot; &gt;&lt;/v-file-input&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;/v-card-text&gt; &lt;/v-window-item&gt; &lt;v-window-item :value=&quot;3&quot;&gt; &lt;v-card-text&gt; &lt;div class=&quot;d-flex align-center mb-8 mt-4&quot;&gt; &lt;v-avatar size=&quot;35&quot; color=&quot;#91CA59&quot;&gt; &lt;v-icon color=&quot;#ffffff&quot;&gt;mdi-check-circle-outline&lt;/v-icon&gt; &lt;/v-avatar&gt; &lt;!-- &lt;v-stepper-content step=&quot;5&quot; color=&quot;light-green&quot;&gt; --&gt; &lt;span class=&quot;heading-md px-4&quot;&gt; Kin (1) Informations &lt;/span&gt; &lt;/div&gt; &lt;!-- &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-autocomplete :items=&quot;returnAccountHolders&quot; item-text=&quot;first_name&quot; item-value=&quot;id&quot; v-model=&quot;kinInformationObj1.acc_no_id&quot; label=&quot;A/C No&quot; :loading=&quot;slctLoadingOnAcHolders&quot; &gt;&lt;/v-autocomplete&gt; &lt;/v-col&gt; &lt;/v-row&gt; --&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;First Name&quot; v-model=&quot;kinInformationObj1.first_name&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Last Name&quot; v-model=&quot;kinInformationObj1.last_name&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;CNIC&quot; v-model=&quot;kinInformationObj1.cnic&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Phone Number&quot; v-model=&quot;kinInformationObj1.contact&quot; type=&quot;number&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot;&gt; &lt;v-autocomplete :items=&quot;genderOptions&quot; label=&quot;Gender&quot; v-model=&quot;kinInformationObj1.gender&quot; &gt;&lt;/v-autocomplete&gt; &lt;/v-col&gt; &lt;v-col sm=&quot;12&quot; md=&quot;4&quot;&gt; &lt;v-file-input v-model=&quot;kinInformationObj1.cnic_img&quot; chips label=&quot;CNIC PHOTO&quot; append-icon=&quot;mdi-image&quot; @change=&quot;selectImage&quot; accept=&quot;image/png, image/jpeg, image/bmp&quot; &gt;&lt;/v-file-input&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;v-row&gt; &lt;v-col md=&quot;6&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;!-- &lt;validation-provider v-slot=&quot;{ errors }&quot; name=&quot;Gender&quot; rules=&quot;required&quot; &gt; --&gt; &lt;v-text-field label=&quot;Current Address&quot; v-model=&quot;kinInformationObj1.current_address&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;6&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Permanent Address&quot; v-model=&quot;kinInformationObj1.permanent_address&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;/v-card-text&gt; &lt;v-card-text&gt; &lt;div class=&quot;d-flex align-center mb-8 mt-4&quot;&gt; &lt;v-avatar size=&quot;35&quot; color=&quot;#91CA59&quot;&gt; &lt;v-icon color=&quot;#ffffff&quot;&gt;mdi-check-circle-outline&lt;/v-icon&gt; &lt;/v-avatar&gt; &lt;!-- &lt;v-stepper-content step=&quot;5&quot; color=&quot;light-green&quot;&gt; --&gt; &lt;span class=&quot;heading-md px-4&quot;&gt; Kin (2) Informations &lt;/span&gt; &lt;/div&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;First Name&quot; v-model=&quot;kinInformationObj2.first_name&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Last Name&quot; v-model=&quot;kinInformationObj2.last_name&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;CNIC&quot; v-model=&quot;kinInformationObj2.cnic&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;v-row&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Phone Number&quot; v-model=&quot;kinInformationObj2.contact&quot; type=&quot;number&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;4&quot; sm=&quot;12&quot;&gt; &lt;v-autocomplete :items=&quot;genderOptions&quot; label=&quot;Gender&quot; v-model=&quot;kinInformationObj2.gender&quot; &gt;&lt;/v-autocomplete&gt; &lt;/v-col&gt; &lt;v-col sm=&quot;12&quot; md=&quot;4&quot;&gt; &lt;v-file-input v-model=&quot;kinInformationObj2.cnic_img&quot; chips label=&quot;CNIC PHOTO&quot; append-icon=&quot;mdi-image&quot; @change=&quot;selectImage&quot; accept=&quot;image/png, image/jpeg, image/bmp&quot; &gt;&lt;/v-file-input&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;v-row&gt; &lt;v-col md=&quot;6&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;!-- &lt;validation-provider v-slot=&quot;{ errors }&quot; name=&quot;Gender&quot; rules=&quot;required&quot; &gt; --&gt; &lt;v-text-field label=&quot;Current Address&quot; v-model=&quot;kinInformationObj2.current_address&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;v-col md=&quot;6&quot; sm=&quot;12&quot; xs=&quot;12&quot;&gt; &lt;v-text-field label=&quot;Permanent Address&quot; v-model=&quot;kinInformationObj2.permanent_address&quot; &gt;&lt;/v-text-field&gt; &lt;/v-col&gt; &lt;/v-row&gt; &lt;/v-card-text&gt; &lt;/v-window-item&gt; &lt;/v-window&gt; &lt;!-- &lt;v-divider&gt;&lt;/v-divider&gt; --&gt; &lt;v-card-actions :class=&quot; steps === 2 ? 'd-flex justify-md-center pl-16' : 'd-flex justify-end' &quot; &gt; &lt;v-btn class=&quot;px-2&quot; :disabled=&quot;steps === 0&quot; text @click=&quot;steps--&quot;&gt; Back &lt;/v-btn&gt; &lt;div style=&quot;width: 82px&quot;&gt; &lt;base-button v-if=&quot;steps !== 3&quot; buttonLabel=&quot;Next&quot; @click=&quot;nextStep&quot;/&gt; &lt;/div&gt; &lt;div style=&quot;width: 82px&quot;&gt; &lt;base-button v-if=&quot;steps === 3&quot; buttonType=&quot;submit&quot; buttonLabel=&quot;save&quot;/&gt; &lt;/div&gt; &lt;/v-card-actions&gt; &lt;/v-form&gt; &lt;/template&gt;``` </code></pre>
3
13,090
How to Join Multiple Reference Tables Based on a String
<p>Suppose that I am given three sheets to pull data from and I need to get repeating data back from those sheets. Essentially for each user in a user group, find all the permissions associated from another group and display given permissions. My sheets are setup as such. <strong>(Assume top left is A1)</strong></p> <h3>First Table (User Sheet)</h3> <pre><code>Username Group GPARR11 ACC-ADMIN LPARR11 PRT-MGR CSMITH VP-SALES </code></pre> <h3>Second Table (Permissions Sheet)</h3> <pre><code>Group Ref Table Rows Switches ACC-ADMIN 500 YNYNNNYN ACC-ADMIN 502 YNYYY ACC-ADMIN 503 NYNYYN PRT-MGR 500 NNNYNNNYN PRT-MGR 633 YNYNNNYNNY VP-Sales 500 NYNYNNNYNY VP-Sales 999 NYNYNYNYNYNNYNNYNYNN </code></pre> <h3>Final Table (Reference Sheet)</h3> <p><em>This sheet get's it's reference from the third column in the second sheet. So if a character is <code>Y</code> then it has that permission enabled <code>N</code> then it doesn't.</em></p> <pre><code>Ref Table Switch Row Sequenc # Permission 500 1 Access G&amp;B 500 2 Access Call 500 3 Access A/R 633 1 Modify G&amp;B 633 2 Modify Call 633 3 Modify Memos 999 1 Delete G&amp;B </code></pre> <h3>What I'm expecting to see</h3> <pre><code>Username Group Permission Enabled GPARR11 ACC-ADMIN Access G&amp;B TRUE Access Call FALSE Access A/R TRUE LPARR11 PRT-MGR Access G&amp;B FALSE Access Call FALSE Access A/R FALSE Modify G&amp;B TRUE Modify Call FALSE Modify Memos TRUE CSMITH38 VP-SALES Access G&amp;B FALSE Access Call TRUE Access A/R FALSE </code></pre> <h3>ADDT'L Info</h3> <p>Essentially the way that the information is supposed to flow to get each of the expected outputs is as follows. For each Username match their group name with the group name in the second sheet. From there the <code>Ref Table Rows</code> would tell you which rows are allowed to be returned, mapping the <code>Switches</code> <code>(YNYNYN)</code> with the respective Ref Table Rows from the reference sheet. The sequence number is there to determine which permission matches with the respective Switch. 1 is first char, 2 the second char, etc.. and determines whether it returns true or false on the output.</p> <p>Looking at <code>GPARR11</code> the <code>ACC-ADMIN</code> matches with <code>ACC-ADMIN</code> in the permissions table. There are three <code>Ref Table Rows</code> associated with <code>ACC-ADMIN</code>, <code>500</code>, <code>502</code>, <code>503</code>. Each row has <code>Switches</code> that correspond to the <code>Reference Table</code>. So it will pull ALL permissions from <code>500</code>, <code>502</code>, <code>503</code>, and then check the <code>switch</code> to determine if each permission from the <code>ref rows</code> is <code>TRUE</code> or <code>FALSE</code> </p> <p>Is there a way that this can be done with a formula?</p>
3
1,516
craft cms command line update to version 3.5.12.1 or greater fails
<p>I am running the following command to update craft cms:</p> <pre><code>php craft update craft </code></pre> <p>However upgrading to version 3.5.12.1 or greater fails with the following error:</p> <pre><code>Performing update with Composer ... done Applying new migrations ... error: The command &quot;'/var/www/craft' 'migrate/all' '--no-content'&quot; failed. Exit Code: 1(General error) Working directory: /var/www Output: ================ Error Output: ================ Error: array_merge(): Expected parameter 2 to be an array, null given Output: </code></pre> <p>The current version of craft that I am running is 3.3.19, and it's running in a docker, using the following composer.json:</p> <pre><code>. . . &quot;require&quot;: { &quot;aelvan/craft-cp-element-count&quot;: &quot;^v1.0.1&quot;, &quot;aelvan/imager&quot;: &quot;v2.3.0&quot;, &quot;aelvan/inlin&quot;: &quot;^2.1&quot;, &quot;aelvan/preparse-field&quot;: &quot;v1.1.0&quot;, &quot;am-impact/amcommand&quot;: &quot;^3.1.4&quot;, &quot;angellco/portal&quot;: &quot;1.1.3&quot;, &quot;angellco/spoon&quot;: &quot;3.3.7&quot;, &quot;charliedev/element-map&quot;: &quot;^1.2&quot;, &quot;charliedev/section-field&quot;: &quot;^1.1.0&quot;, &quot;craftcms/aws-s3&quot;: &quot;1.2.5&quot;, &quot;craftcms/cms&quot;: &quot;3.3.19&quot;, &quot;craftcms/feed-me&quot;: &quot;4.1.2&quot;, &quot;craftcms/redactor&quot;: &quot;2.4.0&quot;, &quot;doublesecretagency/craft-inventory&quot;: &quot;2.0.3&quot;, &quot;doublesecretagency/craft-siteswitcher&quot;: &quot;2.1.0&quot;, &quot;ether/logs&quot;: &quot;^3.0.3&quot;, &quot;ether/sidebarentrytypes&quot;: &quot;^1.0&quot;, &quot;fruitstudios/linkit&quot;: &quot;1.1.11&quot;, &quot;hashtagerrors/user-initials-photo&quot;: &quot;1.1.1&quot;, &quot;lukeyouell/craft-queue-manager&quot;: &quot;^1.1.0&quot;, &quot;marionnewlevant/snitch&quot;: &quot;3.0.0&quot;, &quot;misterbk/mix&quot;: &quot;^1.5&quot;, &quot;mmikkel/child-me&quot;: &quot;1.0.6&quot;, &quot;mmikkel/cp-field-inspect&quot;: &quot;1.0.7&quot;, &quot;mmikkel/incognito-field&quot;: &quot;1.1.1.1&quot;, &quot;monachilada/craft-matrixtoolbar&quot;: &quot;^1.0.6&quot;, &quot;nfourtythree/entriessubset&quot;: &quot;1.2.2&quot;, &quot;nystudio107/craft-cookies&quot;: &quot;^1.1&quot;, &quot;nystudio107/craft-emptycoalesce&quot;: &quot;1.0.6&quot;, &quot;nystudio107/craft-imageoptimize&quot;: &quot;1.6.4&quot;, &quot;nystudio107/craft-minify&quot;: &quot;^1.2.9&quot;, &quot;nystudio107/craft-retour&quot;: &quot;3.1.27&quot;, &quot;nystudio107/craft-scripts&quot;: &quot;^1.2.4&quot;, &quot;nystudio107/craft-seomatic&quot;: &quot;3.2.32&quot;, &quot;nystudio107/craft-typogrify&quot;: &quot;1.1.18&quot;, &quot;nystudio107/craft-webperf&quot;: &quot;1.0.14&quot;, &quot;ostark/craft-async-queue&quot;: &quot;2.0.0&quot;, &quot;page-8/craft-manytomany&quot;: &quot;1.0.2.2&quot;, &quot;putyourlightson/craft-blitz&quot;: &quot;2.3.4&quot;, &quot;rias/craft-position-fieldtype&quot;: &quot;^1.0.13&quot;, &quot;rias/craft-width-fieldtype&quot;: &quot;^1.0&quot;, &quot;spicyweb/craft-embedded-assets&quot;: &quot;2.1.1.1&quot;, &quot;spicyweb/craft-fieldlabels&quot;: &quot;1.1.7&quot;, &quot;spicyweb/craft-neo&quot;: &quot;2.5.7&quot;, &quot;superbig/craft-entry-instructions&quot;: &quot;1.0.6&quot;, &quot;topshelfcraft/environment-label&quot;: &quot;^3.1.5&quot;, &quot;verbb/cp-nav&quot;: &quot;^2.0.9&quot;, &quot;verbb/default-dashboard&quot;: &quot;^1.0&quot;, &quot;verbb/expanded-singles&quot;: &quot;^1.0.4&quot;, &quot;verbb/field-manager&quot;: &quot;2.1.0&quot;, &quot;verbb/icon-picker&quot;: &quot;1.0.10&quot;, &quot;verbb/image-resizer&quot;: &quot;2.0.6&quot;, &quot;verbb/super-table&quot;: &quot;2.3.0&quot;, &quot;vlucas/phpdotenv&quot;: &quot;^2.4.0&quot;, &quot;wbrowar/craft-communicator&quot;: &quot;^1.0&quot;, &quot;wbrowar/guide&quot;: &quot;2.1.2&quot;, &quot;yiisoft/yii2-redis&quot;: &quot;^2.0&quot; }, &quot;repositories&quot;: { &quot;element-map&quot;: { &quot;type&quot;: &quot;path&quot;, &quot;url&quot;: &quot;./plugins/element-map&quot; } }, &quot;autoload&quot;: { &quot;psr-4&quot;: { &quot;modules\\utilitiesmodule\\&quot;: &quot;modules/utilitiesmodule/src/&quot;, &quot;putyourlightson\\blitz\\drivers\\storage\\&quot;: &quot;plugins/blitz-override&quot; } }, &quot;config&quot;: { &quot;optimize-autoloader&quot;: true, &quot;config&quot;: { &quot;process-timeout&quot;: 0 }, &quot;platform&quot;: { &quot;php&quot;: &quot;7.2.5&quot; }, &quot;sort-packages&quot;: true }, &quot;scripts&quot;: { &quot;post-update-cmd&quot;: [ &quot;./craft migrate/all&quot;, &quot;./craft clear-caches/all&quot; ], &quot;post-install-cmd&quot;: [ &quot;./craft migrate/all&quot;, &quot;./craft clear-caches/all&quot; ] } } </code></pre> <p>I have tried disabling plugins but that seems to make no difference. Also, I am not sure where the &quot;'/var/www/craft' 'migrate/all' '--no-content'&quot; command is even coming from since that seems to be slightly different command than what is in the composer.json.</p> <p>When I try to run just the migration:</p> <pre><code>./craft migrate/all </code></pre> <p>I get the following stack trace:</p> <pre><code>PHP Warning 'yii\base\ErrorException' with message 'array_merge(): Expected parameter 2 to be an array, null given' in /var/www/vendor/yiisoft/yii2/web/UrlManager.php:222 Stack trace: #0 [internal function]: yii\base\ErrorHandler-&gt;handleError() #1 /var/www/vendor/yiisoft/yii2/web/UrlManager.php(222): array_merge() #2 /var/www/vendor/yiisoft/yii2-debug/src/Module.php(290): yii\web\UrlManager-&gt;addRules() #3 /var/www/vendor/yiisoft/yii2/base/Application.php(333): yii\debug\Module-&gt;bootstrap() #4 /var/www/vendor/craftcms/cms/src/console/Application.php(61): yii\base\Application-&gt;bootstrap() #5 /var/www/vendor/yiisoft/yii2/base/Application.php(279): craft\console\Application-&gt;bootstrap() #6 /var/www/vendor/yiisoft/yii2/console/Application.php(125): yii\base\Application-&gt;init() #7 /var/www/vendor/craftcms/cms/src/console/Application.php(47): yii\console\Application-&gt;init() #8 /var/www/vendor/yiisoft/yii2/base/BaseObject.php(109): craft\console\Application-&gt;init() #9 /var/www/vendor/yiisoft/yii2/base/Application.php(212): yii\base\BaseObject-&gt;__construct() #10 /var/www/vendor/yiisoft/yii2/console/Application.php(90): yii\base\Application-&gt;__construct() #11 [internal function]: yii\console\Application-&gt;__construct() #12 /var/www/vendor/yiisoft/yii2/di/Container.php(420): ReflectionClass-&gt;newInstanceArgs() #13 /var/www/vendor/yiisoft/yii2/di/Container.php(171): yii\di\Container-&gt;build() #14 /var/www/vendor/yiisoft/yii2/BaseYii.php(365): yii\di\Container-&gt;get() #15 /var/www/vendor/craftcms/cms/bootstrap/bootstrap.php(246): yii\BaseYii::createObject() #16 /var/www/vendor/craftcms/cms/bootstrap/console.php(51): require('/var/www/vendor...') #17 /var/www/craft(21): require('/var/www/vendor...') #18 {main} </code></pre> <p>It appears to be a bug in craft related to the UrlManager code, but if this is the case, I don't know why others have not seemed to experience it (I couldn't find anything about it in my searches)? Does anyone have any suggestions as to what could be wrong?</p>
3
3,680
SemanticModel GetSymbolInfo().Symbol is Null in Constructed Code but not Parsed Code
<p>Given the following code</p> <pre><code>var forText = "int i;for(i=0;i&lt;3;i++){}"; </code></pre> <p>I wish to grab a reference to the <code>i</code> in <code>i=0</code>, and then request its symbol info to see where it was declared, if anywhere! To do this using the string above, you would do the following</p> <pre><code>var forText = "int i;for(i=0;i&lt;3;i++){}"; var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var options = CSharpParseOptions.Default.WithKind(SourceCodeKind.Script); var goodTree = CSharpSyntaxTree.ParseText(forText, options); var goodCompilation = CSharpCompilation.CreateScriptCompilation("GoodCompilation", syntaxTree: goodTree, references: new[] { mscorlib }); var goodModel = goodCompilation.GetSemanticModel(goodTree); var goodLeft = goodTree.GetRoot().DescendantNodes().OfType&lt;AssignmentExpressionSyntax&gt;().First().Left; var goodSymbol = goodModel.GetSymbolInfo(goodLeft).Symbol; </code></pre> <p>This works fine as expected, and <code>goodSymbol</code> is successfully assigned a value. However, in my program what I need to do is perform semantic analysis against an existing syntax tree. For some reason however, if the tree above is manually created via <code>SyntaxFactory</code> nodes, <code>GetSymbolInfo().Symbol</code> returns <code>null</code>!</p> <pre><code>//using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; var manualTree = CompilationUnit() .WithMembers( List(new MemberDeclarationSyntax[] { GlobalStatement( LocalDeclarationStatement( VariableDeclaration( PredefinedType(Token(SyntaxKind.IntKeyword)), SingletonSeparatedList( VariableDeclarator("i") ) ) ).NormalizeWhitespace() ), GlobalStatement( ForStatement( null, SingletonSeparatedList&lt;ExpressionSyntax&gt;( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName("i"), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)) ) ), BinaryExpression( SyntaxKind.LessThanExpression, IdentifierName("i"), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(3)) ), SingletonSeparatedList&lt;ExpressionSyntax&gt;( PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, IdentifierName("i") ) ), Block() ) )} )); var badTree = CSharpSyntaxTree.Create(manualTree, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script)); var badCompilation = CSharpCompilation.CreateScriptCompilation("BadCompilation", syntaxTree: badTree, references: new[] { mscorlib }); var badModel = badCompilation.GetSemanticModel(badTree); var badLeft = badTree.GetRoot().DescendantNodes().OfType&lt;AssignmentExpressionSyntax&gt;().First().Left; var badSymbol = badModel.GetSymbolInfo(badLeft).Symbol; </code></pre> <p>The nodes and tokens in both trees appear to be exactly the same; there do not appear to be any nodes in the <code>goodTree</code> that are reused in multiple places (each <code>SyntaxNode</code> has a unique object reference) - there is simply something fundamentally different about the parsed tree to the constructed tree, but I have no idea what! Both trees have the exact same string representation, so there must be some kind of metadata on either the <code>SyntaxTree</code> or some of the <code>SyntaxNode</code> objects that makes this work in <em>good</em> but not <em>bad</em></p>
3
1,683
Remove Padding with SlideToogle
<p>I have some code that expands the rows. The table has padding for each td. Which is fine but the table when collapsed still shows this padding,</p> <p><a href="http://jsfiddle.net/0Lh5ozyb/55/">http://jsfiddle.net/0Lh5ozyb/55/</a></p> <p>Below is the <strong>jquery</strong></p> <pre><code>$('tr.parent') .css("cursor", "pointer") .click(function () { var $children = $(this).nextUntil( $('tr').not('[class^=child-]') ); $children.find('td &gt; div').slideToggle(); }); $('tr[class^=child-]').find('td &gt; div').hide(); </code></pre> <p>Below is the <strong>HTML</strong></p> <pre><code>&lt;table class="table"&gt; &lt;tr class="parent" id="row1"&gt; &lt;td&gt;&lt;div&gt;People&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Click to Expand&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;N/A&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="child-row1-1"&gt; &lt;td&gt;&lt;div&gt;Eve&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Jackson&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;94&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="child-row1-2"&gt; &lt;td&gt;&lt;div&gt;John&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Doe&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;80&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="parent" id="row2"&gt; &lt;td&gt;&lt;div&gt;People&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Click to Expand&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;N/A&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="child-row2-1"&gt; &lt;td&gt;&lt;div&gt;Eve&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Jackson&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;94&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="child-row2-1"&gt; &lt;td&gt;&lt;div&gt;John&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Doe&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;80&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="parent" id="row3"&gt; &lt;td&gt;&lt;div&gt;People&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Click to Expand&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;N/A&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="child-row3-1"&gt; &lt;td&gt;&lt;div&gt;Eve&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Jackson&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;94&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="child-row3-2"&gt; &lt;td&gt;&lt;div&gt;John&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;Doe&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;80&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>What is the best way to ensure that the padding is removed when the rows are collapsed.</p>
3
1,668
Apply random value to animation-duration using jQuery
<p>I have a page that generates 20 randomly sized div elements and places them in random locations within a div container. Using CSS @keyframe animations I can apply a very simple scale and color animation to each element.</p> <p>I would like to set the animation-duration CSS property to a random number for each element. I tried to do so using the jQuery.css method like so;</p> <p><code>element.css({ 'animation-duration': animationTime, 'animation-delay': animationTime });</code></p> <p>but this does not work.</p> <p>Any suggestions?</p> <p>The full code is below - example is live at <a href="http://codepen.io/CronanGogarty/pen/ZOexMN" rel="nofollow">http://codepen.io/CronanGogarty/pen/ZOexMN</a></p> <pre><code>.animationContainer { width: 100%; min-height: 400px; height: 100%; border: 1px solid #000; overflow:hidden; } .animationElement { position: absolute; background-color: yellow; animation: increase infinite; animation-direction: alternate; } @keyframes increase { 0% { border-radius: 100%; } 50% { background-color: orange; } 100% { transform: scale(2); background-color: red; } } $(function () { createRandomElements(); }); function createRandomElements() { for (var i = 0; i &lt; 20; i++) { var dimensions = Math.floor(Math.random() * (60 - 10) + 10); var width = $('.animationContainer').width(); var height = $('.animationContainer').height(); var eltop = Math.floor(Math.random() * (height - dimensions) + dimensions); var elleft = Math.floor(Math.random() * (width - dimensions) + dimensions); var animationTime = Math.floor(Math.random() * (5 - 2 + 1)) + 2; var element = $('&lt;div&gt;', { class: 'animationElement', width: dimensions, height: dimensions }); element.css({ 'animation-duration': animationTime, 'animation-delay': animationTime }); element.offset({ top: eltop, left: elleft }); $('.animationContainer').prepend(element); } } </code></pre> <p>As an additional question - can anyone explain why the <code>overflow:hidden</code> property isn't working on the .animationContainer element? I suspect it's because the .animationElement divs are being prepended to the container - if anyone has a solution I'd be very thankful.</p>
3
1,038
While sorting lower case and upper case letters are treated seperately
<p>While sorting String field</p> <ul> <li>If field is empty then it should go at the top in desc and at the bottom in asc (This is working fine)</li> <li>For Integer behaviour is fine (It considers null/undefined values and do sorting)</li> </ul> <p><strong>Only problem is with 'Case sensitivity'</strong></p> <blockquote> <ul> <li>It should treat 'rosy' And 'Rosy' as same and display them on after another</li> </ul> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function dynamicsort(property,order) { var sort_order = 1; if(order === "desc"){ sort_order = -1; } return function (a, b){ //check if one of the property is undefined if(a[property] == null){ return 1 * sort_order; } if(b[property] == null){ return -1 * sort_order; } // a should come before b in the sorted order if(a[property] &lt; b[property]){ return -1 * sort_order; // a should come after b in the sorted order }else if(a[property] &gt; b[property]){ return 1 * sort_order; // a and b are the same }else{ return 0 * sort_order; } } } let employees = [ { firstName: 'John11', age: 27, joinedDate: 'December 15, 2017' }, { firstName: 'john22', lastName: 'rosy', age: 44, joinedDate: 'December 15, 2017' }, { firstName: 'SSS', lastName: 'SSSS', age: 111, joinedDate: 'January 15, 2019' }, { firstName: 'Ana', lastName: 'Rosy', age: 25, joinedDate: 'January 15, 2019' }, { firstName: 'Zion', lastName: 'Albert', age: 30, joinedDate: 'February 15, 2011' }, { firstName: 'ben', lastName: 'Doe', joinedDate: 'December 15, 2017' }, ]; console.log("Object to be sorted"); console.log(employees); console.log("Sorting based on the lastName property") console.log(employees.sort(dynamicsort("lastName","desc"))); console.log("Sorting based on the lastName property") console.log(employees.sort(dynamicsort("lastName","asc")));</code></pre> </div> </div> </p>
3
1,088
problem including gtk/gtk.h file not found windows 10 Visual Studio Code
<p>There seems to be a problem floating around for some people using VSCode. I have confirmed the installation of GTK with the terminal window and everything went well.</p> <p>I wrote a quick program in C to read an address and print it back. It compiles and runs (<strong>without the &quot;#include &lt;gtk.gtk.h&quot;&gt;</strong>) creating the .exe file so I can confirm VScode is installed correctly.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;gtk/gtk.h&gt; int main() { int var = 20; /* variable declaration*/ int *ip; /* pointer variable declaration */ ip = &amp;var; /* store the address of var in pointer variable */ printf(&quot;Address of var variable: %x\n&quot;, &amp;var); /* address stored in the pointer variable */ printf(&quot;Address stored in ip the pointer variable: %x\n&quot;, ip); /* access the variable the *ip variable points to */ printf(&quot;Value of *ip variable: %d\n&quot;, *ip); return 0; } </code></pre> <p>When I add the #include &lt;gtk/gtk.h&gt; statement, I get the error that it cannot be found. &gt;#include errors detected. Please update your includePath.&lt;</p> <p>I used the command &quot;pkg-config --cflags --libs gtk+-3.0&quot; in a terminal to create the path in c-cpp.json file</p> <pre><code>&quot;configurations&quot;: [ { &quot;name&quot;: &quot;Win32&quot;, &quot;includePath&quot;: [ &quot;${workspaceFolder}/**&quot;, &quot;C:/msys64/mingw64/bin&quot;, &quot;C:/msys64/mingw64/include/gtk-3.0&quot;, &quot;C:/msys64/mingw64/include/pango-1.0&quot;, &quot;C:/msys64/mingw64/include&quot;, &quot;C:/msys64/mingw64/include/glib-2.0&quot;, &quot;C:/msys64/mingw64/lib/glib-2.0/include&quot;, &quot;C:/msys64/mingw64/include/harfbuzz&quot;, &quot;C:/msys64/mingw64/include/freetype2&quot;, &quot;C:/msys64/mingw64/include/libpng16&quot;, &quot;C:/msys64/mingw64/include/fribidi&quot;, &quot;C:/msys64/mingw64/include/cairo&quot;, &quot;C:/msys64/mingw64/include/lzo&quot;, &quot;C:/msys64/mingw64/include/pixman-1&quot;, &quot;C:/msys64/mingw64/include/gdk-pixbuf-2.0&quot;, &quot;C:/msys64/mingw64/include/atk-1.0&quot;, &quot;C:/msys64/mingw64/lib&quot; ], &quot;defines&quot;: [ &quot;_DEBUG&quot;, &quot;UNICODE&quot;, &quot;_UNICODE&quot; ], &quot;compilerPath&quot;: &quot;C:/msys64/mingw64/bin/gcc.exe&quot;, &quot;cStandard&quot;: &quot;gnu17&quot;, &quot;cppStandard&quot;: &quot;gnu++17&quot;, &quot;intelliSenseMode&quot;: &quot;windows-gcc-x64&quot; } ], &quot;version&quot;: 4 } </code></pre> <p>the directory gtk is in the C:/msys64/mingw64/include/gtk-3.0 directory and the gtk.h file is in the gtk directory. Intellisense even prompted for the directory and file.</p>
3
1,636
React: Build Connections Among Component
<p>I am a beginner of React JS. Messing around to achieve VanJS event listeners.</p> <p>For layout, I decide to store things like <code>a panel, a button</code> as individual component.</p> <p>Now, I have a component <code>Movie</code> and another component <code>Button</code>, how can I <b>trigger state change of Movie by Button.onclick()?</b>.</p> <p>In other words, how to <b>modify a component by the event happening on another component?</b></p> <p>Before posting, I have read:</p> <ul> <li><a href="https://www.youtube.com/watch?v=Oioo0IdoEls" rel="nofollow noreferrer">React Basics Component Lifecycle</a></li> <li><a href="https://reactjs.org/docs/hooks-state.html" rel="nofollow noreferrer">Using the State Hook</a></li> </ul> <p>but tons of method followed by really confused me.</p> <ul> <li><code>useState</code></li> <li><code>componentWillMount</code>: immediately before initial rendering</li> <li><code>componentDidMount</code>: immediately after initial rendering</li> <li><code>componentWillReceiveProps</code>: when component receives new props</li> <li><code>shouldComponentUpdate</code>: before rendering, after receiving new props or state</li> <li><code>componentWillUpdate</code>: before rendering, after receiving new props or state.</li> <li><code>componentDidUpdate</code>: after component's updates are flushed to DOM</li> <li><code>componentWillUnmount</code>: immediately before removing component from DOM</li> </ul> <p>Following is a demo, which contains a <code>Movie</code> card and a <code>Button</code>, when the button is clicked, I want <b>the background colour of the Movie card to change</b></p> <p><a href="https://codesandbox.io/s/floral-rain-70ep3" rel="nofollow noreferrer">React TypeScript Code Sandbox</a></p> <p>the code:</p> <pre class="lang-js prettyprint-override"><code>import * as React from &quot;react&quot;; import &quot;./styles.css&quot;; import styled from 'styled-components'; function CSSPropertiesToComponent(dict:React.CSSProperties){ let str = ''; for(const [key, value] of Object.entries(dict)){ let clo = ''; key.split('').forEach(lt=&gt;{ if(lt.toUpperCase() === lt){ clo += '-' + lt.toLowerCase(); }else{ clo += lt; } }); str += clo + ':' + value + ';'; } return str; } class Movie extends React.Component&lt;any, any&gt;{ public static style:React.CSSProperties|object = { width: &quot;300px&quot;, height: &quot;120px&quot;, display: &quot;flex&quot;, justifyContent: &quot;space-around&quot;, alignItems: &quot;center&quot;, borderRadius: &quot;20px&quot;, filter: &quot;drop-shadow(0px 1px 3px #6d6d6d)&quot;, WebkitFilter: &quot;drop-shadow(3px 3px 3px #6d6d6d)&quot;, backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16), fontSize: '2.5rem', margin: '20px', color: '#fff', } props:React.ComponentProps&lt;any&gt;; state:React.ComponentState; constructor(props:any) { super(props); this.props = props; this.state = {style: Object.assign({}, Movie.style)} this.changeColor = this.changeColor.bind(this); } changeColor():void{ this.setState({style: Object.assign({}, Movie.style, {backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16)})}); } render():JSX.Element{ let StyledMovie = styled.div` ${CSSPropertiesToComponent(Movie.style)} `; return ( &lt;&gt; &lt;StyledMovie&gt;{this.props.title}&lt;/StyledMovie&gt; &lt;/&gt; ) } } export default function App() { let MV = new Movie({title: 'the Avengers'}); return ( &lt;&gt; {MV.render()} &lt;button onClick={MV.changeColor}&gt;Change Color&lt;/button&gt; &lt;/&gt; ) } </code></pre> <p>However, when clicking on the change colour button, it doesn't work and shows a warning:</p> <pre><code>Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the Movie component. </code></pre> <p>if anyone offers some suggestion, I will be so glad.</p>
3
1,675
Jquery is not working properly in asp.net AsyncPostBackTrigger
<p>net.</p> <p>Recently I have tried to validate some asp controls with my jquery functions in the content page.</p> <p>Below I have given some code where i want to validate one dropdown list which will check that the selected Index of the dropdown list is 0. If it is zero then the background of the dropdown list will be red. Else it will remain same.</p> <p>The other Control is TextBox. In the same way if the textbox's length is 0 then the backround color will be red.</p> <p>When the save button will be clicked the validation will start.</p> <p>Here I have given all the necessary code in jquery.</p> <p>But the problem is when I click the Save Button then both Dropdown and Textbox turns red for a certain time(1 or 2 sec) then turns into white background automatically. </p> <pre><code> &lt;asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"&gt; &lt;script&gt; $(document).ready(function () { var valid = 0; // check all fields validity when "Save" Button clicked $("#&lt;%= btnSave.ClientID%&gt;").bind("click", function () { var validity = validateAllFields(); if (validity == false) { return false; } else { } }); }); /// validating all fields // if all fields are valid then return true else return false// function validateAllFields() { var nValid = 0; //validate DropDown box nValid += checkDropdownList($("#&lt;%= ddl1.ClientID%&gt;")); // check ddl1 is Selected or not //validate Text Field nValid += checkTBLength($("#&lt;%= tb1.ClientID%&gt;"), 1); // check "tb1" length if (nValid &gt; 0) { return false; } else { return true; } } // check whether the dropdownlist is selected other than "Select Item" // parametes- idDropdown= id the of the dropdown List function checkDropdownList(idDropdown) { // check if the dropdown selected index is 0 or not // if zero then set the background color red if ($(idDropdown).prop('selectedIndex') == 0) { $(idDropdown).css("background-color", "red").trigger("change"); // set dropdownlist background color to red return 1; } else { // set the background color white $(idDropdown).css("border-color", ""); return 0; } } /// check minimum required length of the textbox // Parameters- idTextbox= id of the textbox, minLength= minimum Required Length function checkTBLength(idTextbox, minLength) { //check if the textbox's lenth is less than minimum Required Length or not if ($(idTextbox).val().length &lt; minLength) { $(idTextbox).css("background-color", "red"); // set the background textbox color to red return 1; // return 1 for validation failed } else { $(idTextbox).css("background-color", "white");// set the background textbox color to red return 0; // return 1 for validation passed } } &lt;/script&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt;&lt;/asp:ScriptManager&gt; &lt;div class="form-group"&gt; &lt;asp:UpdatePanel ID="UP1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true"&gt; &lt;asp:ListItem Selected="true"&gt;Select&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;/div&gt; &lt;div class="span4"&gt; &lt;div class="form-group"&gt; &lt;label for="pwd"&gt;Query Details&lt;/label&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:TextBox ID="tb1" runat="server" TextMode="MultiLine" MaxLength="500" class="form-control" Rows="4" Width="100%"&gt;&lt;/asp:TextBox&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;asp:Button ID="btnSave" runat="server" Text="Save" class="btn btn-info" OnClick="btnSave_Click" /&gt; &lt;/div&gt; &lt;/asp:Content&gt; </code></pre> <p>Note that I have used AsyncPostBackTrigger in both controls.</p> <p>Can you please mention why this is happening and how to resolve it.</p> <p>Thank You.</p>
3
1,908
Uncaught TypeError with my script
<p>I need some help, I don't know why in some websites it not error, but some websites it is error show up.</p> <p>Its show up the error notice in my console: Uncaught TypeError: Cannot read property 'length' of undefined.</p> <p>Any advice is thanks so much.</p> <pre><code>jQuery(document).ready(function(){ jQuery( ".pagenav.home .menu &gt; li:first-child a" ).addClass('important_color'); if (jQuery( ".menu-fixedmenu" ).length) { jQuery( ".menu-fixedmenu .menu a" ).each(function() { var id = jQuery(this).attr('href'); var lenght_id = id.length;//***this line code error*** if (typeof id !== "undefined" &amp;&amp; lenght_id &gt; 2) { if(id.search("#") != -1 &amp;&amp; id.search("http")){ jQuery( window ).scroll(function() { if(jQuery(id).isOnScreen()){ jQuery(id+' h2').removeClass('fadeInDown'); jQuery(id+' h2').addClass('animated fadeInUp'); var newid = id.split("#"); if(document.getElementById(newid[1]).getBoundingClientRect().top &lt; 250){ jQuery( ".fixedmenu .menu &gt; li a[href='"+id+"']" ).addClass('important_color'); } else{ jQuery( ".fixedmenu .menu &gt; li a[href='"+id+"']" ).removeClass('important_color'); } } else{ if(id != jQuery( ".menu &gt; li:first-child a" ).attr('href') ) jQuery( ".fixedmenu .menu &gt; li a[href='"+id+"']" ).removeClass('important_color'); if(jQuery(this).scrollTop() &gt; 700) jQuery( ".menu-fixedmenu .menu &gt; li:first-child a" ).removeClass('important_color'); else jQuery( ".menu-fixedmenu .menu &gt; li:first-child a" ).addClass('important_color'); jQuery(id+' h2').removeClass('fadeInUp'); jQuery(id+' h2').addClass('animated fadeInDown'); } }); } } }); } </code></pre> <p>});</p>
3
1,117
Binding MVC4 to An Object Containing Arrays
<p>I am creating a form to allow employees to submit timesheets online. The form consists of a number of sections, each representing a day of the week. Within each section, the user can add multiple rows, each row reflecting a task undertaken that day.</p> <pre><code>function AddRow(day) { var count = $("#RowCount_" + day).data("count"); var row = "&lt;tr&gt;" + "&lt;td&gt;&amp;nbsp;&lt;/td&gt;" + "&lt;td&gt;&lt;input type='text' size='50' id='" + day + "[" + count + "].Description' name='timesheet." + day + "[" + count + "].Description' class='Description' data-day='" + day + "' /&gt;&lt;/td&gt;" + "&lt;td&gt;&lt;input type='text' size='6' id='" + day + "[" + count + "].Start' name='timesheet." + day + "[" + count + "].Start' /&gt;&lt;/td&gt;" + "&lt;td&gt;&lt;input type='text' size='6' id='" + day + "[" + count + "].Finish' name='timesheet." + day + "[" + count + "].Finish' /&gt;&lt;/td&gt;" + "&lt;td&gt;&lt;input type='text' size='6' id='" + day + "[" + count + "].Travel' name='timesheet." + day + "[" + count + "].Travel'/&gt;&lt;/td&gt;" + "&lt;td&gt;" + "&lt;select style='width:200px' id='" + day + "[" + count + "].JobNo' name='timesheet." + day + "[" + count + "].JobNo'&gt;@Html.Raw(ViewBag.Jobs)&lt;/select&gt;" + "&lt;/td&gt;" + "&lt;td&gt;&lt;input type='text' size='6' id='" + day + "[" + count + "].Hrs' name='timesheet." + day + "[" + count + "].Hrs' /&gt;&lt;/td&gt;" + "&lt;/tr&gt;"; $("#Table_" + day).append(row); $("#RowCount_" + day).data("count", ++count); } </code></pre> <p>I then want to bind this to a <code>Timesheet</code> object, as follows:</p> <pre><code>public class Timesheet { List&lt;Core.Models.TimesheetEntry&gt; Monday = new List&lt;TimesheetEntry&gt;(); TimesheetEntry[] Tuesday { get; set; } TimesheetEntry[] Wednesday { get; set; } TimesheetEntry[] Thursday { get; set; } TimesheetEntry[] Friday { get; set; } TimesheetEntry[] Saturday { get; set; } TimesheetEntry[] Sunday { get; set; } } </code></pre> <p>(note I am trying both lists and arrays here, neither of which bind, but more of this in a minute)</p> <p>The <code>TimesheetEntry</code> is as follows:</p> <pre><code>public class TimesheetEntry { public string Description { get; set; } public string Start { get; set; } public string Finish { get; set; } public decimal Travel { get; set; } public string JobNo { get; set; } public decimal Hrs { get; set; } } </code></pre> <p>This posts to the following controller method:</p> <pre><code>[HttpPost] public ActionResult Create(Core.Models.Timesheet timesheet) { return View(); } </code></pre> <p>When submitted, the form does not bind (all fields in timesheet are 0 or null). However, if I change the controller to </p> <pre><code>public ActionResult Create(List&lt;Core.Models.TimesheetEntry&gt; Monday) { return View(); } </code></pre> <p>and adjust the name of the html fields to <code>name='" + day + "[" + count + "].Description'</code> then it will bind just fine. This is a little messy, so I'd rather use the <code>Timesheet</code> class if possible. Is there an issue binding to Lists within models?</p> <p>EDIT: Below is a snippet of the post data, with a single entry and 2 blank entries for monday, 3 blank for tuesday:</p> <pre><code>timesheet.Monday[0].Description:test entry timesheet.Monday[0].Start:0900 timesheet.Monday[0].Finish:1700 timesheet.Monday[0].Travel:0 timesheet.Monday[0].JobNo:14089A - line 14 hut heater sockets timesheet.Monday[0].Hrs:7.5 timesheet.Monday[1].Description: timesheet.Monday[1].Start: timesheet.Monday[1].Finish: timesheet.Monday[1].Travel: timesheet.Monday[1].JobNo:14089A - line 14 hut heater sockets timesheet.Monday[1].Hrs: timesheet.Monday[2].Description: timesheet.Monday[2].Start: timesheet.Monday[2].Finish: timesheet.Monday[2].Travel: timesheet.Monday[2].JobNo:14089A - line 14 hut heater sockets timesheet.Monday[2].Hrs: timesheet.Tuesday[0].Description: timesheet.Tuesday[0].Start: timesheet.Tuesday[0].Finish: timesheet.Tuesday[0].Travel: timesheet.Tuesday[0].JobNo:14089A - line 14 hut heater sockets timesheet.Tuesday[0].Hrs: timesheet.Tuesday[1].Description: timesheet.Tuesday[1].Start: timesheet.Tuesday[1].Finish: timesheet.Tuesday[1].Travel: timesheet.Tuesday[1].JobNo:14089A - line 14 hut heater sockets timesheet.Tuesday[1].Hrs: </code></pre>
3
1,788
How to start a new activity from a fragment calss by clicking on Linearlayout within fragment? below is my code but this is not working
<p>when i click on linearlayout within a fragment it dose't give any error but do not start new activity. Is there any error in my code? please someone help me. This fragment xml file code of my project. </p> <p>Fragment_one.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" &gt; &lt;LinearLayout android:id="@+id/Lbid" android:layout_width="wrap_content" android:layout_marginTop="30dp" android:layout_height="wrap_content"&gt; &lt;ProgressBar style="?android:attr/progressBarStyleHorizontal" android:id="@+id/pbb" android:layout_marginLeft="15dp" android:layout_width="180dp" android:layout_height="25dp" android:progress="50" android:progressDrawable="@drawable/bidonpb" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bid on" android:id="@+id/tv" android:layout_marginLeft="2dp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/Lap" android:layout_width="wrap_content" android:layout_marginTop="20dp" android:layout_height="wrap_content"&gt; &lt;ProgressBar style="?android:attr/progressBarStyleHorizontal" android:id="@+id/pbap" android:layout_marginLeft="15dp" android:layout_width="180dp" android:layout_height="25dp" android:progress="60" android:progressDrawable="@drawable/appb" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Awaiting Payments" android:layout_marginLeft="2dp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/LO" android:layout_width="wrap_content" android:layout_marginTop="20dp" android:layout_height="wrap_content"&gt; &lt;ProgressBar style="?android:attr/progressBarStyleHorizontal" android:id="@+id/pbo" android:layout_marginLeft="15dp" android:layout_width="180dp" android:layout_height="25dp" android:progress="20" android:progressDrawable="@drawable/opb" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Overdue" android:layout_marginLeft="2dp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_marginTop="20dp" android:id="@+id/LA" android:layout_height="wrap_content"&gt; &lt;ProgressBar style="?android:attr/progressBarStyleHorizontal" android:id="@+id/pba" android:layout_marginLeft="15dp" android:layout_width="180dp" android:layout_height="25dp" android:progress="45" android:progressDrawable="@drawable/assignedpb" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Assigned" android:layout_marginLeft="2dp" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>This fragment java class code of my project. </p> <p><strong>FragmentOne.java</strong></p> <pre class="lang-js prettyprint-override"><code> info.androidhive.listviewfeed; import android.app.Fragment; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ProgressBar; public class FragmentOne extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); LinearLayout lbid =(LinearLayout) view.findViewById(R.id.Lbid); lbid.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ProjectDetails.class); startActivity(intent); } }); return inflater.inflate( R.layout.fragment_one, container, false); } } </code></pre>
3
2,724
Spring & Hibernate @Valid doing nothing
<p>I have annotated my fields in my model and am using the @Valid annotation on my post controller but it appears to be performing no validation (result.errors is empty)</p> <p>Any ideas what might be causing this?</p> <p>Java based configuration:</p> <pre><code>@FeatureConfiguration public class MvcFeatures { @Feature public MvcAnnotationDriven annotationDriven() { return new MvcAnnotationDriven(); } @Feature public MvcResources css() { return new MvcResources("/css/**", "/css/"); } @Feature public MvcResources js() { return new MvcResources("/js/**", "/js/"); } @Feature public MvcViewControllers viewController() { return new MvcViewControllers("/", "home"); } @Feature public ComponentScanSpec componentScan() { return new ComponentScanSpec("com.webapp") .excludeFilters(new AnnotationTypeFilter(Configuration.class), new AnnotationTypeFilter(FeatureConfiguration.class)); } } </code></pre> <p><br/><br/> Controller:</p> <pre><code>@Controller public class UserController extends AppController { static Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired private IUserService userService; @RequestMapping(value = "/registration", method = RequestMethod.GET) public ModelAndView get() { ModelAndView modelAndView = new ModelAndView(Consts.MODEL_RESISTER_PAGE); modelAndView.addObject("user", new User()); return modelAndView; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public ModelAndView post(@Valid User user, BindingResult result) { if (result.hasErrors()) { ModelAndView modelAndView = new ModelAndView( Consts.MODEL_RESISTER_PAGE); modelAndView.addObject("user", result.getModel()); return modelAndView; } else { // SAVE HERE ModelAndView modelAndView = new ModelAndView( Consts.MODEL_RESISTER_PAGE); return modelAndView; } } } </code></pre> <p><br/><br/> Model:</p> <pre><code>@Entity public class User implements Serializable { /** * */ private static final long serialVersionUID = -5232533507244034448L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotEmpty @Size(min=2, max=15) private String firstname; @NotEmpty @Size(min=2, max=15) private String surname; @NotEmpty @Email private String email; @NotEmpty @Size(min=6, max=10) private String password; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } </code></pre> <p><br/><br/> add.html (Using thymeleaf view resolver)</p> <pre><code>&lt;form id="registrationForm" action="#" th:action="@{/registration}" th:object="${user}" method="post" class="clearfix"&gt; &lt;legend&gt;Registration&lt;/legend&gt; &lt;div class="input"&gt; &lt;input type="text" th:field="*{firstname}" placeholder="Firstname" th:class="${#fields.hasErrors('firstname')}? 'fieldError'" /&gt; &lt;/div&gt; &lt;div class="input"&gt; &lt;input type="text" th:field="*{surname}" placeholder="Surname" /&gt; &lt;/div&gt; &lt;div class="input"&gt; &lt;input type="text" th:field="*{email}" placeholder="Email" /&gt; &lt;/div&gt; &lt;div class="input"&gt; &lt;input type="password" th:field="*{password}" placeholder="Password" /&gt; &lt;/div&gt; &lt;div class="clearfix"&gt; &lt;input type="submit" class="btn btn-success btn-large" value="Register" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p><br/><br/> Pom:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;ConsumerApplicaton&lt;/groupId&gt; &lt;artifactId&gt;ConsumerApplicaton&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;repositories&gt; &lt;repository&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;id&gt;springsource-milestone&lt;/id&gt; &lt;name&gt;Spring Framework Milestone Repository&lt;/name&gt; &lt;url&gt;http://maven.springframework.org/milestone&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;!-- spring --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-oxm&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- thymeleaf --&gt; &lt;dependency&gt; &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt; &lt;artifactId&gt;thymeleaf&lt;/artifactId&gt; &lt;version&gt;${thymeleaf.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt; &lt;artifactId&gt;thymeleaf-spring3&lt;/artifactId&gt; &lt;version&gt;${thymeleaf.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- persistence --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version&gt;3.1.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;3.6.9.Final&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt; &lt;version&gt;4.2.0.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!-- json, xml, atom --&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;${jackson-mapper-asl.version}&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;version&gt;${jaxb-api.version}&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- DB --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.18&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- logging --&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;version&gt;${org.slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt; &lt;artifactId&gt;logback-classic&lt;/artifactId&gt; &lt;version&gt;1.0.1&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt; &lt;version&gt;${org.slf4j.version}&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- Various --&gt; &lt;dependency&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib-nodep&lt;/artifactId&gt; &lt;version&gt;${cglib.version}&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;ConsumerApplicaton&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.6&lt;/source&gt; &lt;target&gt;1.6&lt;/target&gt; &lt;encoding&gt;UTF-8&lt;/encoding&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;properties&gt; &lt;!-- VERSIONS --&gt; &lt;!-- &lt;spring.version&gt;3.1.0.RELEASE&lt;/spring.version&gt; --&gt; &lt;spring.version&gt;3.1.0.M1&lt;/spring.version&gt; &lt;cglib.version&gt;2.2.2&lt;/cglib.version&gt; &lt;thymeleaf.version&gt;2.0.11&lt;/thymeleaf.version&gt; &lt;jackson-mapper-asl.version&gt;1.9.5&lt;/jackson-mapper-asl.version&gt; &lt;jaxb-api.version&gt;2.2.6&lt;/jaxb-api.version&gt; &lt;!-- VERSIONS - persistence --&gt; &lt;mysql-connector-java.version&gt;5.1.18&lt;/mysql-connector-java.version&gt; &lt;!-- latest version on: 02.10.2011 - http://dev.mysql.com/downloads/connector/j/ --&gt; &lt;hibernate.version&gt;4.1.0.Final&lt;/hibernate.version&gt; &lt;!-- VERSIONS - logging --&gt; &lt;org.slf4j.version&gt;1.6.4&lt;/org.slf4j.version&gt; &lt;/properties&gt; &lt;/project&gt; </code></pre>
3
6,100
line color change based on logic in apache echarts
<p><strong>Due to the company policy I can't share any kind of code</strong> but I have been struggling with apche echarts. The requirement is I have a line whose color should change at certain points based on logic. I tried achieving using linestyle and piecewise using dimension. I came pretty close to visualmap but the issue persisted when The parallel or adjacent lines started to get affected and caused wrong color changes on the graph. Here is the requirement the line on the chart is supposed to be red unless we come across a point where the color could be changed to green and back to red when the event is done. please refer to the image and I am open to any and all suggestions. I would prefer a sandbox as an answer link so i can test if that works with the requirement or not. <a href="https://i.stack.imgur.com/f3uxT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f3uxT.png" alt="requirement Image" /></a></p> <p>EDIT 1 The closest I came is this</p> <pre><code>option = { title: { text: '一天用电量分布', subtext: '纯属虚构' }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } }, toolbox: { show: true, feature: { saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: ['00:00', '01:15', '02:30', '03:45', '05:00', '06:15', '07:30', '08:45', '10:00', '11:15', '12:30', '13:45', '15:00', '16:15', '17:30', '18:45', '20:00', '21:15', '22:30', '23:45'] }, yAxis: { type: 'value', axisLabel: { formatter: '{value} W' }, axisPointer: { snap: true } }, visualMap: { show: false, dimension: 0, pieces: [{ lte: 6, color: 'green' }, { gt: 6, lte: 8, color: 'red' }, { gt: 8, lte: 14, color: 'green' }, { gt: 14, lte: 17, color: 'red' }, { gt: 17, color: 'green' }] }, series: [ { name: '用电量', type: 'line', smooth: true, data: [300, 280, 250, 260, 270, 300, 550, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400], } ] }; </code></pre> <p>which renders <a href="https://i.stack.imgur.com/9QmGu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9QmGu.png" alt="this" /></a></p> <p>how can I use logic to calculate the visualmap points based on event.</p>
3
1,268
submit register form of user in react
<p>I want to submit this registeration form with unique names.</p> <p><strong>First Problem</strong> : I can't seem to map third time. The error shows <strong>array is not iterable</strong>.</p> <p><strong>Second Problem</strong> : I cant change the setArray state in (<strong>array not empty</strong>) <strong>section</strong>. I know it is synchronous but I can't seem to find a solution.</p> <p>Please give me a solution of if I want to have an immediate value of state after changing setState. I'm stuck in this problem for 3 days.</p> <pre><code>import React from 'react'; import { Paper, Typography, TextField , Button, makeStyles} from '@material-ui/core'; import { Link} from 'react-router-dom' import {useEffect} from 'react'; const useStyle = makeStyles((theme)=&gt;( { formWrapper : { display : 'flex', width : '100%', height : '100%', alignItems : 'center', justifyContent : 'center' }, paper : { padding : '20px', margin : '20px' }, textfield : { marginLeft : '20px', marginBottom : '10px' }, span : { margin: '10px', marginLeft : '20px' } } )) const Register = () =&gt;{ const classes = useStyle(); const [name, setName] = React.useState(''); const [password, setPassword] = React.useState(''); const [array, setArray] = React.useState([]) const submit = (event) =&gt;{ const obj = {} event.preventDefault(); if(array.length === 0){ // Array is empty if((name === null || password === null)||(name === '' || password === '')){ //check if name and password are empty alert('Enter username and password') }else{ // not empty then store in localstorage localStorage.setItem('name', name); localStorage.setItem('password',password); obj.id = Math.random(); obj.name = localStorage.getItem('name'); obj.password = localStorage.getItem('password'); setArray(array.push(obj)) localStorage.setItem('array',JSON.stringify(array)) setName(''); setPassword('') return alert('You are registered'); } } else // array not empty { if((name === null || password === null) ||(name === '' || password === '')){ alert('Enter username and passsword'); } let array2 = JSON.parse(localStorage.getItem('array')).map(user=&gt; user.name) var found = array2.includes(name); if(found){ alert('User name Taken') setName('') setPassword('') } else{ localStorage.setItem('name', name); localStorage.setItem('password',password); obj.id = Math.random(); obj.name = localStorage.getItem('name'); obj.password = localStorage.getItem('password'); setArray([...array,obj]) localStorage.setItem('array',JSON.stringify(array)) console.log(array); setName(''); setPassword('') return alert('You are registered'); } } } return( &lt;div&gt; &lt;div className = {classes.formWrapper}&gt; &lt;Paper elevation={3} className = {classes.paper} &gt; &lt;Typography variant=&quot;h5&quot; style = {{ textAlign : 'center'}}&gt;Register&lt;/Typography&gt; &lt;form noValidate autoComplete=&quot;off&quot;&gt; &lt;TextField id=&quot;username&quot; className={classes.textfield} value = {name} name = &quot;username&quot; label=&quot;Username&quot; onChange = {e=&gt;setName(e.target.value)} /&gt; &lt;br /&gt; &lt;TextField id=&quot;password&quot; className={classes.textfield} value = {password} name = &quot;password&quot; label=&quot;Password&quot; onChange = {e=&gt;setPassword(e.target.value)} /&gt; &lt;br /&gt; &lt;span className ={classes.span}&gt;&lt;Link to=&quot;/&quot;&gt;Sign In&lt;/Link&gt;&lt;/span&gt; &lt;br /&gt; &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot; style = {{width : '100%', marginTop : '10px'}} onClick = {submit} &gt;Register &lt;/Button&gt; &lt;/form&gt; &lt;/Paper&gt; &lt;/div&gt; &lt;/div&gt; ) } export default Register; </code></pre>
3
2,376
Function to check if text is emoji dont recognize all the emojis
<p>I have a function that check if the string is emoji. the <code>function</code>:</p> <pre><code>function has_emojis( $string ) { preg_match( '/[\x{1F600}-\x{1F64F}]/u', $string, $matches_emo ); return !empty( $matches_emo[0] ) ? true : false; } </code></pre> <p>the problem: its not recognize all the emojis, for example its recgonize this one - as emoji but not this (and a lot of more)</p> <p>I tried to change the preg_match range but without success because I dont know the specific range for all the emojis.</p> <h2>Problem solution:</h2> <p>use this function:</p> <pre><code>function has_emojis( $string ) { // Array of emoji (v12, 2019) unicodes from https://unicode.org/emoji/charts/emoji-list.html $unicodes = array( '1F600','1F603','1F604','1F601','1F606','1F605','1F923','1F602','1F642','1F643','1F609','1F60A','1F607','1F970','1F60D','1F929','1F618','1F617','263A','1F61A','1F619','1F60B','1F61B','1F61C','1F92A','1F61D','1F911','1F917','1F92D','1F92B','1F914','1F910','1F928','1F610','1F611','1F636','1F60F','1F612','1F644','1F62C','1F925','1F60C','1F614','1F62A','1F924','1F634','1F637','1F912','1F915','1F922','1F92E','1F927','1F975','1F976','1F974','1F635','1F92F','1F920','1F973','1F60E','1F913','1F9D0','1F615','1F61F','1F641','2639','1F62E','1F62F','1F632','1F633','1F97A','1F626','1F627','1F628','1F630','1F625','1F622','1F62D','1F631','1F616','1F623','1F61E','1F613','1F629','1F62B','1F971','1F624','1F621','1F620','1F92C','1F608','1F47F','1F480','2620','1F4A9','1F921','1F479','1F47A','1F47B','1F47D','1F47E','1F916','1F63A','1F638','1F639','1F63B','1F63C','1F63D','1F640','1F63F','1F63E','1F648','1F649','1F64A','1F48B','1F48C','1F498','1F49D','1F496','1F497','1F493','1F49E','1F495','1F49F','2763','1F494','2764','1F9E1','1F49B','1F49A','1F499','1F49C','1F90E','1F5A4','1F90D','1F4AF','1F4A2','1F4A5','1F4AB','1F4A6','1F4A8','1F573','1F4A3','1F4AC','1F441','FE0F','200D','1F5E8','FE0F','1F5E8','1F5EF','1F4AD','1F4A4','1F44B','1F91A','1F590','270B','1F596','1F44C','1F90F','270C','1F91E','1F91F','1F918','1F919','1F448','1F449','1F446','1F595','1F447','261D','1F44D','1F44E','270A','1F44A','1F91B','1F91C','1F44F','1F64C','1F450','1F932','1F91D','1F64F','270D','1F485','1F933','1F4AA','1F9BE','1F9BF','1F9B5','1F9B6','1F442','1F9BB','1F443','1F9E0','1F9B7','1F9B4','1F440','1F441','1F445','1F444','1F476','1F9D2','1F466','1F467','1F9D1','1F471','1F468','1F9D4','1F471','200D','2642','FE0F','1F468','200D','1F9B0','1F468','200D','1F9B1','1F468','200D','1F9B3','1F468','200D','1F9B2','1F469','1F471','200D','2640','FE0F','1F469','200D','1F9B0','1F469','200D','1F9B1','1F469','200D','1F9B3','1F469','200D','1F9B2','1F9D3','1F474','1F475','1F64D','1F64D','200D','2642','FE0F','1F64D','200D','2640','FE0F','1F64E','1F64E','200D','2642','FE0F','1F64E','200D','2640','FE0F','1F645','1F645','200D','2642','FE0F','1F645','200D','2640','FE0F','1F646','1F646','200D','2642','FE0F','1F646','200D','2640','FE0F','1F481','1F481','200D','2642','FE0F','1F481','200D','2640','FE0F','1F64B','1F64B','200D','2642','FE0F','1F64B','200D','2640','FE0F','1F9CF','1F9CF','200D','2642','FE0F','1F9CF','200D','2640','FE0F','1F647','1F647','200D','2642','FE0F','1F647','200D','2640','FE0F','1F926','1F926','200D','2642','FE0F','1F926','200D','2640','FE0F','1F937','1F937','200D','2642','FE0F','1F937','200D','2640','FE0F','1F468','200D','2695','FE0F','1F469','200D','2695','FE0F','1F468','200D','1F393','1F469','200D','1F393','1F468','200D','1F3EB','1F469','200D','1F3EB','1F468','200D','2696','FE0F','1F469','200D','2696','FE0F','1F468','200D','1F33E','1F469','200D','1F33E','1F468','200D','1F373','1F469','200D','1F373','1F468','200D','1F527','1F469','200D','1F527','1F468','200D','1F3ED','1F469','200D','1F3ED','1F468','200D','1F4BC','1F469','200D','1F4BC','1F468','200D','1F52C','1F469','200D','1F52C','1F468','200D','1F4BB','1F469','200D','1F4BB','1F468','200D','1F3A4','1F469','200D','1F3A4','1F468','200D','1F3A8','1F469','200D','1F3A8','1F468','200D','2708','FE0F','1F469','200D','2708','FE0F','1F468','200D','1F680','1F469','200D','1F680','1F468','200D','1F692','1F469','200D','1F692','1F46E','1F46E','200D','2642','FE0F','1F46E','200D','2640','FE0F','1F575','1F575','FE0F','200D','2642','FE0F','1F575','FE0F','200D','2640','FE0F','1F482','1F482','200D','2642','FE0F','1F482','200D','2640','FE0F','1F477','1F477','200D','2642','FE0F','1F477','200D','2640','FE0F','1F934','1F478','1F473','1F473','200D','2642','FE0F','1F473','200D','2640','FE0F','1F472','1F9D5','1F935','1F470','1F930','1F931','1F47C','1F385','1F936','1F9B8','1F9B8','200D','2642','FE0F','1F9B8','200D','2640','FE0F','1F9B9','1F9B9','200D','2642','FE0F','1F9B9','200D','2640','FE0F','1F9D9','1F9D9','200D','2642','FE0F','1F9D9','200D','2640','FE0F','1F9DA','1F9DA','200D','2642','FE0F','1F9DA','200D','2640','FE0F','1F9DB','1F9DB','200D','2642','FE0F','1F9DB','200D','2640','FE0F','1F9DC','1F9DC','200D','2642','FE0F','1F9DC','200D','2640','FE0F','1F9DD','1F9DD','200D','2642','FE0F','1F9DD','200D','2640','FE0F','1F9DE','1F9DE','200D','2642','FE0F','1F9DE','200D','2640','FE0F','1F9DF','1F9DF','200D','2642','FE0F','1F9DF','200D','2640','FE0F','1F486','1F486','200D','2642','FE0F','1F486','200D','2640','FE0F','1F487','1F487','200D','2642','FE0F','1F487','200D','2640','FE0F','1F6B6','1F6B6','200D','2642','FE0F','1F6B6','200D','2640','FE0F','1F9CD','1F9CD','200D','2642','FE0F','1F9CD','200D','2640','FE0F','1F9CE','1F9CE','200D','2642','FE0F','1F9CE','200D','2640','FE0F','1F468','200D','1F9AF','1F469','200D','1F9AF','1F468','200D','1F9BC','1F469','200D','1F9BC','1F468','200D','1F9BD','1F469','200D','1F9BD','1F3C3','1F3C3','200D','2642','FE0F','1F3C3','200D','2640','FE0F','1F483','1F57A','1F574','1F46F','1F46F','200D','2642','FE0F','1F46F','200D','2640','FE0F','1F9D6','1F9D6','200D','2642','FE0F','1F9D6','200D','2640','FE0F','1F9D7','1F9D7','200D','2642','FE0F','1F9D7','200D','2640','FE0F','1F93A','1F3C7','26F7','1F3C2','1F3CC','1F3CC','FE0F','200D','2642','FE0F','1F3CC','FE0F','200D','2640','FE0F','1F3C4','1F3C4','200D','2642','FE0F','1F3C4','200D','2640','FE0F','1F6A3','1F6A3','200D','2642','FE0F','1F6A3','200D','2640','FE0F','1F3CA','1F3CA','200D','2642','FE0F','1F3CA','200D','2640','FE0F','26F9','26F9','FE0F','200D','2642','FE0F','26F9','FE0F','200D','2640','FE0F','1F3CB','1F3CB','FE0F','200D','2642','FE0F','1F3CB','FE0F','200D','2640','FE0F','1F6B4','1F6B4','200D','2642','FE0F','1F6B4','200D','2640','FE0F','1F6B5','1F6B5','200D','2642','FE0F','1F6B5','200D','2640','FE0F','1F938','1F938','200D','2642','FE0F','1F938','200D','2640','FE0F','1F93C','1F93C','200D','2642','FE0F','1F93C','200D','2640','FE0F','1F93D','1F93D','200D','2642','FE0F','1F93D','200D','2640','FE0F','1F93E','1F93E','200D','2642','FE0F','1F93E','200D','2640','FE0F','1F939','1F939','200D','2642','FE0F','1F939','200D','2640','FE0F','1F9D8','1F9D8','200D','2642','FE0F','1F9D8','200D','2640','FE0F','1F6C0','1F6CC','1F9D1','200D','1F91D','200D','1F9D1','1F46D','1F46B','1F46C','1F48F','1F469','200D','2764','FE0F','200D','1F48B','200D','1F468','1F468','200D','2764','FE0F','200D','1F48B','200D','1F468','1F469','200D','2764','FE0F','200D','1F48B','200D','1F469','1F491','1F469','200D','2764','FE0F','200D','1F468','1F468','200D','2764','FE0F','200D','1F468','1F469','200D','2764','FE0F','200D','1F469','1F46A','1F468','200D','1F469','200D','1F466','1F468','200D','1F469','200D','1F467','1F468','200D','1F469','200D','1F467','200D','1F466','1F468','200D','1F469','200D','1F466','200D','1F466','1F468','200D','1F469','200D','1F467','200D','1F467','1F468','200D','1F468','200D','1F466','1F468','200D','1F468','200D','1F467','1F468','200D','1F468','200D','1F467','200D','1F466','1F468','200D','1F468','200D','1F466','200D','1F466','1F468','200D','1F468','200D','1F467','200D','1F467','1F469','200D','1F469','200D','1F466','1F469','200D','1F469','200D','1F467','1F469','200D','1F469','200D','1F467','200D','1F466','1F469','200D','1F469','200D','1F466','200D','1F466','1F469','200D','1F469','200D','1F467','200D','1F467','1F468','200D','1F466','1F468','200D','1F466','200D','1F466','1F468','200D','1F467','1F468','200D','1F467','200D','1F466','1F468','200D','1F467','200D','1F467','1F469','200D','1F466','1F469','200D','1F466','200D','1F466','1F469','200D','1F467','1F469','200D','1F467','200D','1F466','1F469','200D','1F467','200D','1F467','1F5E3','1F464','1F465','1F463','1F9B0','1F9B1','1F9B3','1F9B2','1F435','1F412','1F98D','1F9A7','1F436','1F415','1F9AE','1F415','200D','1F9BA','1F429','1F43A','1F98A','1F99D','1F431','1F408','1F981','1F42F','1F405','1F406','1F434','1F40E','1F984','1F993','1F98C','1F42E','1F402','1F403','1F404','1F437','1F416','1F417','1F43D','1F40F','1F411','1F410','1F42A','1F42B','1F999','1F992','1F418','1F98F','1F99B','1F42D','1F401','1F400','1F439','1F430','1F407','1F43F','1F994','1F987','1F43B','1F428','1F43C','1F9A5','1F9A6','1F9A8','1F998','1F9A1','1F43E','1F983','1F414','1F413','1F423','1F424','1F425','1F426','1F427','1F54A','1F985','1F986','1F9A2','1F989','1F9A9','1F99A','1F99C','1F438','1F40A','1F422','1F98E','1F40D','1F432','1F409','1F995','1F996','1F433','1F40B','1F42C','1F41F','1F420','1F421','1F988','1F419','1F41A','1F40C','1F98B','1F41B','1F41C','1F41D','1F41E','1F997','1F577','1F578','1F982','1F99F','1F9A0','1F490','1F338','1F4AE','1F3F5','1F339','1F940','1F33A','1F33B','1F33C','1F337','1F331','1F332','1F333','1F334','1F335','1F33E','1F33F','2618','1F340','1F341','1F342','1F343','1F347','1F348','1F349','1F34A','1F34B','1F34C','1F34D','1F96D','1F34E','1F34F','1F350','1F351','1F352','1F353','1F95D','1F345','1F965','1F951','1F346','1F954','1F955','1F33D','1F336','1F952','1F96C','1F966','1F9C4','1F9C5','1F344','1F95C','1F330','1F35E','1F950','1F956','1F968','1F96F','1F95E','1F9C7','1F9C0','1F356','1F357','1F969','1F953','1F354','1F35F','1F355','1F32D','1F96A','1F32E','1F32F','1F959','1F9C6','1F95A','1F373','1F958','1F372','1F963','1F957','1F37F','1F9C8','1F9C2','1F96B','1F371','1F358','1F359','1F35A','1F35B','1F35C','1F35D','1F360','1F362','1F363','1F364','1F365','1F96E','1F361','1F95F','1F960','1F961','1F980','1F99E','1F990','1F991','1F9AA','1F366','1F367','1F368','1F369','1F36A','1F382','1F370','1F9C1','1F967','1F36B','1F36C','1F36D','1F36E','1F36F','1F37C','1F95B','2615','1F375','1F376','1F37E','1F377','1F378','1F379','1F37A','1F37B','1F942','1F943','1F964','1F9C3','1F9C9','1F9CA','1F962','1F37D','1F374','1F944','1F52A','1F3FA','1F30D','1F30E','1F30F','1F310','1F5FA','1F5FE','1F9ED','1F3D4','26F0','1F30B','1F5FB','1F3D5','1F3D6','1F3DC','1F3DD','1F3DE','1F3DF','1F3DB','1F3D7','1F9F1','1F3D8','1F3DA','1F3E0','1F3E1','1F3E2','1F3E3','1F3E4','1F3E5','1F3E6','1F3E8','1F3E9','1F3EA','1F3EB','1F3EC','1F3ED','1F3EF','1F3F0','1F492','1F5FC','1F5FD','26EA','1F54C','1F6D5','1F54D','26E9','1F54B','26F2','26FA','1F301','1F303','1F3D9','1F304','1F305','1F306','1F307','1F309','2668','1F3A0','1F3A1','1F3A2','1F488','1F3AA','1F682','1F683','1F684','1F685','1F686','1F687','1F688','1F689','1F68A','1F69D','1F69E','1F68B','1F68C','1F68D','1F68E','1F690','1F691','1F692','1F693','1F694','1F695','1F696','1F697','1F698','1F699','1F69A','1F69B','1F69C','1F3CE','1F3CD','1F6F5','1F9BD','1F9BC','1F6FA','1F6B2','1F6F4','1F6F9','1F68F','1F6E3','1F6E4','1F6E2','26FD','1F6A8','1F6A5','1F6A6','1F6D1','1F6A7','2693','26F5','1F6F6','1F6A4','1F6F3','26F4','1F6E5','1F6A2','2708','1F6E9','1F6EB','1F6EC','1FA82','1F4BA','1F681','1F69F','1F6A0','1F6A1','1F6F0','1F680','1F6F8','1F6CE','1F9F3','231B','23F3','231A','23F0','23F1','23F2','1F570','1F55B','1F567','1F550','1F55C','1F551','1F55D','1F552','1F55E','1F553','1F55F','1F554','1F560','1F555','1F561','1F556','1F562','1F557','1F563','1F558','1F564','1F559','1F565','1F55A','1F566','1F311','1F312','1F313','1F314','1F315','1F316','1F317','1F318','1F319','1F31A','1F31B','1F31C','1F321','2600','1F31D','1F31E','1FA90','2B50','1F31F','1F320','1F30C','2601','26C5','26C8','1F324','1F325','1F326','1F327','1F328','1F329','1F32A','1F32B','1F32C','1F300','1F308','1F302','2602','2614','26F1','26A1','2744','2603','26C4','2604','1F525','1F4A7','1F30A','1F383','1F384','1F386','1F387','1F9E8','2728','1F388','1F389','1F38A','1F38B','1F38D','1F38E','1F38F','1F390','1F391','1F9E7','1F380','1F381','1F397','1F39F','1F3AB','1F396','1F3C6','1F3C5','1F947','1F948','1F949','26BD','26BE','1F94E','1F3C0','1F3D0','1F3C8','1F3C9','1F3BE','1F94F','1F3B3','1F3CF','1F3D1','1F3D2','1F94D','1F3D3','1F3F8','1F94A','1F94B','1F945','26F3','26F8','1F3A3','1F93F','1F3BD','1F3BF','1F6F7','1F94C','1F3AF','1FA80','1FA81','1F3B1','1F52E','1F9FF','1F3AE','1F579','1F3B0','1F3B2','1F9E9','1F9F8','2660','2665','2666','2663','265F','1F0CF','1F004','1F3B4','1F3AD','1F5BC','1F3A8','1F9F5','1F9F6','1F453','1F576','1F97D','1F97C','1F9BA','1F454','1F455','1F456','1F9E3','1F9E4','1F9E5','1F9E6','1F457','1F458','1F97B','1FA71','1FA72','1FA73','1F459','1F45A','1F45B','1F45C','1F45D','1F6CD','1F392','1F45E','1F45F','1F97E','1F97F','1F460','1F461','1FA70','1F462','1F451','1F452','1F3A9','1F393','1F9E2','26D1','1F4FF','1F484','1F48D','1F48E','1F507','1F508','1F509','1F50A','1F4E2','1F4E3','1F4EF','1F514','1F515','1F3BC','1F3B5','1F3B6','1F399','1F39A','1F39B','1F3A4','1F3A7','1F4FB','1F3B7','1F3B8','1F3B9','1F3BA','1F3BB','1FA95','1F941','1F4F1','1F4F2','260E','1F4DE','1F4DF','1F4E0','1F50B','1F50C','1F4BB','1F5A5','1F5A8','2328','1F5B1','1F5B2','1F4BD','1F4BE','1F4BF','1F4C0','1F9EE','1F3A5','1F39E','1F4FD','1F3AC','1F4FA','1F4F7','1F4F8','1F4F9','1F4FC','1F50D','1F50E','1F56F','1F4A1','1F526','1F3EE','1FA94','1F4D4','1F4D5','1F4D6','1F4D7','1F4D8','1F4D9','1F4DA','1F4D3','1F4D2','1F4C3','1F4DC','1F4C4','1F4F0','1F5DE','1F4D1','1F516','1F3F7','1F4B0','1F4B4','1F4B5','1F4B6','1F4B7','1F4B8','1F4B3','1F9FE','1F4B9','1F4B1','1F4B2','2709','1F4E7','1F4E8','1F4E9','1F4E4','1F4E5','1F4E6','1F4EB','1F4EA','1F4EC','1F4ED','1F4EE','1F5F3','270F','2712','1F58B','1F58A','1F58C','1F58D','1F4DD','1F4BC','1F4C1','1F4C2','1F5C2','1F4C5','1F4C6','1F5D2','1F5D3','1F4C7','1F4C8','1F4C9','1F4CA','1F4CB','1F4CC','1F4CD','1F4CE','1F587','1F4CF','1F4D0','2702','1F5C3','1F5C4','1F5D1','1F512','1F513','1F50F','1F510','1F511','1F5DD','1F528','1FA93','26CF','2692','1F6E0','1F5E1','2694','1F52B','1F3F9','1F6E1','1F527','1F529','2699','1F5DC','2696','1F9AF','1F517','26D3','1F9F0','1F9F2','2697','1F9EA','1F9EB','1F9EC','1F52C','1F52D','1F4E1','1F489','1FA78','1F48A','1FA79','1FA7A','1F6AA','1F6CF','1F6CB','1FA91','1F6BD','1F6BF','1F6C1','1FA92','1F9F4','1F9F7','1F9F9','1F9FA','1F9FB','1F9FC','1F9FD','1F9EF','1F6D2','1F6AC','26B0','26B1','1F5FF','1F3E7','1F6AE','1F6B0','267F','1F6B9','1F6BA','1F6BB','1F6BC','1F6BE','1F6C2','1F6C3','1F6C4','1F6C5','26A0','1F6B8','26D4','1F6AB','1F6B3','1F6AD','1F6AF','1F6B1','1F6B7','1F4F5','1F51E','2622','2623','2B06','2197','27A1','2198','2B07','2199','2B05','2196','2195','2194','21A9','21AA','2934','2935','1F503','1F504','1F519','1F51A','1F51B','1F51C','1F51D','1F6D0','269B','1F549','2721','2638','262F','271D','2626','262A','262E','1F54E','1F52F','2648','2649','264A','264B','264C','264D','264E','264F','2650','2651','2652','2653','26CE','1F500','1F501','1F502','25B6','23E9','23ED','23EF','25C0','23EA','23EE','1F53C','23EB','1F53D','23EC','23F8','23F9','23FA','23CF','1F3A6','1F505','1F506','1F4F6','1F4F3','1F4F4','2640','2642','2695','267E','267B','269C','1F531','1F4DB','1F530','2B55','2705','2611','2714','2716','274C','274E','2795','2796','2797','27B0','27BF','303D','2733','2734','2747','203C','2049','2753','2754','2755','2757','3030','00A9','00AE','2122','0023','FE0F','20E3','002A','FE0F','20E3','0030','FE0F','20E3','0031','FE0F','20E3','0032','FE0F','20E3','0033','FE0F','20E3','0034','FE0F','20E3','0035','FE0F','20E3','0036','FE0F','20E3','0037','FE0F','20E3','0038','FE0F','20E3','0039','FE0F','20E3','1F51F','1F520','1F521','1F522','1F523','1F524','1F170','1F18E','1F171','1F191','1F192','1F193','2139','1F194','24C2','1F195','1F196','1F17E','1F197','1F17F','1F198','1F199','1F19A','1F201','1F202','1F237','1F236','1F22F','1F250','1F239','1F21A','1F232','1F251','1F238','1F234','1F233','3297','3299','1F23A','1F235','1F534','1F7E0','1F7E1','1F7E2','1F535','1F7E3','1F7E4','26AB','26AA','1F7E5','1F7E7','1F7E8','1F7E9','1F7E6','1F7EA','1F7EB','2B1B','2B1C','25FC','25FB','25FE','25FD','25AA','25AB','1F536','1F537','1F538','1F539','1F53A','1F53B','1F4A0','1F518','1F533','1F532','1F3C1','1F6A9','1F38C','1F3F4','1F3F3','1F3F3','FE0F','200D','1F308','1F3F4','200D','2620','FE0F','1F1E6','1F1E8','1F1E6','1F1E9','1F1E6','1F1EA','1F1E6','1F1EB','1F1E6','1F1EC','1F1E6','1F1EE','1F1E6','1F1F1','1F1E6','1F1F2','1F1E6','1F1F4','1F1E6','1F1F6','1F1E6','1F1F7','1F1E6','1F1F8','1F1E6','1F1F9','1F1E6','1F1FA','1F1E6','1F1FC','1F1E6','1F1FD','1F1E6','1F1FF','1F1E7','1F1E6','1F1E7','1F1E7','1F1E7','1F1E9','1F1E7','1F1EA','1F1E7','1F1EB','1F1E7','1F1EC','1F1E7','1F1ED','1F1E7','1F1EE','1F1E7','1F1EF','1F1E7','1F1F1','1F1E7','1F1F2','1F1E7','1F1F3','1F1E7','1F1F4','1F1E7','1F1F6','1F1E7','1F1F7','1F1E7','1F1F8','1F1E7','1F1F9','1F1E7','1F1FB','1F1E7','1F1FC','1F1E7','1F1FE','1F1E7','1F1FF','1F1E8','1F1E6','1F1E8','1F1E8','1F1E8','1F1E9','1F1E8','1F1EB','1F1E8','1F1EC','1F1E8','1F1ED','1F1E8','1F1EE','1F1E8','1F1F0','1F1E8','1F1F1','1F1E8','1F1F2','1F1E8','1F1F3','1F1E8','1F1F4','1F1E8','1F1F5','1F1E8','1F1F7','1F1E8','1F1FA','1F1E8','1F1FB','1F1E8','1F1FC','1F1E8','1F1FD','1F1E8','1F1FE','1F1E8','1F1FF','1F1E9','1F1EA','1F1E9','1F1EC','1F1E9','1F1EF','1F1E9','1F1F0','1F1E9','1F1F2','1F1E9','1F1F4','1F1E9','1F1FF','1F1EA','1F1E6','1F1EA','1F1E8','1F1EA','1F1EA','1F1EA','1F1EC','1F1EA','1F1ED','1F1EA','1F1F7','1F1EA','1F1F8','1F1EA','1F1F9','1F1EA','1F1FA','1F1EB','1F1EE','1F1EB','1F1EF','1F1EB','1F1F0','1F1EB','1F1F2','1F1EB','1F1F4','1F1EB','1F1F7','1F1EC','1F1E6','1F1EC','1F1E7','1F1EC','1F1E9','1F1EC','1F1EA','1F1EC','1F1EB','1F1EC','1F1EC','1F1EC','1F1ED','1F1EC','1F1EE','1F1EC','1F1F1','1F1EC','1F1F2','1F1EC','1F1F3','1F1EC','1F1F5','1F1EC','1F1F6','1F1EC','1F1F7','1F1EC','1F1F8','1F1EC','1F1F9','1F1EC','1F1FA','1F1EC','1F1FC','1F1EC','1F1FE','1F1ED','1F1F0','1F1ED','1F1F2','1F1ED','1F1F3','1F1ED','1F1F7','1F1ED','1F1F9','1F1ED','1F1FA','1F1EE','1F1E8','1F1EE','1F1E9','1F1EE','1F1EA','1F1EE','1F1F1','1F1EE','1F1F2','1F1EE','1F1F3','1F1EE','1F1F4','1F1EE','1F1F6','1F1EE','1F1F7','1F1EE','1F1F8','1F1EE','1F1F9','1F1EF','1F1EA','1F1EF','1F1F2','1F1EF','1F1F4','1F1EF','1F1F5','1F1F0','1F1EA','1F1F0','1F1EC','1F1F0','1F1ED','1F1F0','1F1EE','1F1F0','1F1F2','1F1F0','1F1F3','1F1F0','1F1F5','1F1F0','1F1F7','1F1F0','1F1FC','1F1F0','1F1FE','1F1F0','1F1FF','1F1F1','1F1E6','1F1F1','1F1E7','1F1F1','1F1E8','1F1F1','1F1EE','1F1F1','1F1F0','1F1F1','1F1F7','1F1F1','1F1F8','1F1F1','1F1F9','1F1F1','1F1FA','1F1F1','1F1FB','1F1F1','1F1FE','1F1F2','1F1E6','1F1F2','1F1E8','1F1F2','1F1E9','1F1F2','1F1EA','1F1F2','1F1EB','1F1F2','1F1EC','1F1F2','1F1ED','1F1F2','1F1F0','1F1F2','1F1F1','1F1F2','1F1F2','1F1F2','1F1F3','1F1F2','1F1F4','1F1F2','1F1F5','1F1F2','1F1F6','1F1F2','1F1F7','1F1F2','1F1F8','1F1F2','1F1F9','1F1F2','1F1FA','1F1F2','1F1FB','1F1F2','1F1FC','1F1F2','1F1FD','1F1F2','1F1FE','1F1F2','1F1FF','1F1F3','1F1E6','1F1F3','1F1E8','1F1F3','1F1EA','1F1F3','1F1EB','1F1F3','1F1EC','1F1F3','1F1EE','1F1F3','1F1F1','1F1F3','1F1F4','1F1F3','1F1F5','1F1F3','1F1F7','1F1F3','1F1FA','1F1F3','1F1FF','1F1F4','1F1F2','1F1F5','1F1E6','1F1F5','1F1EA','1F1F5','1F1EB','1F1F5','1F1EC','1F1F5','1F1ED','1F1F5','1F1F0','1F1F5','1F1F1','1F1F5','1F1F2','1F1F5','1F1F3','1F1F5','1F1F7','1F1F5','1F1F8','1F1F5','1F1F9','1F1F5','1F1FC','1F1F5','1F1FE','1F1F6','1F1E6','1F1F7','1F1EA','1F1F7','1F1F4','1F1F7','1F1F8','1F1F7','1F1FA','1F1F7','1F1FC','1F1F8','1F1E6','1F1F8','1F1E7','1F1F8','1F1E8','1F1F8','1F1E9','1F1F8','1F1EA','1F1F8','1F1EC','1F1F8','1F1ED','1F1F8','1F1EE','1F1F8','1F1EF','1F1F8','1F1F0','1F1F8','1F1F1','1F1F8','1F1F2','1F1F8','1F1F3','1F1F8','1F1F4','1F1F8','1F1F7','1F1F8','1F1F8','1F1F8','1F1F9','1F1F8','1F1FB','1F1F8','1F1FD','1F1F8','1F1FE','1F1F8','1F1FF','1F1F9','1F1E6','1F1F9','1F1E8','1F1F9','1F1E9','1F1F9','1F1EB','1F1F9','1F1EC','1F1F9','1F1ED','1F1F9','1F1EF','1F1F9','1F1F0','1F1F9','1F1F1','1F1F9','1F1F2','1F1F9','1F1F3','1F1F9','1F1F4','1F1F9','1F1F7','1F1F9','1F1F9','1F1F9','1F1FB','1F1F9','1F1FC','1F1F9','1F1FF','1F1FA','1F1E6','1F1FA','1F1EC','1F1FA','1F1F2','1F1FA','1F1F3','1F1FA','1F1F8','1F1FA','1F1FE','1F1FA','1F1FF','1F1FB','1F1E6','1F1FB','1F1E8','1F1FB','1F1EA','1F1FB','1F1EC','1F1FB','1F1EE','1F1FB','1F1F3','1F1FB','1F1FA','1F1FC','1F1EB','1F1FC','1F1F8','1F1FD','1F1F0','1F1FE','1F1EA','1F1FE','1F1F9','1F1FF','1F1E6','1F1FF','1F1F2','1F1FF','1F1FC','1F3F4','E0067','E0062','E0065','E006E','E0067','E007F','1F3F4','E0067','E0062','E0073','E0063','E0074','E007F','1F3F4','E0067','E0062','E0077','E006C','E0073','E007F' ); return preg_match( '/[\x{' . implode( '}\x{', $unicodes ) . '}]/u', $string ) ? true : false; } </code></pre>
3
12,146
Pattern matching case when
<p>I write simple math tokenizer and try to use new C# <code>pattern matching</code> feature.</p> <p>Tokenizer is quite simple:</p> <pre><code> public IEnumerable&lt;IToken&gt; Tokenize(string input) { const char decimalSeparator = '.'; string inputWithoutSpaces = input.Replace(" ", string.Empty); var numberBuffer = new StringBuilder(); var letterBuffer = new StringBuilder(); foreach (char c in inputWithoutSpaces) { switch (c) { case var _ when IsTerm(c, letterBuffer): if (numberBuffer.Length &gt; 0) { yield return EmptyNumberBufferAsLiteral(numberBuffer); yield return new Operator('*'); } letterBuffer.Append(c); break; case decimalSeparator: case var _ when IsDigit(c): numberBuffer.Append(c); break; case var _ when IsOperator(c): if (numberBuffer.Length &gt; 0) { yield return EmptyNumberBufferAsLiteral(numberBuffer); } if (letterBuffer.Length &gt; 0) { yield return EmptyLetterBufferAsTerm(letterBuffer); } yield return new Operator(c); break; } } if (numberBuffer.Length &gt; 0) { yield return EmptyNumberBufferAsLiteral(numberBuffer); } if (letterBuffer.Length &gt; 0) { yield return EmptyLetterBufferAsTerm(letterBuffer); } } </code></pre> <p>I'm using <code>case var _</code> because I want to match by condition without using <code>if-else if</code> chain, but I'm unable to write <code>case when</code> without specifying <code>var variableName</code>. </p> <p>Is there any fancy way to perform such operation? Or it is recommended way to do these things?</p>
3
1,069
Java Websocket client lib issue: nv-websocket-client sendBinary
<p>When using sendBinary of this lib from client I got all 0 in the server ;(</p> <p>this page asks me to to add more description but the code bellow is simple and straight forward and should be self explainable...</p> <p>client side code:</p> <pre><code>private WebSocket connect() throws IOException, WebSocketException { return new WebSocketFactory() .setConnectionTimeout(5000) .createSocket("ws://localhost:8080/testwsapp2/endpoint") .addListener(new WebSocketAdapter() { public void onBinaryMessage(WebSocket websocket, byte[] message) { String strmsg = new String(message, StandardCharsets.US_ASCII); System.out.println("message from server: " + strmsg); //echo back try { strmsg = "echo: " + strmsg; System.out.println("now echo back with \"" + strmsg + "\""); byte[] bytemsg = strmsg.getBytes("US-ASCII"); System.out.println("echo message length = " + bytemsg.length); String a2sview = Arrays.toString(bytemsg); System.out.println("echo message a2sview: " + a2sview); websocket.sendBinary(bytemsg); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }) .addExtension(WebSocketExtension.PERMESSAGE_DEFLATE) .connect(); } </code></pre> <p>server side code:</p> <pre><code>@OnOpen public void on_open(Session session) { try { byte[] bytemsg = ("hello client").getBytes("US-ASCII"); session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytemsg)); } catch (Exception ex) { System.out.println(ex.getMessage()); } } @OnMessage public void on_message(Session session, ByteBuffer message) { byte[] bytemsg = new byte[message.remaining()]; System.out.println("client message length = " + bytemsg.length); String a2sview = Arrays.toString(bytemsg); System.out.println("client message a2sview: " + a2sview); String strmsg = new String(bytemsg, StandardCharsets.US_ASCII); System.out.println("client message: " + strmsg); } </code></pre> <p>client output:</p> <pre><code>message from server: hello client now echo back with "echo: hello client" echo message length = 18 echo message a2sview: [101, 99, 104, 111, 58, 32, 104, 101, 108, 108, 111, 32, 99, 108, 105, 101, 110, 116] </code></pre> <p>server output</p> <pre><code>Info: client message length = 18 Info: client message a2sview: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Info: client message: </code></pre> <p>Thank you very much for help.</p>
3
1,282