title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
vue.js select2 multiple select
<p>For many days I've searched to find an answer to this error. I tried many alternatives but nothing worked. </p> <p>I need to select multiple values. When I select multiple values, my code hangs, but when I use a single select it works well with <code>self.$emit('input', this.value)</code>. What I need is to select multiple values.</p> <p><strong>Select2.vue</strong></p> <pre><code>&lt;template&gt; &lt;select multiple class="input-sm" :name="name"&gt; &lt;slot&gt;&lt;/slot&gt; &lt;/select&gt; &lt;/template&gt; &lt;style src="select2/dist/css/select2.min.css"&gt;&lt;/style&gt; &lt;style src="select2-bootstrap-theme/dist/select2-bootstrap.min.css"&gt;&lt;/style&gt; &lt;script&gt; import Select2 from 'select2'; export default{ twoWay: true, priority: 1000, props: ['options', 'value', 'name'], data(){ return{ msg: 'hello' } }, mounted(){ var self = this; $(this.$el) .select2({theme: "bootstrap", data: this.options}) .val(this.value) .trigger('change') .on('change', function () { //self.$emit('input', this.value) //single select worked good self.$emit('input', $(this).val()) // multiple select }) }, watch: { value: function (value) { $(this.$el).val(value).trigger('change'); }, options: function (options) { $(this.$el).select2({ data: options }) } }, destroyed: function () { $(this.$el).off().select2('destroy') } } &lt;/script&gt; </code></pre> <p><strong>new.vue</strong></p> <pre><code> &lt;p&gt;Selected: {{ model.users_id }}&lt;/p&gt; &lt;select2 :options="options" v-model="model.users_id" name="options[]" style="width: 1000px; height: 1em;" class="form-control"&gt; &lt;option value="0"&gt;default&lt;/option&gt; &lt;/select2&gt; export default { data(){ return { model: { 'users_id': [], }, options: [], components:{ 'select2': Select2 }, </code></pre>
0
1,194
Querying and Filtering Array of JObjects with Linq
<p>I suppose this is another entry in my series of questions, but I'm stuck again. This time, I'm having trouble working with a JArray of JObjects and determining the Property.Value type for each element in the JArray... </p> <p>My code is here: <a href="https://dotnetfiddle.net/bRcSAQ" rel="nofollow">https://dotnetfiddle.net/bRcSAQ</a></p> <p>The difference between my previous questions and this question is that my outer Linq query gets both JObject and JArray tokens, so that's why I have an <code>if (jo is JObject)</code> at Line 40 and a <code>if (jo is JArray)</code> at Line 48. </p> <p>Once I know I have a JArray of <code>&lt;JObjects&gt;</code>, I have code that looks like this (Lines 48-):</p> <pre><code> if (jo is JArray) { var items = jo.Children&lt;JObject&gt;(); // return a JObject object } </code></pre> <p>When I use a debugger and look at items, I see that it contains 3 JObject objects--one for Item_3A1, Item_3A2, and Item3A3. But I need to know the JTokenType for each JProperty.Value because I am interested only in Property values of type JTokenType.String.</p> <p>So I tried:</p> <pre><code>// doesn't work :( var items = jo.Children&lt;JObject&gt;() .Where(p =&gt; p.Value.Type == JTokenType.String); </code></pre> <p>The compiler red-lines the Value property with the error <code>CS0119 'JToken.Value&lt;T&gt;(object)' is a method, which is not valid in the given context.</code></p> <p>I realize that "p" in the Linq express is not a JProperty. I guess it's a JObject. And I don't know how to cast "p" so that I can examine the type of JProperty object it represents. </p> <p>Ultimately, I need the code for JArray processing (starting at Line 48) to add an return a JObject that contains an JSON array composed only of JProperty objects of type JTokenType.String. This means that given the sample JSON, it first should return a JObject holding these JSON properties:</p> <pre><code>{ ""Item_3A1"": ""Desc_3A1"" }, { ""Item_3A2"": ""Desc_3A2"" }, { ""Item_3A3"": ""Desc_3A3"" } </code></pre> <p>On the next iteration, it should return a JObject holding these JSON properties (notice that the nested Array3B1 properties are omitted because Array3B1 is not a JProperty with a Value type of JTokenType.String):</p> <pre><code>{ ""Item_3B1"": ""Desc_3B1"" }, { ""Item_3B2"": ""Desc_3B2"" }, </code></pre> <p>The third iteration would contain:</p> <pre><code>{ ""Item_3B11"": ""Desc_3B11"" }, { ""Item_3B12"": ""Desc_3B12"" }, { ""Item_3B13"": ""Desc_3B13"" } </code></pre> <p>And the fourth (final) iteration would contain:</p> <pre><code>{ ""Item_3C1"": ""Desc_3C1"" }, { ""Item_3C2"": ""Desc_3C2"" }, { ""Item_3C3"": ""Desc_3C3"" } </code></pre> <p>This might be my final hurdle in this "series". </p> <p>Sincere thanks to anyone who can and will help--and a special thanks again to users "Brian Rogers" and "dbc" for their truly amazing JSON.NET/Linq knowledge.</p>
0
1,072
android: device not supported by app- why?
<p>I am currently developing a camera app. Now one of the users is complaining that his device is not supported. It's a <a href="http://www.specsbox.com/819/acer-iconia-a200-tablet.html" rel="noreferrer">Acer A200</a>:</p> <p>I don't see any reason why android market / google play marks the app as <strong>not supported</strong> for this device. Do you know what might be the reason?</p> <p>Here is the manifest:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.ttttrash.myapp" android:versionCode="32" android:versionName="3.2" &gt; &lt;application android:icon="@drawable/icon" android:label="@string/app_name" android:hardwareAccelerated="true"&gt; &lt;activity android:name=".CameraActivity" android:configChanges="keyboard|orientation|keyboardHidden" android:label="@string/app_name" android:windowSoftInputMode="adjustPan" &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;intent-filter&gt; &lt;action android:name="android.media.action.IMAGE_CAPTURE" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="net.ttttrash.myapp.PreferenceActivity" android:label="@string/set_preferences" &gt; &lt;/activity&gt; &lt;activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"&gt; &lt;/activity&gt; &lt;/application&gt; &lt;uses-sdk android:minSdkVersion="7" android:targetSdkVersion="8" /&gt; &lt;uses-permission android:name="android.permission.CAMERA" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;uses-feature android:name="android.hardware.camera.autofocus" android:required="false" /&gt; &lt;/manifest&gt; </code></pre>
0
1,090
getActivity() / context in a ViewHolder in Kotlin Android
<p>I'm building a ViewHolder and Adapter for a Fragment and when I try to make an OnClick for the ViewHolder, none of the contexts I pass in work. There is no <code>activity</code> from <code>getActivity()</code> that I can use, and <code>p0!!.context</code> nor <code>itemView.context</code> work either. Where should I be getting my context from, and how do I reference it?</p> <pre><code>package com._________.criminalintent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast class CrimeListFragment: Fragment() { private var mCrimeRecyclerView: RecyclerView? = null private var mAdapter: CrimeAdapter? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // fragment_crime_list.xml has a RecyclerView element = crime_recycler_view // inflate the fragment into the activity val view = inflater!!.inflate(R.layout.fragment_crime_list, container, false) // grab the recyclerView and give it a required layoutManager mCrimeRecyclerView = view.findViewById(R.id.crime_recycler_view) mCrimeRecyclerView!!.layoutManager = LinearLayoutManager(activity) updateUI() return view } private fun updateUI() { val crimeLab = CrimeLab.get(activity) val crimes = crimeLab.getCrimes() mAdapter = CrimeAdapter(crimes) // Connect the adapter to the recyclerView mCrimeRecyclerView!!.adapter = mAdapter } /** * in Kotlin, we must give the view passed into the constructor directly * as a substitute for a super() call * * create a ViewHolder that holders the crime list item's view * * super(itemView) = super(inflater!!.inflate(R.layout.list_item_crime, parent, false)) * MUST give it the direct value in Kotlin */ private class CrimeHolder(inflater: LayoutInflater?, parent: ViewGroup): RecyclerView.ViewHolder(inflater!!.inflate(R.layout.list_item_crime, parent, false)), View.OnClickListener { private var mCrime: Crime? = null /** * When given a crime, this CrimeHolder will update the title and date for this Crime */ fun bind(crime: Crime) { mCrime = crime val titleTextView = itemView.findViewById&lt;TextView&gt;(R.id.crime_title) val dateTextView = itemView.findViewById&lt;TextView&gt;(R.id.crime_date) titleTextView.text = mCrime!!.mTitle dateTextView.text = mCrime!!.mDate.toString() } override fun onClick(p0: View?) { Toast.makeText(WHAT_TO_PUT_HERE, "${mCrime!!.mTitle} clicked!", Toast.LENGTH_SHORT / 2) .show() } } private class CrimeAdapter(private var mCrimes: MutableList&lt;Crime&gt;): RecyclerView.Adapter&lt;CrimeHolder&gt;() { /** * - Calls our CrimeHolder to make our custom ViewHolders * - Called by RecyclerView when it needs a new view to display * - Gets the layoutInflater from the ViewGroup and returns a CrimeHolder of it */ override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CrimeHolder = CrimeHolder(LayoutInflater.from(parent!!.context), parent) /** * Bind the crime (data) to the CrimeHolder */ override fun onBindViewHolder(holder: CrimeHolder?, position: Int) { holder!!.bind(mCrimes[position]) } /** * Sees how many items are in the RecyclerView that need to be shown */ override fun getItemCount(): Int = mCrimes.size } } </code></pre>
0
1,515
How to add a checkbox in a Material Design table in Angular 4
<p>I would like to add a checkbox in a Material Design table in Angular 4, it would be under the column Publish. The problem is that the checkbox doesn't show in the table just the text with and error message </p> <p>"No value accessor for form control with unspecified name attribute" <a href="https://i.stack.imgur.com/BiCwd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BiCwd.png" alt=""></a></p> <p>Here is my code:</p> <pre><code>&lt;div class="mat-table-container mat-elevation-z8"&gt; &lt;mat-table #table [dataSource]="assessmentManualList"&gt; &lt;ng-container cdkColumnDef="documentID"&gt; &lt;mat-header-cell *cdkHeaderCellDef&gt; &lt;/mat-header-cell&gt; &lt;mat-cell *cdkCellDef="let row"&gt; &lt;button mat-icon-button [matMenuTriggerFor]="menu"&gt; &lt;mat-icon&gt;more_vert&lt;/mat-icon&gt; &lt;/button&gt; &lt;mat-menu #menu="matMenu"&gt; &lt;button mat-menu-item&gt; &lt;mat-icon&gt;&lt;i class="material-icons"&gt;content_copy&lt;/i&gt;&lt;/mat-icon&gt; &lt;span&gt;Copy {{row.DocumentID}}&lt;/span&gt; &lt;/button&gt; &lt;button mat-menu-item&gt; &lt;mat-icon&gt;&lt;i class="fa fa-trash" aria-hidden="true"&gt;&lt;/i&gt;&lt;/mat-icon&gt; &lt;span&gt;Delete {{row.documentID}}&lt;/span&gt; &lt;/button&gt; &lt;/mat-menu&gt; &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;ng-container cdkColumnDef="textDetail"&gt; &lt;mat-header-cell *cdkHeaderCellDef&gt; Document &lt;/mat-header-cell&gt; &lt;mat-cell *cdkCellDef="let row"&gt; {{row.textDetail}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;ng-container cdkColumnDef="isPublish"&gt; &lt;mat-header-cell *cdkHeaderCellDef&gt; Publish &lt;/mat-header-cell&gt; &lt;mat-cell *cdkCellDef="let row"&gt; {{row.isPublish}} &lt;md-checkbox class="example-margin" [(ngModel)]="row.isPublish"&gt; Checked &lt;/md-checkbox&gt; &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;mat-header-row *cdkHeaderRowDef="displayedColumns"&gt;&lt;/mat-header-row&gt; &lt;mat-row *cdkRowDef="let row; columns: displayedColumns;" (click)="selectedRow(row)" [class.active]="isSelected(row)"&gt;&lt;/mat-row&gt; &lt;/mat-table&gt; &lt;/div&gt; </code></pre>
0
1,132
Rake db:test:prepare task deleting data in development database
<p>Using a <a href="https://github.com/mhartl/sample_app_rails_3_2/blob/master/config/database.yml" rel="nofollow noreferrer">simple Rails sqlite3 configuration example</a> in my <strong>config/database.yml</strong> for a Rails 3.2.6 app, I used to reset my development database, re-seed it, and prepare my test database simply by performing:</p> <pre><code>$ rake db:reset $ rake db:test:prepare </code></pre> <p>After looking at <a href="https://web.archive.org/web/20120924203633/http://matthew.mceachen.us:80/blog/howto-test-your-rails-application-with-travis-ci-on-different-database-engines-1220.html" rel="nofollow noreferrer">this blog entry</a> about testing a Rails application with <a href="https://travis-ci.org/" rel="nofollow noreferrer">Travis CI</a> on different database engines, I thought I'd give it a try, so I installed mysql and postgresql using <a href="https://brew.sh/" rel="nofollow noreferrer">Homebrew</a> (I'm on OSX Snow Leopard), set them up as per the <code>brew info</code> instructions. I installed the relevant gems, and configured the database and Travis files as follows:</p> <p><strong>Gemfile</strong></p> <pre><code># ... group :development, :test do # ... gem 'sqlite3', '1.3.6' end group :test do # ... # Test mysql on Travis CI gem 'mysql2', '0.3.11' end group :test, :production do # ... # Test postgres on Travis CI and deploy on Heroku gem 'pg', '0.13.2' end </code></pre> <p><strong>config/database.yml</strong></p> <pre><code>sqlite: &amp;sqlite adapter: sqlite3 database: db/&lt;%= Rails.env %&gt;.sqlite3 mysql: &amp;mysql adapter: mysql2 username: root password: database: my_app_&lt;%= Rails.env %&gt; postgresql: &amp;postgresql adapter: postgresql username: postgres password: database: my_app_&lt;%= Rails.env %&gt; min_messages: ERROR defaults: &amp;defaults pool: 5 timeout: 5000 host: localhost &lt;&lt;: *&lt;%= ENV['DB'] || &quot;sqlite&quot; %&gt; development: &lt;&lt;: *defaults test: &amp;test &lt;&lt;: *defaults production: &lt;&lt;: *defaults cucumber: &lt;&lt;: *test </code></pre> <p><strong>.travis.yml</strong></p> <pre><code>language: ruby rvm: - 1.9.2 - 1.9.3 env: - DB=sqlite - DB=mysql - DB=postgresql script: - RAILS_ENV=test bundle exec rake --trace db:migrate - bundle exec rake db:test:prepare - bundle exec rspec spec/ before_script: - mysql -e 'create database my_app_test' - psql -c 'create database my_app_test' -U postgres bundler_args: --binstubs=./bundler_stubs </code></pre> <p>Now, though, when I run <code>rake db:reset</code>, I get a <code>Couldn't drop db/development.sqlite3</code> error message before the development database is successfully created. So, it seems that there are now multiple calls being made to drop the same database(?). The traced output looks like:</p> <pre><code>$ rake db:reset --trace ** Invoke db:reset (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:reset ** Invoke db:drop (first_time) ** Invoke db:load_config (first_time) ** Invoke rails_env (first_time) ** Execute rails_env ** Execute db:load_config ** Execute db:drop Couldn't drop db/development.sqlite3 : #&lt;Errno::ENOENT: No such file or directory - my_app/db/development.sqlite3&gt; ** Invoke db:setup (first_time) ** Invoke db:schema:load_if_ruby (first_time) ** Invoke db:create (first_time) ** Invoke db:load_config ** Execute db:create db/development.sqlite3 already exists # ... </code></pre> <p>This is odd, but at least the development database gets created and seeded. The real issue comes when I run <code>rake db:test:prepare</code>: although there are no error messages, as well as the test database not being created, the data in the development database gets blown away (schema is still in tact, though). I tried directly specifying the Rails environment for the command and got:</p> <pre><code>$ rake db:test:prepare RAILS_ENV=test You have 7 pending migrations: 20120503193649 CreateUsers # ... Run `rake db:migrate` to update your database then try again. </code></pre> <p>After running <code>rake db:migrate RAILS_ENV=test</code>, I could run my rspec tests again. So, my rake commands to get the same results have now changed to:</p> <pre><code>$ rake db:reset # (with an error) $ rake db:migrate RAILS_ENV=test </code></pre> <p><em>If I change my</em> <strong>config/database.yml</strong> <em>file back to a simple sqlite3 only configuration,</em> <code>db:reset</code> <em>and</em> <code>db:test:prepare</code> <em>work as I expect.</em></p> <p>So, does this mean that my mysql and/or postgres settings are causing rake tasks to repeat and/or they're messing with the Rails environment settings? Where should I be looking to confirm if my environment is really set up to work properly with these 3 database engines?</p> <h3>Edit</h3> <p>Looking at the <a href="https://weblog.rubyonrails.org/2012/8/3/ann-rails-3-2-8-rc2-has-been-released/" rel="nofollow noreferrer">release notes for Rails 3.2.8.rc2</a>, I found a change to <code>ActiveRecord</code> potentially related to this question:</p> <ul> <li>Do not set <code>RAILS_ENV</code> to <code>development</code> when using <code>db:test:prepare</code> and related rake tasks. This was causing the truncation of the development database data when using RSpec. In RC2 was fixed again when using <code>config.active_record.schema_format = :sql</code></li> </ul> <p><strong>config/application.rb</strong> has the following explanation:</p> <pre><code># Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql </code></pre> <p>My schema doesn't have constraints or database-specific column types, so I didn't uncomment this line, however, given the content of the release note, I wagered that <code>RAILS_ENV</code> defaulting to <code>development</code> could be responsible for the deleted data in the development environment. So, I tried out a few things and got expected results by doing what I did before (after upgrading Rails to 3.2.8.rc2):</p> <pre><code>$ rake db:reset # (with an error) $ rake db:test:prepare RAILS_ENV=test # (with no &quot;pending migrations&quot; issue) </code></pre> <p>This is a bit better, but still seems wrong to me since there is still an error with <code>rake db:reset</code>, and it doesn't make sense to me to have to set <code>RAILS_ENV=test</code> when running a rake command specifically tailored for the test database.</p> <h2>Update</h2> <p>It would seem that upgrading to Rails 3.2.9 solves this issue due to the following fix:</p> <ul> <li>Fix bug where <code>rake db:test:prepare</code> tries to load the structure.sql into development database. Fixes #8032.</li> </ul> <p><em>Grace Liu + Rafael Mendonça França</em></p> <p>I can now again reset my development database, re-seed it, and prepare my test database simply by performing:</p> <pre><code>$ rake db:reset $ rake db:test:prepare </code></pre>
0
2,388
English to Morse Converter
<p>I've been working on a program that is supposed to convert english to morse code. I am having a really hard time dealing with the strings. For example I have no clue why I can have morseAlphabet have a set number of positions at [30] but I cannot do the same for latinAlphabet. Overall I have no clue how I am supposed to translate the words.</p> <p>My idea was to see what character in the alphabet shows up in the first position of the phrase to be translated then print the corresponding alphabet position for the morse alphabet then move onto the second position in the phrase however me messing around with for loops just ended with me getting errors about for loops getting far too huge and memory errors or just gave me a blank.</p> <p>With what I have right now whenever I enter the phrase to be translated it comes stops with a subscript out of range error and some of my earlier fiddling had it return jibberish(memory locations?) and I am really just out of ideas. I hope that this is phrased right and someone can help me because the past four hours of internet searches hasn't really helped me and to be honest at this point I am doubting if any of the stuff I've written is any use at all.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; int main() { int operatingMode = 0; using namespace std; std::string latinPhrase; std::string morsePhrase; std::string latinAlphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '.', ',' }; std::string morseAlphabet[30] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".-.-.-", "--..--" }; std::string translatedMorsePhrase; int wordSearch = 0; std::cout &lt;&lt; "Please select a mode of operation. " &lt;&lt; endl; std::cout &lt;&lt; "Input 1 for English to Morse and 2 for Morse to English. " &lt;&lt; endl; std::cin &gt;&gt; operatingMode; std::cout &lt;&lt; "Your mode of operation is " &lt;&lt; operatingMode &lt;&lt; endl; if (operatingMode == 1) { std::cout &lt;&lt; "You have selected English to Morse." &lt;&lt; endl; std::cout &lt;&lt; "Please enter the phrase you would like translated." &lt;&lt; endl; std::cin.ignore(); std::getline(std::cin, latinPhrase); } for (int counter = 0; counter &lt; 30; counter++) { for (unsigned i = 0; i&lt;latinPhrase.length(); ++i) { if (latinPhrase.at(i) == latinAlphabet[i]) { cout &lt;&lt; morseAlphabet[i]; } } std::cout &lt;&lt; "The translated phrase is: " &lt;&lt; translatedMorsePhrase &lt;&lt; " stop" &lt;&lt; endl; return 0; } </code></pre>
0
1,082
SSL bad Handshake Error 10054 "WSAECONNRESET"
<p><strong>Notes:</strong></p> <pre><code>versions Python 2.7.11 and my requests version is '2.10.0' 'OpenSSL 1.0.2d 9 Jul 2015' Please read the below comment by Martijn Pieters before reproducing </code></pre> <p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx</code> using code as below</p> <p><strong>code1:</strong></p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; requests.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx",verify=False) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 67, in get return request('get', url, params=params, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESE T')",) </code></pre> <p>After googling and searching I found that you have use SSL verification and using session with adapters can solve the problem. But I still got error's please find the code and error's below</p> <p><strong>Code2:</strong> </p> <pre><code>import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager import ssl import traceback class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) s = requests.Session() s.mount('https://', MyAdapter()) print "Mounted " r = s.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx", stream=True, timeout=120) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESET')",) </code></pre>
0
1,447
How I get a LinkButton in Black and without Underline in my ASP.NET Control?
<p>I have a ASP.NET Application and I use a ListView. If I create a ListItem (a line) I want use a LinkButton. I want that this LinkButton have the CSS Properties..</p> <pre class="lang-css prettyprint-override"><code>color:Black; text-decoration:none; </code></pre> <p>But if I start the Application. I get the linkButtons as Blue and with underline :( </p> <p>here my Code:</p> <p>ASPX:</p> <p>...</p> <pre class="lang-html prettyprint-override"><code>&lt;asp:ListView runat="server" ID="myListView"&gt; &lt;LayoutTemplate&gt; &lt;table id="UserTable" runat="server" border="0"&gt; &lt;tr id="Tr1" style="background-color:#E5E5FE"&gt; &lt;th runat="server"&gt;&lt;asp:LinkButton ID="lnkBenutzer" runat="server" &gt;id_Benutzer&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th runat="server"&gt;&lt;asp:LinkButton ID="lnkemail" runat="server" &gt;id_Email&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th runat="server"&gt;&lt;asp:LinkButton ID="lnkVorname" runat="server" &gt;id_Vorname&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th runat="server"&gt;&lt;asp:LinkButton ID="lnkNachname" runat="server" &gt;id_Nachname&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;th runat="server"&gt;&lt;asp:LinkButton ID="lnkTelefon" runat="server" &gt;id_Telefon&lt;/asp:LinkButton&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr runat="server" id="ItemPlaceholder"&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/LayoutTemplate&gt; &lt;ItemTemplate&gt; &lt;tr&gt; &lt;td align="left" &gt;&lt;asp:LinkButton ID="Label1" Text='&lt;%# Eval("Benutzername") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label2" Text='&lt;%# Eval("eMail") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label3" Text='&lt;%# Eval("Vorname") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label4" Text='&lt;%# Eval("Nachname") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label5" Text='&lt;%# Eval("Telefonnummer") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Button ID="Button1" Text="Anzeigen" OnCommand="Button1_Command" CommandName="Select" CommandArgument='&lt;%# Container.DataItemIndex %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label6" Text='&lt;%# Eval("GUID") %&gt;' runat="server" Visible="False" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; &lt;AlternatingItemTemplate&gt; &lt;tr style="background-color:#EFEFEF"&gt; &lt;td align="left" &gt;&lt;asp:LinkButton ID="Label1" Text='&lt;%# Eval("Benutzername") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label2" Text='&lt;%# Eval("eMail") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label3" Text='&lt;%# Eval("Vorname") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label4" Text='&lt;%# Eval("Nachname") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label5" Text='&lt;%# Eval("Telefonnummer") %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Button ID="Button1" Text="Anzeigen" OnCommand="Button1_Command" CommandName="Select" CommandArgument='&lt;%# Container.DataItemIndex %&gt;' runat="server" /&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;asp:Label ID="Label6" Text='&lt;%# Eval("GUID") %&gt;' runat="server" Visible="False" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/AlternatingItemTemplate&gt; &lt;/asp:ListView&gt; </code></pre> <p>...</p> <p>My CSS File:</p> <p>...</p> <pre class="lang-css prettyprint-override"><code>#Label1 { color:Black; text-decoration:none; } </code></pre> <p>... </p> <p>What is wrong ?</p> <p>tarasov </p>
0
2,171
How to add hadoop dependency via Maven? I have hadoop installed and present in my IDE project library
<ul> <li>I have hadoop installed on my system(I am using Mac 10.7)</li> <li>I am using Intellij IDEA as IDE and my hadoop project has listed hadoop*.jar as dependency</li> <li>When I do <code>mvn install</code>, it fails with the following error</li> </ul> <blockquote> <pre><code>(master) $ mvn clean install [INFO] Scanning for projects... [ERROR] The build could not read 1 project -&gt; [Help 1] [ERROR] [ERROR] The project groupId:hadoop:master-SNAPSHOT (/Users/me/code/p/java/hadoop-programs/hadoop-programs/pom.xml) </code></pre> <p>has 1 error [ERROR] 'dependencies.dependency.systemPath' for org.apache.hadoop:hadoop-core:jar must be omitted. This field may only be specified for a dependency with system scope. @ line 18, column 25 [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] <a href="http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException" rel="nofollow">http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException</a></p> </blockquote> <p>I make changed to my <code>pom.xml</code> as </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &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;groupId&lt;/groupId&gt; &lt;artifactId&gt;hadoop&lt;/artifactId&gt; &lt;version&gt;master-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.hadoop&lt;/groupId&gt; &lt;artifactId&gt;hadoop-core&lt;/artifactId&gt; &lt;version&gt;1.0.3&lt;/version&gt; &lt;type&gt;jar&lt;/type&gt; &lt;systemPath&gt;/usr/local/Cellar/hadoop/1.0.3/libexec/hadoop-core-1.0.3.jar&lt;/systemPath&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p>But still same error, How do I resolve this in Maven?</p>
0
1,053
How to Refresh Android List Adapter, so it shows new-added items
<p>I was working on a project. It's just showing a list of tasks and Adding new tasks to it. I have 3 CLASSES. One for adding, One for view and One to hold all information (or so I think).</p> <p>I have 2 tasks in my List already, and they are shown properly. </p> <p>The problem is, when I <strong>add</strong> a new task it won't show them in view. I have tried many possible solutions:</p> <ul> <li><p>simply adding item to list</p></li> <li><p>creating a new list that consists items from old one and rebuilding adapter;</p></li> <li><p>using <code>notifyDataSetChanged();</code> alongside with add() command;</p></li> <li><p>etc.</p></li> </ul> <p>Here is my code, it's a bit messy, but I hope you will figure it out.</p> <p><strong>AndroidListAdapterActivity class:</strong></p> <pre><code>public class AndroidListAdapterActivity extends ListActivity { /** Called when the activity is first created. */ Button b1; Lista o; ArrayAdapter aa; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1=(Button)findViewById(R.id.add); Log.w("POC", "PA OVO SE ZOVE SVAKI PUT"); o=new Lista(); o.lis.add("S1"); o.lis.add("S2"); aa = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, o.lis); setListAdapter(aa); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(AndroidListAdapterActivity.this, Dodavanje.class); startActivity(i); } }); } @Override public void onResume(){ super.onResume(); aa.notifyDataSetChanged(); if(o.broj&gt;=2){ aa=new ArrayAdapter&lt;String&gt;(this,android.R.layout.simple_spinner_item, o.lis2); setListAdapter(aa); Log.w("myApp", "CALLED TOO"); } String yt=String.valueOf(o.ses); Log.w("teras", yt); aa.notifyDataSetChanged(); Log.w("myApp", "CaLLED!!!!!!!!!!!!!"); String fx= String.valueOf(o.broj); Log.w("myAPPe", fx); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } } </code></pre> <p><strong>Dodavanje (Adding):</strong></p> <pre><code>public class Dodavanje extends Activity { Button but; Button but2; EditText et; Lista o; AndroidListAdapterActivity www; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.dodavanje); but= (Button)findViewById(R.id.bb); but2= (Button)findViewById(R.id.bc); et=(EditText)findViewById(R.id.tt); www=new AndroidListAdapterActivity(); o = new Lista(); but.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("unchecked") @Override public void onClick(View arg0) { String t1= et.getText().toString(); //o.lis.add(t1); o.lis2.addAll(o.lis); o.lis2.add(t1); o.lis.add(t1); o.ses=true; Log.w("IZVJESTAJ: ", String.valueOf(o.ses)); o.broj++; String fx=String.valueOf(o.broj); Log.w("Izbacaj",fx); et.setText(""); } }); but2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); } } </code></pre> <p><strong>Lista (list):</strong></p> <pre><code>public class Lista extends Application { ArrayList&lt;String&gt; lis=new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; lis2=new ArrayList&lt;String&gt;(); int broj =1; boolean ses= false; } </code></pre>
0
1,610
Fetch API and multer error while uploading file
<p>I'm trying to use fetch API to upload files to a node.js server (I'm using github's pollyfill if it has something to do with it: <a href="https://github.com/github/fetch" rel="noreferrer">https://github.com/github/fetch</a>).</p> <p>The request is done like this:</p> <pre><code>const data = new FormData(); data.append('file', file); return fetch(this.concatToUrl(url), { method: 'post', headers: Object.assign({}, this.getHeaders(), {'Content-Type': 'multipart/form-data'}), body: data, }); </code></pre> <p>On the server side I have, this declaration of route:</p> <pre><code>app.post('/media', upload.single('file'), mediaRoutes.postMedia); </code></pre> <p>And trying to get the file like this:</p> <pre><code>exports.postMedia = function(req, res) { console.log('req.file', req.file, req.files, req.body); return res.sendStatus(200); } </code></pre> <p>But <code>req.file</code> is not being filled.</p> <p>Also I'm getting this error from express side:</p> <pre><code>Error: Multipart: Boundary not found [2] at new Multipart (/Users/jmanzano/Development/web/test/node_modules/busboy/lib/types/multipart.js:58:11) [2] at Multipart (/Users/jmanzano/Development/web/test/node_modules/busboy/lib/types/multipart.js:26:12) [2] at Busboy.parseHeaders (/Users/jmanzano/Development/web/test/node_modules/busboy/lib/main.js:64:22) [2] at new Busboy (/Users/jmanzano/Development/web/test/node_modules/busboy/lib/main.js:21:10) [2] at multerMiddleware (/Users/jmanzano/Development/web/test/node_modules/multer/lib/make-middleware.js:32:16) [2] at Layer.handle [as handle_request] (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/layer.js:95:5) [2] at next (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/route.js:131:13) [2] at Route.dispatch (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/route.js:112:3) [2] at Layer.handle [as handle_request] (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/layer.js:95:5) [2] at /Users/jmanzano/Development/web/test/node_modules/express/lib/router/index.js:277:22 [2] at Function.process_params (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/index.js:330:12) [2] at next (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/index.js:271:10) [2] at cors (/Users/jmanzano/Development/web/test/node_modules/cors/lib/index.js:178:7) [2] at /Users/jmanzano/Development/web/test/node_modules/cors/lib/index.js:228:17 [2] at originCallback (/Users/jmanzano/Development/web/test/node_modules/cors/lib/index.js:217:15) [2] at /Users/jmanzano/Development/web/test/node_modules/cors/lib/index.js:222:13 [2] at optionsCallback (/Users/jmanzano/Development/web/test/node_modules/cors/lib/index.js:203:9) [2] at /Users/jmanzano/Development/web/test/node_modules/cors/lib/index.js:208:7 [2] at Layer.handle [as handle_request] (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/layer.js:95:5) [2] at trim_prefix (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/index.js:312:13) [2] at /Users/jmanzano/Development/web/test/node_modules/express/lib/router/index.js:280:7 [2] at Function.process_params (/Users/jmanzano/Development/web/test/node_modules/express/lib/router/index.js:330:12) </code></pre> <p>And this is the configuration via middlewares:</p> <pre><code>app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(expressValidator()); app.use(logger('dev')); app.use(cookieParser()); app.use(methodOverride()); app.use(passport.initialize()); app.use(passport.session()); app.set('JWTSuperSecret', jwtConfig.secret); if (process.env.NODE_ENV !== 'production') { app.use(cors()); } </code></pre> <p>Also, this is correctly working with POSTMAN. So, I think I'm doing something wrong with the request.</p> <p>Thanks!</p>
0
1,569
Java Map sort by value
<p>I was looking for ways of sorting <code>Map&lt;String, Integer&gt;</code> by values. I found <a href="https://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java">this post</a>, which solved my sorting problem, but not exactly. According to the post, I wrote the following code:</p> <pre><code>import java.util.*; public class Sort { static class ValueComparator implements Comparator&lt;String&gt; { Map&lt;String, Integer&gt; base; ValueComparator(Map&lt;String, Integer&gt; base) { this.base = base; } @Override public int compare(String a, String b) { if (base.get(a) &gt;= base.get(b)) { return 1; } else { return -1; } } } public static void main(String[] args) { HashMap&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;(); ValueComparator vc = new ValueComparator(map); TreeMap&lt;String, Integer&gt; sorted = new TreeMap&lt;String, Integer&gt;(vc); map.put("A", 1); map.put("B", 2); sorted.putAll(map); for (String key : sorted.keySet()) { System.out.println(key + " : " + sorted.get(key)); // why null values here? } System.out.println(sorted.values()); // But we do have non-null values here! } } </code></pre> <p>Output:</p> <pre><code>A : null B : null [1, 2] BUILD SUCCESSFUL (total time: 0 seconds) </code></pre> <p>As you can see from the output, the <code>get</code> method always returns <code>null</code>. The reason is my <code>ValueComparator.compare()</code> method never returns <code>0</code>, which I've figured out by making <a href="https://stackoverflow.com/questions/13842830/treemapstring-integer-objects-get-method-return-null-value">this post</a>.</p> <p>Someone suggested in that post the following to solve the <code>null</code> value problem:</p> <pre><code> public int compare(String a, String b) { if (base.get(a) &gt; base.get(b)) { return 1; }else if(base.get(a) == base.get(b)){ return 0; } return -1; } </code></pre> <p>I've tested this piece of code and it introduces a key merging problem. In other words, when the values are equal their corresponding keys are merged.</p> <p>I've also tried the following:</p> <pre><code> public int compare(String a, String b) { if (a.equals(b)) return 0; if (base.get(a) &gt;= base.get(b)) { return 1; } else return -1; } </code></pre> <p>It does not work either. Some of the values are still <code>null</code>. Besides, this workaround might potentially have logical problems.</p> <p>Anyone can propose a fully working solution to my problem? I'd like the sort by value function to work and the <code>get</code> method to work at the same time.</p>
0
1,266
I Can't Find dompdf_config.inc.php or dompdf_config.custom.inc.php for setting "DOMPDF_UNICODE_ENABLED" true
<p>I use dompdf to save a html page as pdf by php. I use Persian characters in my html page (actually php page) but when i'm trying to save it as pdf, the export just looked like '?????' :( .I have searched all the net and I found a configuration for unicode characters <a href="https://github.com/dompdf/dompdf/wiki/UnicodeHowTo#configure-dompdf-for-unicode-support" rel="noreferrer">https://github.com/dompdf/dompdf/wiki/UnicodeHowTo#configure-dompdf-for-unicode-support</a> in "<strong>dompdf_config.inc.php</strong>" or <strong>"dompdf_config.custom.inc.php"</strong> file. but the problem is I CAN'T FIND such file in all of my dompdf folder and in all of my file system. Please somebody tell me where it is or what I must do. something else is that I have to use dompdf because of its fantastic CSS compatibility. Thanks. <br><br> This is Export. <a href="http://i.stack.imgur.com/nYAzW.png" rel="noreferrer">http://i.stack.imgur.com/nYAzW.png</a> <br><br> This is my code.</p> <pre><code>require("dompdf/autoload.inc.php"); use Dompdf\Dompdf; $dompdf = new Dompdf(); $dompdf-&gt;loadHtml("&lt;html&gt;&lt;head&gt; &lt;meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"&gt; &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"styles/scorestyle.css\"&gt; &lt;/head&gt; &lt;body&gt;&lt;div&gt; &lt;div id=\"showscorediv\"&gt;&lt;table&gt;&lt;tbody&gt;&lt;tr class=\"scoresubject\"&gt;&lt;th colspan=\"2\"&gt;کارنامه ارزیابی&lt;/th&gt;&lt;/tr&gt;&lt;tr class=\"scorecategory\"&gt;&lt;th&gt;شاخص ها&lt;/th&gt;&lt;th&gt;امیتاز ها&lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_0\"&gt;شاخص های کیفی&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;62&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_1\"&gt;شاخص های مرتبط با تیم کاری&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;10&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_1\"&gt;شاخص های مرتبط با محصول&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;28&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_1\"&gt;شاخص های مرتبط با بازار&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;24&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_0\"&gt;شاخص های کمی&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;60&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_1\"&gt;شاخص های تولیدی&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;20&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_1\"&gt;شاخص های درآمدی&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;14&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span class=\"level_1\"&gt;شاخص های هزینه ای&lt;/span&gt;&lt;/td&gt;&lt;td class=\"scoretd\"&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr class=\"scoresubject\"&gt;&lt;th&gt;امتیاز کل&lt;/th&gt;&lt;th&gt;122&lt;/th&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;/div&gt; &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;"); $dompdf-&gt;setPaper('A4', 'landscape'); $dompdf-&gt;render(); $dompdf-&gt;stream(); </code></pre>
0
1,597
Change < Formik > to useFormik
<p>I am using Formik/Yup for a validation of a page, which calls a GraphQL mutation. My code works fully:</p> <pre><code>export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemoved] = useState(false); const [errorMessage, setErrorMessage] = useState(''); const [removeUser] = useMutation(RemoveUserMutation); function submitForm(email: string) { setIsSubmitted(true); removeUser({ variables: { email: email, }, }).then(({ data }: any) =&gt; { setIsRemoved(true); console.log('info: ', data.deleteUser); }) .catch((error: { message: string; }) =&gt; { setIsRemoved(false); console.log("Error msg:" + error.message); setErrorMessage(error.message) }) } return ( &lt;div&gt; &lt;PermanentDrawerLeft&gt;&lt;/PermanentDrawerLeft&gt; &lt;Formik initialValues={{ email: '' }} onSubmit={(values, actions) =&gt; { setTimeout(() =&gt; { alert(JSON.stringify(values, null, 2)); actions.setSubmitting(false); }, 1000); }} validationSchema={schema} &gt; {props =&gt; { const { values: { email }, errors, touched, handleChange, isValid, setFieldTouched } = props; const change = (name: string, e: any) =&gt; { e.persist(); handleChange(e); setFieldTouched(name, true, false); }; return ( &lt;div className='main-content'&gt; &lt;form style={{ width: '100%' }} onSubmit={e =&gt; {e.preventDefault();submitForm(email) }}&gt; &lt;div&gt; &lt;TextField variant="outlined" margin="normal" id="email" name="email" helperText={touched.email ? errors.email : ""} error={touched.email &amp;&amp; Boolean(errors.email)} label="Email" value={email} onChange={change.bind(null, "email")} /&gt; &lt;br&gt;&lt;/br&gt; &lt;Button type="submit" disabled={!isValid || !email} &gt; Remove User&lt;/Button&gt; &lt;/div&gt; &lt;/form&gt; &lt;br&gt;&lt;/br&gt; {isSubmitted &amp;&amp; StatusMessage(isRemoved, errorMessage)} &lt;/div&gt; ) }} &lt;/Formik&gt; &lt;/div&gt; ); } </code></pre> <p>However, now I want to use <code>useFormik</code> hook instead of <code>&lt;Formik&gt;</code> and I am unable to do so. I have seen the following example but I just can't figure out how exactly I could syntactically use it in my case since I am using material ui components instead of formic-specific inputs.</p> <p><a href="https://jaredpalmer.com/formik/docs/api/useFormik" rel="nofollow noreferrer">https://jaredpalmer.com/formik/docs/api/useFormik</a></p> <p>Edit:</p> <p>This compiles and all but there's no validation happening on the textfields. What am I missing?</p> <pre><code>export const schema = Yup.object({ email: Yup.string() .email('Invalid Email') .required('This Field is Required'), }); export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved, setIsRemoved] = useState(false); const [errorMessage, setErrorMessage] = useState(''); const [removeUser] = useMutation&lt;DeleteUserResponse&gt;(REMOVE_USER); let submitForm = (email: string) =&gt; { setIsSubmitted(true); removeUser({ variables: { email: email, }, }) .then(({ data }: ExecutionResult&lt;DeleteUserResponse&gt;) =&gt; { if (data !== null &amp;&amp; data !== undefined) { setIsRemoved(true); console.log('info: ', data.deleteUser); } }) .catch((error: { message: string }) =&gt; { setIsRemoved(false); console.log('Error msg:' + error.message); setErrorMessage(error.message); }); }; const formik = useFormik({ initialValues:{ email: '' }, onSubmit:(values, actions) =&gt; { setTimeout(() =&gt; { alert(JSON.stringify(values, null, 2)); actions.setSubmitting(false); }, 1000); }, validationSchema:{schema} }) const handleChange = (e: ChangeEvent&lt;HTMLInputElement&gt;)=&gt;{ const {name,value} = e.target; formik.setFieldValue(name,value); } return ( &lt;div&gt; &lt;PermanentDrawerLeft&gt;&lt;/PermanentDrawerLeft&gt; &lt;Wrapper&gt; &lt;Form onSubmit={e =&gt; { e.preventDefault(); submitForm(formik.values.email); }}&gt; &lt;div&gt; &lt;TextField variant="outlined" margin="normal" id="email" name="email" helperText={formik.touched.email ? formik.errors.email : ''} error={formik.touched.email &amp;&amp; Boolean(formik.errors.email)} label="Email" value={formik.values.email} //onChange={change.bind(null, 'email')} onChange={handleChange} /&gt; &lt;br&gt;&lt;/br&gt; &lt;CustomButton disabled={!formik.values.email} text={'Remove User'} /&gt; &lt;/div&gt; &lt;/Form&gt; &lt;br&gt;&lt;/br&gt; {isSubmitted &amp;&amp; StatusMessage(isRemoved, errorMessage)} &lt;/Wrapper&gt; &lt;/div&gt; ); } </code></pre> <p>It gave me this error:</p> <pre><code>TypeError: schema[sync ? 'validateSync' : 'validate'] is not a function. (In 'schema[sync ? 'validateSync' : 'validate'](validateData, { abortEarly: false, context: context })', 'schema[sync ? 'validateSync' : 'validate']' is undefined) </code></pre> <p>Secondly, earlier on, I was using <code>isValid</code>for the button but now it gives an error. Is there an alternative?</p>
0
3,310
Uncaught exception in Firebase runloop (3.0.0)
<p>I'm using the latest firebase(9.0.2): <code>build.gradle:</code></p> <pre><code>dependencies { ... compile "com.google.firebase:firebase-database:9.0.2" compile 'com.google.firebase:firebase-auth:9.0.2' } apply plugin: 'com.google.gms.google-services' </code></pre> <p>Project <code>build.gradle</code></p> <pre><code>classpath 'com.google.gms:google-services:3.0.0' </code></pre> <p>And after some time application starts crashing with this Exception:</p> <pre><code> Fatal Exception: java.lang.RuntimeException: Uncaught exception in Firebase runloop (3.0.0). Please report to support@firebase.com at com.google.android.gms.internal.zzadp$1$1.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5274) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) Caused by java.lang.AssertionError: hardAssert failed: at com.google.android.gms.internal.zzaiv.zzb(Unknown Source) at com.google.android.gms.internal.zzaiv.zzaN(Unknown Source) at com.google.android.gms.internal.zzagh.zzb(Unknown Source) at com.google.android.gms.internal.zzagh.&lt;init&gt;(Unknown Source) at com.google.android.gms.internal.zzaga.&lt;init&gt;(Unknown Source) at com.google.android.gms.internal.zzaga.&lt;init&gt;(Unknown Source) at com.google.android.gms.internal.zzadp.zza(Unknown Source) at com.google.android.gms.internal.zzaeu.zzic(Unknown Source) at com.google.android.gms.internal.zzafc.zzRy(Unknown Source) at com.google.android.gms.internal.zzafc.zza(Unknown Source) at com.google.android.gms.internal.zzafc$1.run(Unknown Source) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) </code></pre> <p>in onCreate of Application I have:</p> <pre><code>@Override public void onCreate() { ... FirebaseDatabase.getInstance().setPersistenceEnabled(true); } </code></pre> <p>and also we created singleton helper class for Firebase what called from Activities(all activities in the same process)/Fragments:</p> <pre><code> private FirebaseHelper() { mFirebaseRef = FirebaseDatabase.getInstance().getReference(); mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseAuth.addAuthStateListener(this); authentication(); } public static synchronized FirebaseHelper getInstance() { if (mInstance == null || mInstance.getFirebaseRef() == null) { mInstance = new FirebaseHelper(); } return mInstance; } </code></pre> <p>Libraries:</p> <pre><code>dependencies { testCompile 'junit:junit:4.12' compile('com.crashlytics.sdk.android:crashlytics:2.5.6@aar') { transitive = true; } compile 'com.google.code.gson:gson:2.6.2' compile 'com.android.support:support-v4:23.4.0' compile 'com.android.support:support-v13:23.4.0' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.android.support:support-annotations:23.4.0' compile 'com.android.support:gridlayout-v7:23.4.0' compile 'com.google.android.gms:play-services-base:9.0.2' compile 'com.google.android.gms:play-services-maps:9.0.2' compile 'com.google.android.gms:play-services-location:9.0.2' compile 'com.google.android.gms:play-services-appindexing:9.0.2' compile 'com.google.android.gms:play-services-analytics:9.0.2' compile 'com.google.firebase:firebase-messaging:9.0.2' compile 'com.facebook.android:facebook-android-sdk:4.11.0' compile 'de.greenrobot:eventbus:2.4.0' compile 'com.amazonaws:aws-android-sdk-core:2.2.12' compile 'com.amazonaws:aws-android-sdk-cognito:2.2.12' compile 'com.amazonaws:aws-android-sdk-s3:2.2.12' compile 'com.android.support:multidex:1.0.1' compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2' compile 'io.reactivex:rxandroid:1.2.0' compile 'io.reactivex:rxjava:1.1.5' compile 'com.squareup.okhttp3:logging-interceptor:3.3.1' compile 'com.github.curioustechizen.android-ago:library:1.3.0' compile 'com.cedarsoftware:json-io:4.4.0' compile 'com.timehop.stickyheadersrecyclerview:library:0.4.3@aar' compile 'joda-time:joda-time:2.9.3' compile 'com.facebook.fresco:fresco:0.10.0' compile 'com.facebook.fresco:imagepipeline-okhttp3:0.10.0' compile 'com.google.firebase:firebase-core:9.0.2' compile 'com.google.firebase:firebase-invites:9.0.2' compile 'com.google.firebase:firebase-database:9.0.1' compile 'com.google.firebase:firebase-auth:9.0.1' compile 'com.github.jd-alexander:LikeButton:0.2.0' debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2' androidTestCompile 'junit:junit:4.12' androidTestCompile 'com.android.support:support-annotations:23.4.0' androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support.test:rules:0.5' compile files('libs/core-3.2.1.jar') } </code></pre>
0
2,551
Cannot load driver class: com.mysql.jdbc.Driver Spring Boot
<p>I was working with Spring Boot project, and suddenly I faced with an issue that application can not load MySQL jdbc.(I compiled this project once without changing anything) <br> This is my pom.xml:</p> <pre><code>&lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.5.9.RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.12&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;!-- &lt;scope&gt;runtime&lt;/scope&gt; I tried this too --&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; &lt;artifactId&gt;gson&lt;/artifactId&gt; &lt;version&gt;2.8.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;5.2.10.Final&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>This is my application.properties:</p> <pre><code>spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost/PROJECT_NAME?useUnicode=yes&amp;characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=password </code></pre> <p>Logcat:</p> <pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] ... 26 common frames omitted Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] ... 39 common frames omitted Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE] at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:232) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE] at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:184) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE] at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:42) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE] at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource(DataSourceConfiguration.java:56) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] ... 40 common frames omitted </code></pre> <p>MySQL database is created with hibernate at first. These configurations worked fine but I am not sure what is the real problem here</p> <p><strong>EDIT :</strong> I removed .m2 folder and install all dependencies from beginning as well.</p>
0
3,223
Fatal Error Laravel: Uncaught ReflectionException when i view my Site
<p>I have the following error when i view my site.</p> <p><strong>My Error:</strong></p> <blockquote> <p>Fatal error: Uncaught ReflectionException: Class log does not exist in /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php:741> Stack trace: #0 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(741): ReflectionClass->__construct('log') #1 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\Container\Container->build('log', Array) #2 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\Container\Container->make('log', Array) #3 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(842): Illuminate\Foundation\Application->make('log') #4 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(805): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter)) > #5 /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php(774): Il in /home/vagrant/Code/in10km/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 741</p> </blockquote> <p>My <strong>Composer.json</strong> file is like this</p> <pre><code>{ "name": "laravel/laravel", "description": "The Laravel Framework.", "keywords": ["framework", "laravel"], "license": "MIT", "type": "project", "require": { "php": "&gt;=5.5.9", "laravel/framework": "5.1.*", "doctrine/dbal": "v2.4.2", "swiftmailer/swiftmailer": "^5.4", "guzzlehttp/guzzle": "~5.3|~6.0", "chrisbjr/api-guard": "^2.3", "serverfireteam/panel": "1.3.*", "laravel/socialite": "^2.0" }, "require-dev": { "fzaninotto/faker": "~1.4", "mockery/mockery": "0.9.*", "phpunit/phpunit": "~4.0", "phpspec/phpspec": "~2.1" }, "autoload": { "files": [ "app/Http/helpers.php", "app/Support/helpers.php" ], "classmap": [ "database" ], "psr-4": { "App\\": "app/" } }, "autoload-dev": { "classmap": [ "tests/TestCase.php" ] }, "scripts": { "post-install-cmd": [ "php artisan clear-compiled", "php artisan optimize" ], "pre-update-cmd": [ "php artisan clear-compiled" ], "post-update-cmd": [ "php artisan optimize" ], "post-root-package-install": [ "php -r \"copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "php artisan key:generate" ] }, "config": { "preferred-install": "dist" } } </code></pre> <p>Anyone help me how to get rid of this error and view my site successfully.</p>
0
1,431
Spring-Boot : 400 Bad request error even when parameter is present
<p>In the following method there are two parameters <code>childFile</code> and <code>file</code>, I run this call through postman but it gives me 400 Bad Request error when I check the logs it says that parameter <code>childFile</code> is not present, I attach code, error and postman screenshot please tell me what is the issue </p> <p><a href="https://i.stack.imgur.com/1sTc7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1sTc7.png" alt="Postman Call"></a></p> <p><strong>Controller</strong></p> <pre><code>@Transactional @RequestMapping(method = RequestMethod.POST, value = "api/addchild",produces="application/json") public ResponseEntity&lt;?&gt; child(Authentication authentication, @RequestParam(value="childFile") String childFile, @RequestParam(value="file") MultipartFile file) { ObjectMapper mapper = new ObjectMapper(); Child child; try { child=mapper.readValue(childFile, Child.class); Child createdChild=childRepo.save(child); if(createdChild!=null) { childService.createChildPhoto(file, createdChild.getId()); } return ResponseEntity.ok("child created"); } catch (IOException e1) { e1.printStackTrace(); } return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Child can not be created , please check your headers and string body again."); } </code></pre> <p><strong>Logs</strong></p> <pre><code>Content-Disposition: form-data; name] with value ["childFile" { "id": 0, "firstName": "Abeer", "lastName": "Hashmi", "gender": "Male", "dateOfBirth": "1999-02-11", "detail": null, "emergencyNumber": "03001111115", "medicalCondition": false, "medicalConditionDescription": null, "enabled": true } ------WebKitFormBoundary3t9AJTMgmU7MV4da Content-Disposition: form-data; name="file"; filename="child3.jpg" Content-Type: image/jpeg [![org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'childFile' is not present at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:198) ~\[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:109) ~\[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~\[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158) \[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128) \[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) \[tomcat-embed-core-8.5.23.jar:8.5.23\] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) \[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE\] at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) \[tomcat-embed-core-8.5.23.jar:8.5.23\] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) \[tomcat-embed-core-8.5.23.jar:8.5.23\] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) \[tomcat-embed-core-8.5.23.jar:8.5.23\] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) \[tomcat-embed-websocket-8.5.23.jar:8.5.23\] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) \[tomcat-embed-core-8.5.23.jar:8.5.23\] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) \[tomcat-embed-core-8.5.23.jar:8.5.23\] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) \[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE\] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) \[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE\] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) \[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE\]][1]][1] </code></pre>
0
2,442
JPA sequence generator not working
<p>Trying to setup an id with a JPA sequence generator:</p> <pre><code>@Entity @Table(name=CommitmentRegisterDetailTable.TABLE) public class TestCrd { @Id @Column(name=CommitmentRegisterDetailTable.COMMIT_REG_DETAIL_ID) @SequenceGenerator(name="CRD_ID", sequenceName="COMMIT_REG_DETAIL_ID_SEQ", allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CRD_ID") private int id; @Column(name=CommitmentRegisterDetailTable.COMMIT_REG_ID) private int commitRegId = 89915; } </code></pre> <p>With this entity I am able to do load, and merge. But when I do persist(), the SQL output shows it attempts to perform an INSERT with id = 0. Am I missing a step?</p> <p>This is an Oracle DB.</p> <p>Code where I persist:</p> <pre><code> TestCrd testCrd = new TestCrd(); EntityManagerFactory factory = Persistence.createEntityManagerFactory( "incepPersistence" ); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); em.persist( testCrd ); em.getTransaction().commit(); em.close(); factory.close(); </code></pre> <p>Sequence details:</p> <pre><code>CREATED 07-JUN-16 LAST_DDL_TIME 07-JUN-16 SEQUENCE_OWNER RMS SEQUENCE_NAME COMMIT_REG_DETAIL_ID_SEQ MIN_VALUE 0 MAX_VALUE 999999999999999999999999999 INCREMENT_BY 1 CYCLE_FLAG N ORDER_FLAG N CACHE_SIZE 0 LAST_NUMBER 107568 </code></pre> <p>This is the call that goes to the DB. As you can see the first parameter COMMIT_REG_DETAIL_ID is assigned a value of 0.</p> <pre><code>Call: INSERT INTO RMS.COMMITMENT_REGISTER_DETAIL (COMMIT_REG_DETAIL_ID, AMOUNT, COMMITTED, LINE_DESCRIPTION, DISBURSED, INVOICED, LINE_NUMBER, OBLIGATED, RECEIVED, ACCOUNT_COMBO_ID, COMMIT_REG_ID, OBJECT_CLASS_CODE, SP_DETAIL_VALUE_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) bind =&gt; [0, 5127, null, null, null, null, 0, null, null, 2097, 89843, 31510, null] Query: InsertObjectQuery(com.incep.commitmentregister.CommitmentRegisterDetail@2ee77e0f) </code></pre> <p>Here's the full JPA log set to FINEST:</p> <pre><code>[EL Finest]: jpa: 2016-07-06 13:56:00.506--ServerSession(786709615)--Thread(Thread[main,5,main])--Begin predeploying Persistence Unit incepPersistence; session file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence; state Initial; factoryCount 0 [EL Finest]: properties: 2016-07-06 13:56:00.535--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.orm.throw.exceptions; default value=true [EL Finest]: properties: 2016-07-06 13:56:00.536--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.weaving.changetracking; default value=true [EL Finest]: properties: 2016-07-06 13:56:00.536--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.weaving.lazy; default value=true [EL Finest]: properties: 2016-07-06 13:56:00.536--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.weaving.eager; default value=false [EL Finest]: properties: 2016-07-06 13:56:00.537--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.weaving.fetchgroups; default value=true [EL Finest]: properties: 2016-07-06 13:56:00.537--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.weaving.internal; default value=true [EL Finest]: properties: 2016-07-06 13:56:00.539--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.multitenant.tenants-share-emf; default value=true [EL Finest]: properties: 2016-07-06 13:56:00.539--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.multitenant.tenants-share-cache; default value=false [EL Finer]: metadata: 2016-07-06 13:56:00.573--ServerSession(786709615)--Thread(Thread[main,5,main])--Searching for default mapping file in file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/ (There is no English translation for this message.) [EL Finer]: metadata: 2016-07-06 13:56:00.976--ServerSession(786709615)--Thread(Thread[main,5,main])--Found a default mapping file at file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/META-INF/orm.xml for root URL file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/ (There is no English translation for this message.) [EL Finer]: metadata: 2016-07-06 13:56:02.326--ServerSession(786709615)--Thread(Thread[main,5,main])--Searching for default mapping file in file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/ (There is no English translation for this message.) [EL Config]: metadata: 2016-07-06 13:56:02.775--ServerSession(786709615)--Thread(Thread[main,5,main])--The access type for the persistent class [class com.incep.test.commitmentregister.TestCrd] is set to [FIELD]. [EL Config]: metadata: 2016-07-06 13:56:02.815--ServerSession(786709615)--Thread(Thread[main,5,main])--The alias name for the entity class [class com.incep.test.commitmentregister.TestCrd] is being defaulted to: TestCrd. [EL Finer]: weaver: 2016-07-06 13:56:02.889--ServerSession(786709615)--Thread(Thread[main,5,main])--Class [com.incep.test.commitmentregister.TestCrd] registered to be processed by weaver. [EL Finest]: jpa: 2016-07-06 13:56:02.898--ServerSession(786709615)--Thread(Thread[main,5,main])--End predeploying Persistence Unit incepPersistence; session file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence; state Predeployed; factoryCount 0 [EL Finer]: weaver: 2016-07-06 13:56:02.899--Thread(Thread[main,5,main])--JavaSECMPInitializer - transformer is null. [EL Finest]: jpa: 2016-07-06 13:56:02.9--ServerSession(786709615)--Thread(Thread[main,5,main])--Begin predeploying Persistence Unit incepPersistence; session file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence; state Predeployed; factoryCount 0 [EL Finest]: jpa: 2016-07-06 13:56:02.901--ServerSession(786709615)--Thread(Thread[main,5,main])--End predeploying Persistence Unit incepPersistence; session file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence; state Predeployed; factoryCount 1 [EL Finest]: jpa: 2016-07-06 13:56:22.435--ServerSession(786709615)--Thread(Thread[main,5,main])--Begin deploying Persistence Unit incepPersistence; session file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence; state Predeployed; factoryCount 1 [EL Finer]: 2016-07-06 13:56:22.453--ServerSession(786709615)--Thread(Thread[main,5,main])--Could not initialize Validation Factory. Encountered following exception: java.lang.NoClassDefFoundError: javax/validation/Validation [EL Finest]: properties: 2016-07-06 13:56:22.481--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.logging.logger; value=DefaultLogger; translated value=org.eclipse.persistence.logging.DefaultSessionLog [EL Finest]: properties: 2016-07-06 13:56:22.482--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.logging.level; value=FINEST; translated value=FINEST [EL Finest]: properties: 2016-07-06 13:56:22.483--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.logging.level; value=FINEST; translated value=FINEST [EL Finest]: properties: 2016-07-06 13:56:22.484--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.target-database; value=org.eclipse.persistence.platform.database.oracle.OraclePlatform [EL Finest]: properties: 2016-07-06 13:56:22.493--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.id-validation; value=NULL [EL Finest]: properties: 2016-07-06 13:56:22.493--ServerSession(786709615)--Thread(Thread[main,5,main])--property=eclipselink.session.customizer; value=com.apprio.acquisition.JPAEclipseLinkSessionCustomizer _JPAEclipseLinkSessionCustomizer: configured java:comp/env/jdbc/OracleRMS_DS [EL Info]: 2016-07-06 13:56:22.496--ServerSession(786709615)--Thread(Thread[main,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.4.1.v20121003-ad44345 [EL Config]: connection: 2016-07-06 13:56:22.509--ServerSession(786709615)--Connection(1167290948)--Thread(Thread[main,5,main])--connecting(DatabaseLogin( platform=&gt;OraclePlatform user name=&gt; "" connector=&gt;JNDIConnector datasource name=&gt;java:comp/env/jdbc/OracleRMS_DS )) [EL Config]: connection: 2016-07-06 13:56:23.129--ServerSession(786709615)--Connection(452044444)--Thread(Thread[main,5,main])--Connected: jdbc:oracle:thin:@localhost:1521:INCEPDEV User: RMS Database: Oracle Version: Oracle Database 11g Release 11.2.0.3.0 - 64bit Production Driver: Oracle JDBC driver Version: 11.2.0.2.0 [EL Finest]: connection: 2016-07-06 13:56:23.143--ServerSession(786709615)--Connection(839511213)--Thread(Thread[main,5,main])--Connection acquired from connection pool [read]. [EL Finest]: connection: 2016-07-06 13:56:23.144--ServerSession(786709615)--Connection(839511213)--Thread(Thread[main,5,main])--Connection released to connection pool [read]. [EL Config]: connection: 2016-07-06 13:56:23.144--ServerSession(786709615)--Connection(697396101)--Thread(Thread[main,5,main])--connecting(DatabaseLogin( platform=&gt;OraclePlatform user name=&gt; "" connector=&gt;JNDIConnector datasource name=&gt;java:comp/env/jdbc/OracleRMS_DS )) [EL Config]: connection: 2016-07-06 13:56:23.31--ServerSession(786709615)--Connection(170524181)--Thread(Thread[main,5,main])--Connected: jdbc:oracle:thin:@localhost:1521:INCEPDEV User: RMS Database: Oracle Version: Oracle Database 11g Release 11.2.0.3.0 - 64bit Production Driver: Oracle JDBC driver Version: 11.2.0.2.0 [EL Finest]: sequencing: 2016-07-06 13:56:23.327--ServerSession(786709615)--Thread(Thread[main,5,main])--sequencing connected, state is Preallocation_NoTransaction_State [EL Finest]: sequencing: 2016-07-06 13:56:23.327--ServerSession(786709615)--Thread(Thread[main,5,main])--sequence COMMIT_REG_DETAIL_ID_SEQ: preallocation size 1 [EL Info]: connection: 2016-07-06 13:56:23.365--ServerSession(786709615)--Thread(Thread[main,5,main])--file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence login successful [EL Finer]: metamodel: 2016-07-06 13:56:23.441--ServerSession(786709615)--Thread(Thread[main,5,main])--Canonical Metamodel class [com.incep.test.commitmentregister.TestCrd_] not found during initialization. [EL Finest]: jpa: 2016-07-06 13:56:23.442--ServerSession(786709615)--Thread(Thread[main,5,main])--End deploying Persistence Unit incepPersistence; session file:/D:/Development/Workspaces/InCEP/incep-aspr-aqc-local/codeCharge/WEB-INF/classes/_incepPersistence; state Deployed; factoryCount 1 [EL Finer]: connection: 2016-07-06 13:56:29.205--ServerSession(786709615)--Thread(Thread[main,5,main])--client acquired: 1882760631 [EL Finer]: transaction: 2016-07-06 13:56:29.235--ClientSession(1882760631)--Thread(Thread[main,5,main])--acquire unit of work: 102009560 [EL Finest]: transaction: 2016-07-06 13:56:30.565--UnitOfWork(102009560)--Thread(Thread[main,5,main])--persist() operation called on: com.incep.test.commitmentregister.TestCrd@3c07590f. [EL Finer]: transaction: 2016-07-06 13:56:33.25--UnitOfWork(102009560)--Thread(Thread[main,5,main])--begin unit of work commit [EL Finest]: query: 2016-07-06 13:56:33.261--UnitOfWork(102009560)--Thread(Thread[main,5,main])--Execute query InsertObjectQuery(com.incep.test.commitmentregister.TestCrd@3c07590f) [EL Finest]: connection: 2016-07-06 13:56:33.267--ServerSession(786709615)--Connection(13402762)--Thread(Thread[main,5,main])--Connection acquired from connection pool [default]. [EL Finer]: transaction: 2016-07-06 13:56:33.267--ClientSession(1882760631)--Connection(13402762)--Thread(Thread[main,5,main])--begin transaction [EL Finest]: connection: 2016-07-06 13:56:33.268--ClientSession(1882760631)--Thread(Thread[main,5,main])--reconnecting to external connection pool [EL Fine]: sql: 2016-07-06 13:56:33.557--ClientSession(1882760631)--Connection(1921921646)--Thread(Thread[main,5,main])--INSERT INTO RMS.COMMITMENT_REGISTER_DETAIL (COMMIT_REG_DETAIL_ID, COMMIT_REG_ID) VALUES (?, ?) bind =&gt; [0, 89915] [EL Fine]: sql: 2016-07-06 13:56:33.9--ClientSession(1882760631)--Thread(Thread[main,5,main])--SELECT 1 FROM DUAL [EL Warning]: 2016-07-06 13:56:33.927--UnitOfWork(102009560)--Thread(Thread[main,5,main])--Local Exception Stack: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (RMS.COMMITMENT_REGISTER_DETAIL_PK) violated Error Code: 1 Call: INSERT INTO RMS.COMMITMENT_REGISTER_DETAIL (COMMIT_REG_DETAIL_ID, COMMIT_REG_ID) VALUES (?, ?) bind =&gt; [0, 89915] Query: InsertObjectQuery(com.incep.test.commitmentregister.TestCrd@3c07590f) at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324) at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:851) at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:913) at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:594) at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:537) at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1800) at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:286) at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207) at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193) at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342) at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162) at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177) at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:471) at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80) at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90) at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:286) at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58) at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:852) at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:751) at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108) at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2875) at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1602) at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1584) at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1535) at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:224) at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:123) at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3914) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1419) at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:634) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1509) at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:266) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1147) at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:84) at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63) at com.incep.test.commitmentregister.TestCommitmentRegisterManager.testLoadSave(TestCommitmentRegisterManager.java:729) at com.incep.test.commitmentregister.TestCommitmentRegisterManager.testAll(TestCommitmentRegisterManager.java:73) at com.incep.test.TestMaster.testAll(TestMaster.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (RMS.COMMITMENT_REGISTER_DETAIL_PK) violated at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207) at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576) at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3657) at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350) at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:842) ... 59 more [EL Finer]: transaction: 2016-07-06 13:56:33.942--ClientSession(1882760631)--Connection(1921921646)--Thread(Thread[main,5,main])--rollback transaction [EL Finest]: connection: 2016-07-06 13:56:33.966--ServerSession(786709615)--Connection(13402762)--Thread(Thread[main,5,main])--Connection released to connection pool [default]. [EL Finer]: transaction: 2016-07-06 13:56:33.967--UnitOfWork(102009560)--Thread(Thread[main,5,main])--release unit of work [EL Finer]: connection: 2016-07-06 13:56:33.967--ClientSession(1882760631)--Thread(Thread[main,5,main])--client released </code></pre>
0
7,457
'Failed to build gem native extension' on Windows 7 (The system cannot find the path specified)
<h2>The problem in short</h2> <p>I'm on Windows and am getting the following error when running <code>gem install json —platform=ruby</code>:</p> <pre><code>The system cannot find the path specified. Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... The system cannot find the path specified. ERROR: Error installing json: ERROR: Failed to build gem native extension. C:/Ruby193/bin/ruby.exe extconf.rb creating Makefile Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1 for inspection. Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1/ext/json/ext/generator/gem_make.out </code></pre> <h2>Background and some Investigations</h2> <p>So first off, I'm not a Windows person so this is a brave new world for me. Having inherited a laptop from work that had a mad collection of libraries spread all over it I've managed to remove all previous installations of ruby and the Devkit and then installed the following:</p> <ul> <li>Ruby 1.9.3p484 with <a href="http://rubyinstaller.org" rel="noreferrer">Ruby Installer</a> into <code>C:/Ruby193</code></li> <li>Ruby 2.0.0p353 with <a href="http://rubyinstaller.org" rel="noreferrer">Ruby Installer</a> into <code>C:/Ruby200</code></li> <li>Devkit <code>DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe</code> (for ruby 1x) extracted into <code>C:/Ruby193-devkit</code></li> <li>Devkit <code>DevKit-mingw64-32-4.7.2-20130224-1151-sfx.exe</code> (32-bit for ruby 2x) extracted into <code>C:/Ruby200-devkit-x32</code>.</li> </ul> <p>I then installed <a href="https://github.com/vertiginous/pik" rel="noreferrer">Pik 0.2.8</a> as a gem and ran <code>pik_install</code> into a new directory <code>C:/bin</code> as per the installation instructions.</p> <p>My PATH looks like this:</p> <pre><code>PATH=C:\bin;C:\Ruby193\bin;C:\windows;C:\windows\system32;C:\windows\system32\Wbem;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Java\jdk1.6.0_33\bin;C:\Program Files (x86)\Common Files\Apple\Mobile Device Support\;C:\Program Files (x86)\Common Files\Apple\Apple Application Support;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\TortoiseSVN\bin;C:/inpath;C:\Program Files (x86)\WinMerge;C:\ChromeDriver;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64 </code></pre> <p>The important things being that <code>C:/bin</code> and <code>C:/Ruby193/bin</code> are in the path. This means that ruby 1.9.3 is loaded by default when I fire up a shell and I can successfully switch to 2.0.0 with <code>pik use 2.0.0p353</code>. In other words, pik works fine.</p> <p>Devkit <a href="https://github.com/oneclick/rubyinstaller/wiki/Development-Kit" rel="noreferrer">is intended</a> to allow the compiling of native C/C++ binaries from gems on Windows, so as to aviod using precompiled windows binaries.</p> <p>Because I've got two versions of ruby installed, and each requires a different devkit (one for 2x and one for 1x), I had to do the setup for devkit twice:</p> <pre><code>cd C:/Ruby193-devkit ruby dk.rb init # Edit config.yml to remove all but Ruby193 ruby dk.rb install cd C:/Ruby200-devkit ruby dk.rb init # Edit config.yml to remove all but C:/Ruby200 ruby dk.rb install </code></pre> <p>At this point I should have been able to run <code>gem install json —platform=ruby</code> successfully, but got the error above. After a little digging <a href="https://github.com/oneclick/rubyinstaller/wiki/Troubleshooting#wiki-gems_fails_comspec_autorun" rel="noreferrer">I discovered this</a>, which advises checking that COMSPEC is set corectly and removing any AutoRun keys from <code>HKEY_CURRENT_USER\Software\Microsoft\Command Processor</code> – I had one from ANSIcon and duly deleted it.</p> <p>Unfortunatly I was still unable to install the json gem.</p> <p>It then struck me that perhaps the wrong version of GCC was being used, or not being found. The two versions of Devkit come with different versions of gcc:</p> <pre><code>&gt; C:\Ruby193-devkit\mingw\bin\gcc —version gcc (tdm-1) 4.5.2 &gt; C:\Ruby200-devkit-x32\mingw\bin\gcc —version gcc (rubenv-4.7.2-release) 4.7.2 </code></pre> <p>I then wondered if pik wasn't loading the version of devtools (and therefore gcc) for the specific version of ruby that i'd picked, and was always using 1.9.3. Thanks to <a href="http://rubyonwindowsguides.github.io/book/ch02-04.html" rel="noreferrer">this article</a>, it seems that's not the case:</p> <pre><code>&gt; pik use 193 &gt; where ruby C:\Ruby193\bin\ruby.exe &gt; cat C:\Ruby193\lib\ruby\site_ruby\devkit.rb # enable RubyInstaller DevKit usage as a vendorable helper library unless ENV['PATH'].include?('C:\\Ruby193-devkit\\mingw\\bin') then puts 'Temporarily enhancing PATH to include DevKit...' ENV['PATH'] = 'C:\\Ruby193-devkit\\bin;C:\\Ruby193-devkit\\mingw\\bin;' + ENV['PATH'] end ENV['RI_DEVKIT'] = 'C:\\Ruby193-devkit' ENV['CC'] = 'gcc' ENV['CXX'] = 'g++' ENV['CPP'] = 'cpp' &gt; pik use 200 &gt; where ruby C:\Ruby200\bin\ruby.exe &gt; cat C:\Ruby200\lib\ruby\site_ruby\devkit.rb # enable RubyInstaller DevKit usage as a vendorable helper library unless ENV['PATH'].include?('C:\\Ruby200-devkit-x32\\mingw\\bin') then phrase = 'Temporarily enhancing PATH to include DevKit...' if defined?(Gem) Gem.ui.say(phrase) if Gem.configuration.verbose else puts phrase end puts "Prepending ENV['PATH'] to include DevKit..." if $DEBUG ENV['PATH'] = 'C:\\Ruby200-devkit-x32\\bin;C:\\Ruby200-devkit-x32\\mingw\\bin;' + ENV['PATH'] end ENV['RI_DEVKIT'] = 'C:\\Ruby200-devkit-x32' ENV['CC'] = 'gcc' ENV['CXX'] = 'g++' ENV['CPP'] = 'cpp' </code></pre> <p>(I don't actually have cat available on windows but it makes for a clearer explanation)</p> <p>As you can see, it looks like the correct version of devkit is being added to the path by devkit.rb, which is obviously being loaded because my error contains 'Temporarily enhancing PATH to include DevKit…'.</p> <h2>Back to the original error</h2> <p>It was:</p> <pre><code>The system cannot find the path specified. Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... The system cannot find the path specified. ERROR: Error installing json: ERROR: Failed to build gem native extension. C:/Ruby193/bin/ruby.exe extconf.rb creating Makefile Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1 for inspection. Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1/ext/json/ext/generator/gem_make.out </code></pre> <p>Unfortunatly the results log doesn't exactly offer much in the way of help. This is what gem_make.out looks like:</p> <pre><code>C:/Ruby193/bin/ruby.exe extconf.rb creating Makefile </code></pre> <p>I thought that <code>extconf.rb</code> might offer some help, but I can't make head nor tail of it:</p> <pre><code>require 'mkmf' unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3') $CFLAGS &lt;&lt; ' -O3' end if CONFIG['CC'] =~ /gcc/ $CFLAGS &lt;&lt; ' -Wall' unless $DEBUG &amp;&amp; !$CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb') $CFLAGS &lt;&lt; ' -O0 -ggdb' end end $defs &lt;&lt; "-DJSON_GENERATOR" create_makefile 'json/ext/generator' </code></pre> <p>The Makefile in <code>C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1/ext/json/ext/generator</code> <a href="https://gist.github.com/dannysmith/8043321" rel="noreferrer">looks like this</a>. It seems odd to me that this Makefile is even being created.</p> <p>If anybody with a bit more Windows/Ruby experience can shed any light on this it would be amazing!</p> <p>PS. I'm on Windows 7 Professional SP1</p> <h2>Update after some more digging</h2> <p>So I wanted to check that devkit was defiantly enhancing the path with the correct devkit directories. Thanks to a suggestion from another SO question, I moved the devkit installations inside the Ruby directories:</p> <p>The tdm devkit now lives in <code>C:\Ruby193\devkit</code> while the mingw64 lives in <code>C:\Ruby200\devkit</code>. Having run <code>ruby dk.rb install -f</code> for each devkit, I opened up both devkit.rb files to check that the path's had been updated correctly. They had, and I updated the puts so it should print "Temporarily enhancing PATH do include DevKit for 1.9" or "Temporarily enhancing PATH do include DevKit for 2". By way of confirmation that the correct devkit is being loaded:</p> <pre><code>C:\&gt;pik 193 C:\&gt;ruby -rdevkit -ve "puts ENV['PATH']" ruby 1.9.3p484 (2013-11-22) [i386-mingw32] Temporarily enhancing PATH to include DevKit for 1.9... C:\Ruby193\devkit\bin;C:\Ruby193\devkit\mingw\bin;C:\bin;C:\Ruby193\bin;C:\windows;C:\windows\system32;C:\windows\system32\Wbem;c:\Program Files (x86) \Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Pro gram Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Java\jdk1.6.0_33\bin;C:\Program Files (x86)\Common Files\Apple\Mobile Device Su pport\;C:\Program Files (x86)\Common Files\Apple\Apple Application Support;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\TortoiseSVN\bin ;C:/inpath;C:\Program Files (x86)\WinMerge;C:\ChromeDriver;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\sy swow64 C:\&gt;pik 200 C:\&gt;ruby -rdevkit -ve "puts ENV['PATH']" ruby 2.0.0p353 (2013-11-22) [i386-mingw32] Temporarily enhancing PATH to include DevKit for 2... C:\Ruby200\devkit\bin;C:\Ruby200\devkit\mingw\bin;C:\bin;C:\Ruby200\bin;C:\windows;C:\windows\system32;C:\windows\system32\Wbem;c:\Program Files (x86) \Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Pro gram Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Java\jdk1.6.0_33\bin;C:\Program Files (x86)\Common Files\Apple\Mobile Device Su pport\;C:\Program Files (x86)\Common Files\Apple\Apple Application Support;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\TortoiseSVN\bin ;C:/inpath;C:\Program Files (x86)\WinMerge;C:\ChromeDriver;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\sy swow64 </code></pre> <p>So that all looks like it works correctly. but:</p> <pre><code>C:\&gt;gem install json --platform=ruby Temporarily enhancing PATH to include DevKit for 2... Building native extensions. This could take a while... The system cannot find the path specified. ERROR: Error installing json: ERROR: Failed to build gem native extension. C:/Ruby200/bin/ruby.exe extconf.rb creating Makefile Gem files will remain installed in C:/Ruby200/lib/ruby/gems/2.0.0/gems/json-1.8.1 for inspection. Results logged to C:/Ruby200/lib/ruby/gems/2.0.0/gems/json-1.8.1/ext/json/ext/generator/gem_make.out C:\&gt;pik 193 C:\&gt;gem install json --platform=ruby Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... The system cannot find the path specified. ERROR: Error installing json: ERROR: Failed to build gem native extension. C:/Ruby193/bin/ruby.exe extconf.rb creating Makefile Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1 for inspection. Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/gems/json-1.8.1/ext/json/ext/generator/gem_make.out </code></pre> <p>This clearly tells us two things:</p> <ol> <li>Some other devkit.rb file is being loaded when I'm using ruby 1.9, as the 'for 1.9' message isn't being printed.</li> <li>This is unlikely to be the actual problem, as the error is identical in either case.</li> </ol> <p>I'm going to see if I can build manually using the generated Makefiles.</p>
0
4,287
Force each row in Bootstrap table to be a one-liner when table is wider than screen
<p>I am building up a dynamic table which consists of 1-50 columns depending what the user selects. When the user selects 1-6 colums there is no problem showing all the data on the screen but when the user selects more than 6 columns the table tries to squeeze the view together on the screen resulting in each row being expanded to multiple lines.</p> <p>I want it to always show the text in one line as this (OK): <a href="https://i.stack.imgur.com/XWAFp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XWAFp.png" alt="OK"></a></p> <p>But having many columns will wrap the text in to two or more lines (not OK): <a href="https://i.stack.imgur.com/F8skR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F8skR.png" alt="Not OK"></a></p> <p>The column width is not defined as it also varies depending on the text to show.</p> <p>How can I make sure the row will always be a one-liner like ex.1 no matter how many columns the user selects?</p> <p>I have this <a href="http://jsfiddle.net/wNPBp/1/" rel="noreferrer">JSFiddle demo</a> with the code for the two above examples:</p> <pre><code>&lt;table class='table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Column 1&lt;/th&gt; &lt;th&gt;Column 2&lt;/th&gt; &lt;th&gt;Column 3&lt;/th&gt; &lt;th&gt;Column 4&lt;/th&gt; &lt;th&gt;Column 5&lt;/th&gt; &lt;th&gt;Column 6&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Row 1&lt;/td&gt; &lt;td&gt;Row 11&lt;/td&gt; &lt;td&gt;Row 11 1&lt;/td&gt; &lt;td&gt;Row 11 11&lt;/td&gt; &lt;td&gt;Row 11 11 1&lt;/td&gt; &lt;td&gt;Row 11 11 11&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Row 2&lt;/td&gt; &lt;td&gt;Row 22&lt;/td&gt; &lt;td&gt;Row 22 2&lt;/td&gt; &lt;td&gt;Row 22 22&lt;/td&gt; &lt;td&gt;Row 22 22 2&lt;/td&gt; &lt;td&gt;Row 22 22 22&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
0
1,075
Prevent resubmit form after click "back" button
<p>I have 2 pages :<br/><br/> <strong>page1.php :</strong><br/> - has a form with text box and a "submit" button. Eg : <code>&lt;form name="frm_register" action="page1.php" method="post"&gt;</code><br/><br/> - php and mysql code to store the value of textbox to database. Javascript will redirect the page to <code>php2.php</code> after the value is submitted to database. Eg : </p> <pre><code>$query = "INSERT INTO traceuser (username) VALUES ('{$username}')"; $result = mysql_query($query, $connection); echo '&lt;script language="javascript"&gt;window.location="page2.php";&lt;/script&gt;'; </code></pre> <p><strong>page2.php</strong><br/> - mysql retrieve the data from database and display on this page.<br/></p> <p><strong>Problem :</strong> When I press "back" button, the browser will pop up a warning message saying that the form will be resubmit. How to prevent resubmit the form when click "back" button? Is it I need to clear the cache of page1.php? How to do it with php or javascript or ajax?</p> <p><hr> <strong>Update 1 :</strong> Thanks for the answer of replacing javascript <code>window.location="page2.php"</code> to php <code>header('Location: home2.php');</code>. It fix 80% of problem. The rest of 20% problem show below :</p> <pre><code> if (strtotime($_SESSION['servertime']) &lt; time()-3){ //10800 = 3 hours 3600 = 1 hour if (($username != "") AND ($username != $_SESSION[username])){ $_SESSION['servertime'] = $servertime; $_SESSION['username'] = $username; $query = "INSERT INTO traceuser (username) VALUES ('{$username}')"; $result = mysql_query($query20, $connection); header('Location: page2.php'); exit; } else { echo "same name"; //problem here } }else{ echo "submit multiple data too fast"; //problem here too. } } </code></pre> <p>The problem happen when do the following steps :<br/> 1) User submit data successfully, jump to page2.php view records.<br/> 2) User click "back" button, jump back to page1.php.<br/> 3) User submit data fail, stay on page1.php. (because too fast or same name)<br/> 4) User submit data successful, jump to page2.php view records.<br/> 5) User click "back" button, but browser shows warning message "form will be resubmited".<br/></p> <p>The problem is because of Step 3. Step 3 didn't run <code>header('Location: page2.php');</code>, didn't jump to page2.php. So it cause Step 5 show the warning message. How to fix this problem? <hr> <strong>Update 2 :</strong> I have figured out the solution to fix the 20% problem, it works perfectly. I use <code>session['error123']</code> to decide whether or not want to display the error message "same name". I kill <code>session['error123']</code> if success submit data to database or if success jump to page2.php. I also use <code>header('Location: page1.php');</code> to redirect to own page (same page) to make the page forget about form submission previously. Example of codes :</p> <pre><code>if ($_SESSION['error123'] == "toofast"){ echo $_SESSION['error123'] ; }elseif ($_SESSION['error123'] == "samename"){ echo $_SESSION['error123'] ; } if (strtotime($_SESSION['servertime']) &lt; time()-3){ //10800 = 3 hours 3600 = 1 hour if (($username != "") AND ($username != $_SESSION['username'])){ $_SESSION['username'] = $username; $query = "INSERT INTO traceuser (username) VALUES ('{$username}')"; $result = mysql_query($query20, $connection); $_SESSION['error123'] = "aa"; header('Location: http://localhost/plekz/page2.php'); exit; } else { $_SESSION['error123'] = "samename"; header('Location: http://localhost/plekz/page1.php'); exit; } }else{ $_SESSION['error123'] = "toofast"; header('Location: http://localhost/plekz/page1.php'); exit; } } } </code></pre> <p>Note : You need to buffer the output by <code>&lt;?php ob_start();?&gt;</code> because $_SESSION cannot put before header(). Buffer will stop all output including session, let header() send the output first.</p>
0
1,786
Parsing error "parserOptions.project" has been set for @typescript-eslint/parser
<p>I created a new <a href="https://docs.nestjs.com/" rel="noreferrer">NestJS project</a> which is a very popular NodeJS framework. But I have this error (see title) on my IDE (PhpStorm 2020.2-Beta) and ESLint doesn't work at all.</p> <p>I've used the NestJS CLI :</p> <pre><code>nest new nestjs-micro </code></pre> <p>I don't seem to be the only one with this problem, so it would be nice to find the cause of this problem and <strong>fix it once and for all.</strong></p> <p>I already have an open <a href="https://github.com/typescript-eslint/typescript-eslint/issues/2303" rel="noreferrer">issue</a> but I haven't had an answer, this is really very problematic.</p> <p>If anyone has an idea on how to fix the problem and <strong>keeping an ESLint / Prettier integration with PhpStorm</strong>, thanks.</p> <p><strong>Repro</strong></p> <pre class="lang-js prettyprint-override"><code>// .eslintrc.js module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier', 'prettier/@typescript-eslint', ], root: true, env: { node: true, jest: true, }, rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', }, }; </code></pre> <pre><code>// tsconfig.json { &quot;compilerOptions&quot;: { &quot;module&quot;: &quot;commonjs&quot;, &quot;declaration&quot;: true, &quot;removeComments&quot;: true, &quot;emitDecoratorMetadata&quot;: true, &quot;experimentalDecorators&quot;: true, &quot;allowSyntheticDefaultImports&quot;: true, &quot;target&quot;: &quot;es2017&quot;, &quot;sourceMap&quot;: true, &quot;outDir&quot;: &quot;./dist&quot;, &quot;baseUrl&quot;: &quot;./&quot;, &quot;incremental&quot;: true } } </code></pre> <p><strong>Additional Info</strong> <a href="https://user-images.githubusercontent.com/42717232/87725198-1d260a00-c7bd-11ea-9520-fd0d69fd7790.png" rel="noreferrer"><img src="https://user-images.githubusercontent.com/42717232/87725198-1d260a00-c7bd-11ea-9520-fd0d69fd7790.png" alt="Screenshot_20200716_233543" /></a></p> <p><strong>Versions</strong></p> <pre><code>Typescript: 3.7.4 Node: 14.3.0 ESLint: 7.1.0 @typescript-eslint/parser: 3.0.2 Yarn: 1.22.4 </code></pre>
0
1,078
Spring Maven repository issue
<p>A sample Spring project contains the following POM file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &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/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.prospinghibernate.gallery&lt;/groupId&gt; &lt;artifactId&gt;gallery&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;name&gt;gallery&lt;/name&gt; &lt;properties&gt; &lt;spring.version&gt;3.0.2.RELEASE&lt;/spring.version&gt; &lt;hibernate.version&gt;3.5.0-Final&lt;/hibernate.version&gt; &lt;/properties&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;JBoss Repo&lt;/id&gt; &lt;url&gt;http://repository.jboss.com/maven2&lt;/url&gt; &lt;name&gt;JBoss Repo&lt;/name&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;ibiblio mirror&lt;/id&gt; &lt;url&gt;http://mirrors.ibiblio.org/pub/mirrors/maven2/&lt;/url&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;jboss-public-repository-group&lt;/id&gt; &lt;name&gt;JBoss Public Maven Repository Group&lt;/name&gt; &lt;url&gt;https://repository.jboss.org/nexus/content/groups/public/&lt;/url&gt; &lt;layout&gt;default&lt;/layout&gt; &lt;releases&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;updatePolicy&gt;never&lt;/updatePolicy&gt; &lt;/releases&gt; &lt;snapshots&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;updatePolicy&gt;never&lt;/updatePolicy&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;!-- General dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.15&lt;/version&gt; &lt;!-- Exclusions only required for version 1.2.15 of log4j --&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;javax.mail&lt;/groupId&gt; &lt;artifactId&gt;mail&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;javax.jms&lt;/groupId&gt; &lt;artifactId&gt;jms&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;com.sun.jdmk&lt;/groupId&gt; &lt;artifactId&gt;jmxtools&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;com.sun.jmx&lt;/groupId&gt; &lt;artifactId&gt;jmxri&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;version&gt;1.6.0&lt;/version&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;1.6.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;version&gt;1.6.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt; &lt;version&gt;1.6.9.M2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- file upload dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-fileupload&lt;/groupId&gt; &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt; &lt;version&gt;1.2.1&lt;/version&gt; &lt;/dependency&gt; &lt;!-- image processing dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.media&lt;/groupId&gt; &lt;artifactId&gt;jai-core&lt;/artifactId&gt; &lt;version&gt;1.1.3&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring dependencies --&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;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-test&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&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-context&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-context-support&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-aop&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-aspects&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-tx&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring MVC dependencies --&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;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-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;!--Spring OXM--&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;!-- JSP dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- H2 dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;com.h2database&lt;/groupId&gt; &lt;artifactId&gt;h2&lt;/artifactId&gt; &lt;version&gt;1.2.131&lt;/version&gt; &lt;/dependency&gt; &lt;!-- ehcache dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt; &lt;artifactId&gt;ehcache&lt;/artifactId&gt; &lt;version&gt;1.6.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Hibernate dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt; &lt;artifactId&gt;ehcache&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;asm&lt;/groupId&gt; &lt;artifactId&gt;asm&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;asm&lt;/groupId&gt; &lt;artifactId&gt;asm-attrs&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;javax.transaction&lt;/groupId&gt; &lt;artifactId&gt;jta&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&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;${hibernate.version}&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;dom4j&lt;/groupId&gt; &lt;artifactId&gt;dom4j&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate.javax.persistence&lt;/groupId&gt; &lt;artifactId&gt;hibernate-jpa-2.0-api&lt;/artifactId&gt; &lt;version&gt;1.0.0.Final&lt;/version&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.0.2.GA&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.validation&lt;/groupId&gt; &lt;artifactId&gt;validation-api&lt;/artifactId&gt; &lt;version&gt;1.0.0.GA&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib-nodep&lt;/artifactId&gt; &lt;version&gt;2.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.transaction&lt;/groupId&gt; &lt;artifactId&gt;jta&lt;/artifactId&gt; &lt;version&gt;1.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&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-orm&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-pool&lt;/groupId&gt; &lt;artifactId&gt;commons-pool&lt;/artifactId&gt; &lt;version&gt;1.5.4&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;commons-dbcp&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt; &lt;version&gt;1.3&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;exclusion&gt; &lt;groupId&gt;commons-pool&lt;/groupId&gt; &lt;artifactId&gt;commons-pool&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;xerces&lt;/groupId&gt; &lt;artifactId&gt;xerces&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;xerces&lt;/groupId&gt; &lt;artifactId&gt;xercesImpl&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;xml-apis&lt;/groupId&gt; &lt;artifactId&gt;xml-apis&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;!--Hibernate Search--&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-search&lt;/artifactId&gt; &lt;version&gt;3.2.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!--Dozer --&gt; &lt;dependency&gt; &lt;groupId&gt;net.sf.dozer&lt;/groupId&gt; &lt;artifactId&gt;dozer&lt;/artifactId&gt; &lt;version&gt;5.2.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.xmlbeans&lt;/groupId&gt; &lt;artifactId&gt;xmlbeans&lt;/artifactId&gt; &lt;version&gt;2.4.0&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Testing dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jmock&lt;/groupId&gt; &lt;artifactId&gt;jmock-junit4&lt;/artifactId&gt; &lt;version&gt;2.5.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1-beta-1&lt;/version&gt; &lt;/plugin&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.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.6&lt;/source&gt; &lt;target&gt;1.6&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt; &lt;version&gt;2.2-beta-5&lt;/version&gt; &lt;configuration&gt; &lt;descriptorRefs&gt; &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt; &lt;/descriptorRefs&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-deploy-plugin&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;tomcat-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;maven-jetty-plugin&lt;/artifactId&gt; &lt;version&gt;6.1.22&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I get the following error message when I try to run the Spring sample application:</p> <blockquote> <p>Failed to execute goal on project gallery: Could not resolve dependencies for project com.prospinghibernate.gallery:gallery:war:1.0.0-SNAPSHOT: Failed to collect dependencies for [log4j:log4j:jar:1.2.15 (compile), org.slf4j:slf4j-api:jar:1.6.0 (compile), org.slf4j:jcl-over-slf4j:jar:1.6.0 (compile), org.slf4j:slf4j-log4j12:jar:1.6.0 (compile), org.aspectj:aspectjrt:jar:1.6.9.M2 (compile), javax.servlet:servlet-api:jar:2.5 (provided), commons-fileupload:commons-fileupload:jar:1.2.1 (compile), javax.media:jai-core:jar:1.1.3 (compile), org.springframework:spring-core:jar:3.0.2.RELEASE (compile), org.springframework:spring-test:jar:3.0.2.RELEASE (test), org.springframework:spring-context:jar:3.0.2.RELEASE (compile), org.springframework:spring-context-support:jar:3.0.2.RELEASE (compile), org.springframework:spring-aop:jar:3.0.2.RELEASE (compile), org.springframework:spring-aspects:jar:3.0.2.RELEASE (compile), org.springframework:spring-tx:jar:3.0.2.RELEASE (compile), org.springframework:spring-web:jar:3.0.2.RELEASE (compile), org.springframework:spring-webmvc:jar:3.0.2.RELEASE (compile), org.springframework:spring-oxm:jar:3.0.2.RELEASE (compile), jstl:jstl:jar:1.2 (compile), com.h2database:h2:jar:1.2.131 (compile), net.sf.ehcache:ehcache:jar:1.6.2 (compile), org.hibernate:hibernate-core:jar:3.5.0-Final (compile), org.hibernate:hibernate-entitymanager:jar:3.5.0-Final (compile), org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.0.Final (compile), org.hibernate:hibernate-validator:jar:4.0.2.GA (compile), javax.validation:validation-api:jar:1.0.0.GA (compile), cglib:cglib-nodep:jar:2.2 (compile), javax.transaction:jta:jar:1.1 (compile), org.springframework:spring-jdbc:jar:3.0.2.RELEASE (compile), org.springframework:spring-orm:jar:3.0.2.RELEASE (compile), commons-pool:commons-pool:jar:1.5.4 (compile), commons-dbcp:commons-dbcp:jar:1.3 (compile), org.hibernate:hibernate-search:jar:3.2.1.Final (compile), net.sf.dozer:dozer:jar:5.2.2 (compile), org.apache.xmlbeans:xmlbeans:jar:2.4.0 (compile), junit:junit:jar:4.8.1 (test), org.jmock:jmock-junit4:jar:2.5.1 (test)]: Failed to read artifact descriptor for org.aspectj:aspectjrt:jar:1.6.9.M2: Could not transfer artifact org.aspectj:aspectjrt:pom:1.6.9.M2 from/to JBoss Repo (<a href="http://repository.jboss.com/maven2" rel="nofollow">http://repository.jboss.com/maven2</a>): Access denied to: <a href="http://repository.jboss.com/maven2/org/aspectj/aspectjrt/1.6.9.M2/aspectjrt-1.6.9.M2.pom" rel="nofollow">http://repository.jboss.com/maven2/org/aspectj/aspectjrt/1.6.9.M2/aspectjrt-1.6.9.M2.pom</a> -> [Help 1]</p> </blockquote>
0
12,549
Renaming an uploaded file using Multer doesn't work (Express.js)
<p>I'm trying to upload a file from a HTML form using Express.js and Multer. I've managed to save the file to the desired location (a folder named <em>uploads</em>).</p> <p>However, I'd like to rename the file while uploading it because, by default, Multer gives it a strange name such as:</p> <blockquote> <p>5257ee6b035926ca99923297c224a1bb</p> </blockquote> <p>Might be a hexadecimal time stamp or so but I need a more explicit name in order to call a script on it later.</p> <p>I've followed the explanation found <a href="https://stackoverflow.com/questions/29214237/rename-a-file-with-multer-is-not-working">here</a> but it doesn't do anything more than it used to: uploading the file with the hexa name.</p> <p>Also, the two events <strong>onFileUploadStart</strong> and <strong>onFileUploadComplete</strong> never seem to be triggered as I don't get anything logged in my console.</p> <p>I am using two separate files for the server and the routing:</p> <p><strong><em>app.js</em></strong></p> <pre><code>/** * Dependencies */ var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); /** * Importation of routes */ var routes = require('./routes/index'); var recog = require('./routes/recog'); /** * Express */ var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // pour contrer les erreurs de cross domain app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); /** * Routes */ app.use('/', routes); app.use('/recog', recog); module.exports = app; </code></pre> <p><strong><em>recog.js</em></strong></p> <pre><code>/** * Requirements */ var express = require('express'); var router = express.Router(); var multer = require('multer'); var uploads = multer({ dest: 'uploads/', rename: function (fieldname, filename) { console.log("Rename..."); return filename + Date.now(); }, onFileUploadStart: function () { console.log("Upload is starting..."); }, onFileUploadComplete: function () { console.log("File uploaded"); } }); /** * Upload d'une image */ router.post('/upload', uploads.single('image'), function (req, res, next) { console.log("Front-end is calling"); res.json({status: 'success', data: 'Fichier chargé.\nOrgane sélectionné : ' + req.body.organ}); }); module.exports = router; </code></pre> <p>I have been digging around but I can't figure out what the problem is as I am quite new to Node.js and JavaScript in general.</p> <p>Thanks for your help guys!</p>
0
1,143
Installing lxml with pip in virtualenv Ubuntu 12.10 error: command 'gcc' failed with exit status 4
<p>I'm having the following error when trying to run "pip install lxml" into a virtualenv in Ubuntu 12.10 x64. I have Python 2.7.</p> <p>I have seen other related questions here about the same problem and tried installing python-dev, libxml2-dev and libxslt1-dev.</p> <p>Please take a look of the traceback from the moment I tip the command to the moment when the error occurs.</p> <pre> Downloading/unpacking lxml Running setup.py egg_info for package lxml /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) Building lxml version 3.1.2. Building without Cython. Using build configuration of libxslt 1.1.26 Building against libxml2/libxslt in the following directory: /usr/lib warning: no files found matching '*.txt' under directory 'src/lxml/tests' Installing collected packages: lxml Running setup.py install for lxml /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) Building lxml version 3.1.2. Building without Cython. Using build configuration of libxslt 1.1.26 Building against libxml2/libxslt in the following directory: /usr/lib building 'lxml.etree' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/home/admin/.virtualenvs/dev.actualito.com/build/lxml/src/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o src/lxml/lxml.etree.c: In function '__pyx_f_4lxml_5etree__getFilenameForFile': src/lxml/lxml.etree.c:26851:7: warning: variable '__pyx_clineno' set but not used [-Wunused-but-set-variable] src/lxml/lxml.etree.c:26850:15: warning: variable '__pyx_filename' set but not used [-Wunused-but-set-variable] src/lxml/lxml.etree.c:26849:7: warning: variable '__pyx_lineno' set but not used [-Wunused-but-set-variable] src/lxml/lxml.etree.c: In function '__pyx_pf_4lxml_5etree_4XSLT_18__call__': src/lxml/lxml.etree.c:138273:81: warning: passing argument 1 of '__pyx_f_4lxml_5etree_12_XSLTContext__copy' from incompatible pointer type [enabled by default] src/lxml/lxml.etree.c:136229:52: note: expected 'struct __pyx_obj_4lxml_5etree__XSLTContext *' but argument is of type 'struct __pyx_obj_4lxml_5etree__BaseContext *' src/lxml/lxml.etree.c: In function '__pyx_f_4lxml_5etree__copyXSLT': src/lxml/lxml.etree.c:139667:79: warning: passing argument 1 of '__pyx_f_4lxml_5etree_12_XSLTContext__copy' from incompatible pointer type [enabled by default] src/lxml/lxml.etree.c:136229:52: note: expected 'struct __pyx_obj_4lxml_5etree__XSLTContext *' but argument is of type 'struct __pyx_obj_4lxml_5etree__BaseContext *' src/lxml/lxml.etree.c: At top level: src/lxml/lxml.etree.c:12384:13: warning: '__pyx_f_4lxml_5etree_displayNode' defined but not used [-Wunused-function] gcc: internal compiler error: Killed (program cc1) Please submit a full bug report, with preprocessed source if appropriate. See for instructions. error: command 'gcc' failed with exit status 4 Complete output from command /home/admin/.virtualenvs/dev.actualito.com/bin/python -c "import setuptools;__file__='/home/admin/.virtualenvs/dev.actualito.com/build/lxml/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-asDtN5-record/install-record.txt --single-version-externally-managed --install-headers /home/admin/.virtualenvs/dev.actualito.com/include/site/python2.7: /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) Building lxml version 3.1.2. Building without Cython. Using build configuration of libxslt 1.1.26 Building against libxml2/libxslt in the following directory: /usr/lib running install running build running build_py copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.7/lxml/includes running build_ext building 'lxml.etree' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/home/admin/.virtualenvs/dev.actualito.com/build/lxml/src/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o src/lxml/lxml.etree.c: In function '__pyx_f_4lxml_5etree__getFilenameForFile': src/lxml/lxml.etree.c:26851:7: warning: variable '__pyx_clineno' set but not used [-Wunused-but-set-variable] src/lxml/lxml.etree.c:26850:15: warning: variable '__pyx_filename' set but not used [-Wunused-but-set-variable] src/lxml/lxml.etree.c:26849:7: warning: variable '__pyx_lineno' set but not used [-Wunused-but-set-variable] src/lxml/lxml.etree.c: In function '__pyx_pf_4lxml_5etree_4XSLT_18__call__': src/lxml/lxml.etree.c:138273:81: warning: passing argument 1 of '__pyx_f_4lxml_5etree_12_XSLTContext__copy' from incompatible pointer type [enabled by default] src/lxml/lxml.etree.c:136229:52: note: expected 'struct __pyx_obj_4lxml_5etree__XSLTContext *' but argument is of type 'struct __pyx_obj_4lxml_5etree__BaseContext *' src/lxml/lxml.etree.c: In function '__pyx_f_4lxml_5etree__copyXSLT': src/lxml/lxml.etree.c:139667:79: warning: passing argument 1 of '__pyx_f_4lxml_5etree_12_XSLTContext__copy' from incompatible pointer type [enabled by default] src/lxml/lxml.etree.c:136229:52: note: expected 'struct __pyx_obj_4lxml_5etree__XSLTContext *' but argument is of type 'struct __pyx_obj_4lxml_5etree__BaseContext *' src/lxml/lxml.etree.c: At top level: src/lxml/lxml.etree.c:12384:13: warning: '__pyx_f_4lxml_5etree_displayNode' defined but not used [-Wunused-function] gcc: internal compiler error: Killed (program cc1) Please submit a full bug report, with preprocessed source if appropriate. See for instructions. error: command 'gcc' failed with exit status 4 ---------------------------------------- Command /home/admin/.virtualenvs/dev.actualito.com/bin/python -c "import setuptools;__file__='/home/admin/.virtualenvs/dev.actualito.com/build/lxml/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-asDtN5-record/install-record.txt --single-version-externally-managed --install-headers /home/admin/.virtualenvs/dev.actualito.com/include/site/python2.7 failed with error code 1 in /home/admin/.virtualenvs/dev.actualito.com/build/lxml Storing complete log in /home/admin/.pip/pip.log </pre>
0
2,535
Exception: Error when checking model target: expected dense_3 to have shape (None, 1000) but got array with shape (32, 2)
<p>How do I create a VGG-16 sequence for my data?</p> <p>The data has the following :</p> <pre><code>model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(256, 3, 3, activation='relu', name='conv3_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv4_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_2')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(512, 3, 3, activation='relu', name='conv5_3')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(Flatten()) model.add(Dense(4096, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(4096, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1000, activation='softmax')) sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss='categorical_crossentropy') train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=32) validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=32) model.fit_generator( train_generator, samples_per_epoch=2000, nb_epoch=1, verbose=1, validation_data=validation_generator, nb_val_samples=800) json_string = model.to_json() open('my_model_architecture.json','w').write(json_string) model.save_weights('Second_try.h5') </code></pre> <p>I got an error:</p> <blockquote> <p>Exception: Error when checking model target: expected dense_3 to have shape (None, 32) but got array with shape (32, 2)</p> </blockquote> <p>How do I change <code>Dense</code> to make it work?</p>
0
1,399
coverage.py does not cover script if py.test executes it from another directory
<p>I got a python script which takes command line arguments, working with some files. I'm writing succeeding tests with <code>py.test</code> putting this script through its paces, executing it with <code>subprocess.call</code>.</p> <p>Now I want to analyze code coverage with <code>coverage.py</code>. Coverage, when used via the <code>pytest-cov</code> plugin (which has subprocess-handling built-in), <strong>does not see/cover my script</strong> when it is called from a temporary testing directory created with <code>py.test</code>'s <code>tmpdir</code> fixture. Coverage <strong>does see</strong> my script when it's called in the directory it resides in (and the filename argument points to a remote path).</p> <p>In both situations, my <strong>tests pass</strong>! Coverage 3.6, pytest-2.3.5, pytest-cov 1.6, all from PyPi.</p> <p>Question: How can I get coverage to recognize my script even if it's executed in another directory? Is this a bug in coverage, or something which is just not possible to do? Would be surprised if the latter, after all, <code>tmpdir</code> is a stock mechanism of py.test...</p> <p><strong>Minimal example:</strong></p> <p>I got a script <code>my_script.py</code> which just echoes the contents of a file <code>arg_file.txt</code> supplied via command-line argument. In two different tests, this is once called in a <code>tmpdir</code>, and once in the script's location. Both tests pass, but the in the tmpdir test, I get no coverage information! </p> <p>Test run:</p> <pre><code>~/pytest_experiment$ py.test -s =================================== test session starts ==================================== platform linux2 -- Python 2.7.4 -- pytest-2.3.5 plugins: cov collected 2 items tests/test_in_scriptdir.py set_up: In directory /tmp/pytest-52/test_10 Running in directory /home/cbuchner/pytest_experiment Command: ./my_script.py /tmp/pytest-52/test_10/arg_file.txt --Contents of arg_file.txt-- . tests/test_in_tmpdir.py set_up: In directory /tmp/pytest-52/test_11 Running in directory /tmp/pytest-52/test_11 Command: /home/cbuchner/pytest_experiment/my_script.py arg_file.txt --Contents of arg_file.txt-- . ================================= 2 passed in 0.06 seconds ================================= </code></pre> <p>Coverage: </p> <pre><code>~/pytest_experiment$ py.test --cov=my_script.py tests/test_in_scriptdir.py=================================== test session starts ==================================== platform linux2 -- Python 2.7.4 -- pytest-2.3.5 plugins: cov collected 1 items tests/test_in_scriptdir.py . --------------------- coverage: platform linux2, python 2.7.4-final-0 ---------------------- Name Stmts Miss Cover ------------------------------- my_script 3 0 100% ================================= 1 passed in 0.09 seconds ================================= ~/pytest_experiment$ py.test --cov=my_script.py tests/test_in_tmpdir.py=================================== test session starts ==================================== platform linux2 -- Python 2.7.4 -- pytest-2.3.5 plugins: cov collected 1 items tests/test_in_tmpdir.py .Coverage.py warning: No data was collected. --------------------- coverage: platform linux2, python 2.7.4-final-0 ---------------------- Name Stmts Miss Cover --------------------------- ================================= 1 passed in 0.09 seconds ================================= </code></pre> <p>The files are here: <a href="https://gist.github.com/bilderbuchi/6412754">https://gist.github.com/bilderbuchi/6412754</a></p> <p><strong>Edit:</strong> Interstingly, when running the coverage tests with <code>-s</code>, too, there's more curious output - coverage warns that <code>No data was collected</code>, when obviously it was collected, and in the <code>tmpdir</code> test warns that <code>Module my_script.py was never imported.</code>??</p> <pre><code>~/pytest_experiment$ py.test -s --cov=my_script.py tests/test_in_scriptdir.py =================================== test session starts ==================================== platform linux2 -- Python 2.7.4 -- pytest-2.3.5 plugins: cov collected 1 items tests/test_in_scriptdir.py set_up: In directory /tmp/pytest-63/test_10 Running in directory /home/cbuchner/pytest_experiment Command: ./my_script.py /tmp/pytest-63/test_10/arg_file.txt --Contents of arg_file.txt-- Coverage.py warning: No data was collected. . --------------------- coverage: platform linux2, python 2.7.4-final-0 ---------------------- Name Stmts Miss Cover ------------------------------- my_script 3 0 100% ================================= 1 passed in 0.09 seconds ================================= ~/pytest_experiment$ py.test -s --cov=my_script.py tests/test_in_tmpdir.py=================================== test session starts ==================================== platform linux2 -- Python 2.7.4 -- pytest-2.3.5 plugins: cov collected 1 items tests/test_in_tmpdir.py set_up: In directory /tmp/pytest-64/test_10 Running in directory /tmp/pytest-64/test_10 Command: /home/cbuchner/pytest_experiment/my_script.py arg_file.txt --Contents of arg_file.txt-- Coverage.py warning: Module my_script.py was never imported. Coverage.py warning: No data was collected. Coverage.py warning: Module my_script.py was never imported. Coverage.py warning: No data was collected. .Coverage.py warning: No data was collected. --------------------- coverage: platform linux2, python 2.7.4-final-0 ---------------------- Name Stmts Miss Cover --------------------------- ================================= 1 passed in 0.09 seconds ================================= </code></pre>
0
1,694
ClassNotFoundException upon running JAR, no errors while running in IntelliJ IDEA
<p>I'm just starting to build Java apps (I do have .NET experience) and I was trying to build a small test app whose whole code is this :</p> <pre><code>package com.company; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Main { public static void main(String[] args) throws SQLException { System.out.println("Buna lume!"); SQLServerDataSource ds = new SQLServerDataSource(); ds.setIntegratedSecurity(true); ds.setServerName("localhost"); ds.setPortNumber(1433); ds.setDatabaseName("Test"); Connection con = ds.getConnection(); String SQL = "SELECT * FROM Test WHERE ID = ?"; PreparedStatement stmt = con.prepareStatement(SQL); stmt.setInt(1, 2); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getInt(1) + ", " + rs.getString(2)); } rs.close(); stmt.close(); con.close(); } } </code></pre> <p>If I run the app in the IDE (IntelliJ IDEA 12.1.6 Community Edition), having the SQL Server available, the app runs fine doing exactly what it should.</p> <p>The SQL Server Driver is downloaded from Microsoft and added as an External Library. I have created an artifact as JAR file :</p> <p><img src="https://i.stack.imgur.com/OJFn4.png" alt="enter image description here"></p> <p>Now, if I include the sqljdbc4.jar in the cliTest.jar (my JAR) the resulted JAR is fat (550kB and includes the classes in that JAR too). Or I can exclude it. Either way, running</p> <pre><code>java -jar cliTest.jar </code></pre> <p>Results in </p> <pre><code>Buna lume! Exception in thread "main" java.lang.NoClassDefFoundError: com/microsoft/sqlserv er/jdbc/SQLServerDataSource at com.company.Main.main(Main.java:15) Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLSer verDataSource at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more </code></pre> <p>I bet I'm missing something quite basic but I just can't figure out what exactly is causing this.</p> <p>LE1 : I tried adding sqljdbc4.jar (although it didn't seem necessary) and sqljdbc_auth.dll in the directory containing the JAR but still no change.</p> <p>Later edit 2 : Based on Nikolay's answer I've done the following :</p> <ol> <li>Deleted the existing artifact</li> <li>Created a new artifact like so :</li> </ol> <p><img src="https://i.stack.imgur.com/FJIAn.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/nw70Z.png" alt="enter image description here"></p> <p>.. and resulted this :</p> <p><img src="https://i.stack.imgur.com/fLZQ1.png" alt="enter image description here"></p> <ol start="3"> <li><p>Build -> Build artifacts -> cliTest.jar -> Rebuild</p></li> <li><p>CMD Prompt at the folder containing :</p></li> </ol> <p>[cliTest.jar 566 KB was generated]</p> <p>java -jar cliTest.jar</p> <p>Now I get :</p> <pre><code>Exception in thread "main" java.lang.SecurityException: Invalid signature file d igest for Manifest main attributes at sun.security.util.SignatureFileVerifier.processImpl(Unknown Source) at sun.security.util.SignatureFileVerifier.process(Unknown Source) at java.util.jar.JarVerifier.processEntry(Unknown Source) at java.util.jar.JarVerifier.update(Unknown Source) at java.util.jar.JarFile.initializeVerifier(Unknown Source) at java.util.jar.JarFile.getInputStream(Unknown Source) at sun.misc.URLClassPath$JarLoader$2.getInputStream(Unknown Source) at sun.misc.Resource.cachedInputStream(Unknown Source) at sun.misc.Resource.getByteBuffer(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) </code></pre>
0
1,743
"Cannot call value of non-function type"
<p>I have just downloaded the Xcode 8 Beta so that I can include some of the new iOS 10 frameworks in my app. However, during the process of converting my code from Swift 2 to Swift 3, I ran into several errors. I fixed all but one super annoying one. </p> <p>I am getting the error:</p> <blockquote> <p>Cannot call value of non-function type 'JSQMessagesCollectionView!' at the following line of code:</p> </blockquote> <pre><code>let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell </code></pre> <p>Here is my entire function for context:</p> <pre><code>func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell{ let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell let message = messages[indexPath.item] if message.senderId == senderId { cell.textView!.textColor = UIColor.whiteColor() } else { cell.textView!.textColor = UIColor.blackColor() } return cell } </code></pre> <p>Does anybody have an ideas?</p> <p>P.s. If this helps, here is my entire block of code:</p> <pre><code>import UIKit import Firebase import JSQMessagesViewController class ChatViewController: JSQMessagesViewController { // MARK: Properties var rootRef = FIRDatabase.database().reference() var messageRef: FIRDatabaseReference! var messages = [JSQMessage]() var outgoingBubbleImageView: JSQMessagesBubbleImage! var incomingBubbleImageView: JSQMessagesBubbleImage! var userIsTypingRef: FIRDatabaseReference! // 1 private var localTyping = false // 2 var isTyping: Bool { get { return localTyping } set { // 3 localTyping = newValue userIsTypingRef.setValue(newValue) } } var usersTypingQuery: FIRDatabaseQuery! override func viewDidLoad() { super.viewDidLoad() // Change the navigation bar background color to blue. // navigationController!.navigationBar.barTintColor = UIColor.init(red:252/255, green: 87/255, blue: 68/255, alpha: 1) navigationController!.navigationBar.barTintColor = UIColor.init(red:250/255, green: 69/255, blue: 85/255, alpha: 1) title = "RoastChat" setupBubbles() // No avatars collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero // Remove file upload icon self.inputToolbar.contentView.leftBarButtonItem = nil; messageRef = rootRef.child("messages") } func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) observeMessages() observeTyping() } func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -&gt; JSQMessageData! { return messages[indexPath.item] } func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -&gt; JSQMessageBubbleImageDataSource! { let message = messages[indexPath.item] // 1 if message.senderId == senderId { // 2 return outgoingBubbleImageView } else { // 3 return incomingBubbleImageView } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int { return messages.count } func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -&gt; JSQMessageAvatarImageDataSource! { return nil } private func setupBubbles() { let factory = JSQMessagesBubbleImageFactory() outgoingBubbleImageView = factory?.outgoingMessagesBubbleImage( // UIColor.init(red:250/255, green: 69/255, blue: 85/255, alpha: 1)) with: UIColor.init(red:47/255, green: 53/255, blue: 144/255, alpha: 1)) incomingBubbleImageView = factory?.incomingMessagesBubbleImage( with: UIColor.jsq_messageBubbleLightGray()) } func addMessage(id: String, text: String) { let message = JSQMessage(senderId: id, displayName: "", text: text) messages.append(message!) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell{ let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell let message = messages[indexPath.item] if message.senderId == senderId { cell.textView!.textColor = UIColor.whiteColor() } else { cell.textView!.textColor = UIColor.blackColor() } return cell } func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) { let itemRef = messageRef.childByAutoId() // 1 let messageItem = [ // 2 "text": text, "senderId": senderId ] itemRef.setValue(String(messageItem)) // 3 // 4 JSQSystemSoundPlayer.jsq_playMessageSentSound() // 5 finishSendingMessage() isTyping = false } private func observeMessages() { // 1 let messagesQuery = messageRef.queryLimited(toLast: 25) // 2 messagesQuery.observe(.childAdded) { (snapshot: FIRDataSnapshot!) in // 3 let id = snapshot.value!["senderId"] as! String let text = snapshot.value!["text"] as! String // 4 self.addMessage(id: id, text: text) // 5 self.finishReceivingMessage() } } private func observeTyping() { let typingIndicatorRef = rootRef.child("typingIndicator") userIsTypingRef = typingIndicatorRef.child(senderId) userIsTypingRef.onDisconnectRemoveValue() // 1 usersTypingQuery = typingIndicatorRef.queryOrderedByValue().queryEqual(toValue: true) // 2 usersTypingQuery.observe(.value) { (data: FIRDataSnapshot!) in // 3 You're the only typing, don't show the indicator if data.childrenCount == 1 &amp;&amp; self.isTyping { return } // 4 Are there others typing? self.showTypingIndicator = data.childrenCount &gt; 0 self.scrollToBottom(animated: true) } } func textViewDidChange(textView: UITextView) { super.textViewDidChange(textView) // If the text is not empty, the user is typing isTyping = textView.text != "" } func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -&gt; AttributedString! { return AttributedString(string:"test") } } </code></pre>
0
3,009
@EnableJpaRepositories dependency
<p>I'm trying to connect my STS project with DB.</p> <p>But I can not import <code>@EnableJpaRepositories</code>.</p> <p>My code AccountRepository.java : </p> <pre><code>package com.myongjoon.spring; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @EnableJpaRepositories(basePackages="com.myongjoon.spring") public interface AccountRepository extends JpaRepository&lt;Account, Long&gt; { } </code></pre> <p>and pom.xml : </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &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/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.myongjoon&lt;/groupId&gt; &lt;artifactId&gt;spring&lt;/artifactId&gt; &lt;name&gt;spring&lt;/name&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0.0-BUILD-SNAPSHOT&lt;/version&gt; &lt;properties&gt; &lt;java-version&gt;1.6&lt;/java-version&gt; &lt;org.springframework-version&gt;3.2.6.RELEASE&lt;/org.springframework-version&gt; &lt;org.aspectj-version&gt;1.6.10&lt;/org.aspectj-version&gt; &lt;org.slf4j-version&gt;1.6.6&lt;/org.slf4j-version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;!-- Spring --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;${org.springframework-version}&lt;/version&gt; &lt;exclusions&gt; &lt;!-- Exclude Commons Logging in favor of SLF4j --&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-webmvc&lt;/artifactId&gt; &lt;version&gt;${org.springframework-version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- AspectJ --&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt; &lt;version&gt;${org.aspectj-version}&lt;/version&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;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;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;version&gt;${org.slf4j-version}&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.15&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;javax.mail&lt;/groupId&gt; &lt;artifactId&gt;mail&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;javax.jms&lt;/groupId&gt; &lt;artifactId&gt;jms&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;com.sun.jdmk&lt;/groupId&gt; &lt;artifactId&gt;jmxtools&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;com.sun.jmx&lt;/groupId&gt; &lt;artifactId&gt;jmxri&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- @Inject --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.inject&lt;/groupId&gt; &lt;artifactId&gt;javax.inject&lt;/artifactId&gt; &lt;version&gt;1&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Servlet --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- added dependency --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.persistence&lt;/groupId&gt; &lt;artifactId&gt;persistence-api&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;!-- java EE API --&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;/dependency&gt; &lt;!-- hiberate-validator --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt; &lt;version&gt;5.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- dao --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-dao&lt;/artifactId&gt; &lt;version&gt;2.0.3&lt;/version&gt; &lt;/dependency&gt; &lt;!-- jpa --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt; &lt;version&gt;1.2.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-commons-core&lt;/artifactId&gt; &lt;version&gt;1.4.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;!-- jpa --&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.38&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt; &lt;version&gt;1.0.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;!-- added dependency --&gt; &lt;!-- Test --&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.7&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-beans&lt;/artifactId&gt; &lt;version&gt;3.2.6.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt; &lt;version&gt;2.9&lt;/version&gt; &lt;configuration&gt; &lt;additionalProjectnatures&gt; &lt;projectnature&gt;org.springframework.ide.eclipse.core.springnature&lt;/projectnature&gt; &lt;/additionalProjectnatures&gt; &lt;additionalBuildcommands&gt; &lt;buildcommand&gt;org.springframework.ide.eclipse.core.springbuilder&lt;/buildcommand&gt; &lt;/additionalBuildcommands&gt; &lt;downloadSources&gt;true&lt;/downloadSources&gt; &lt;downloadJavadocs&gt;true&lt;/downloadJavadocs&gt; &lt;/configuration&gt; &lt;/plugin&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.5.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.6&lt;/source&gt; &lt;target&gt;1.6&lt;/target&gt; &lt;compilerArgument&gt;-Xlint:all&lt;/compilerArgument&gt; &lt;showWarnings&gt;true&lt;/showWarnings&gt; &lt;showDeprecation&gt;true&lt;/showDeprecation&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.2.1&lt;/version&gt; &lt;configuration&gt; &lt;mainClass&gt;org.test.int1.Main&lt;/mainClass&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I think I have dependency to EnableJpaRepositories spring-data-jaa </p> <p>but This code have red line</p> <pre><code>import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @EnableJpaRepositories(basePackages="com.myongjoon.spring") </code></pre> <p>I need other dependency?</p>
0
5,297
Binding between my usercontrol and ViewModel
<p>Can not do Binding</p> <p>Random (MyViewModel) -> VMTestValue (MyViewModel) -> TestUserControl (MainWindow)</p> <p>"MyViewModel" is ViewModel for "MainWindow"</p> <p>All project: <a href="http://rusfolder.com/32608140" rel="nofollow">http://rusfolder.com/32608140</a></p> <p>TestUserControl.xaml</p> <pre><code>&lt;UserControl x:Class="TestBinding.TestUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Background="Green" d:DesignHeight="300" d:DesignWidth="300"&gt; &lt;Grid&gt; &lt;TextBlock Background="Gray" Margin="50" FontSize="18" Text="{Binding TestValue}" /&gt; &lt;Rectangle Height="200" Width="{Binding TestValue}" Fill="#FFFF1717" /&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>TestUserControl.cs</p> <pre><code>... public TestUserControl() { InitializeComponent(); this.DataContext = this; } public static readonly DependencyProperty TestValueProperty = DependencyProperty.Register("TestValue", typeof(int), typeof(TestUserControl), new FrameworkPropertyMetadata((int)255) ); public int TestValue { set { SetValue(TestValueProperty, value); } get { return (int)GetValue(TestValueProperty); } } ... </code></pre> <p>MyViewModel.cs</p> <pre><code>using System; using System.Timers; using Microsoft.Practices.Prism.ViewModel; namespace TestBinding { class MyViewModel : NotificationObject { private int _VMTestValue; private Timer timer; private Random _random; public MyViewModel() { _random=new Random(); timer=new Timer(); timer.Interval = 500; timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Start(); } void timer_Elapsed(object sender, ElapsedEventArgs e) { VMTestValue = _random.Next(10, 300); } public int VMTestValue { set { _VMTestValue = value; this.RaisePropertyChanged(() =&gt; this.VMTestValue); } get { return _VMTestValue; } } } } </code></pre> <p>MainWindow.cs</p> <pre><code>... public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MyViewModel(); } } ... </code></pre> <p>MainWindow.xaml</p> <pre><code>... &lt;TestBinding1:TestUserControl TestValue="{Binding VMTestValue}" /&gt; &lt;TextBlock VerticalAlignment="Bottom" Background="Blue" FontSize="20" Text="{Binding VMTestValue}" /&gt; ... </code></pre> <p><strong>Why can not I go to the UserControl?</strong></p>
0
1,490
Correct YUV422 to RGB conversion
<p>I've been trying to tackle a YUV422 into a RGB conversion problem for about a week. I've visited many different websites and have gotten different formulas from each one. If anyone else has any suggestions I would be glad to hear about them. The formulas below give me an image with either and overall purple or a green hue in them. As of this moment I haven't been able to find a formula that allows me to get back a proper RGB image. I have include all my various chunks of code below.</p> <pre><code> //for(int i = 0; i &lt; 1280 * 720 * 3; i=i+3) //{ // /*m_RGB-&gt;imageData[i] = pData[i] + pData[i+2]*((1 - 0.299)/0.615); // m_RGB-&gt;imageData[i+1] = pData[i] - pData[i+1]*((0.114*(1-0.114))/(0.436*0.587)) - pData[i+2]*((0.299*(1 - 0.299))/(0.615*0.587)); // m_RGB-&gt;imageData[i+2] = pData[i] + pData[i+1]*((1 - 0.114)/0.436);*/ // m_RGB-&gt;imageData[i] = pData[i] + 1.403 * (pData[i+1] - 128); // m_RGB-&gt;imageData[i+1] = pData[i] + 0.344 * (pData[i+1] - 128) - 0.714 * (pData[i+2] - 128); // m_RGB-&gt;imageData[i+2] = pData[i] + 1.773 * (pData[i+2] - 128); //} for(int i = 0, j=0; i &lt; 1280 * 720 * 3; i+=6, j+=4) { /*m_RGB-&gt;imageData[i] = pData[j] + pData[j+3]*((1 - 0.299)/0.615); m_RGB-&gt;imageData[i+1] = pData[j] - pData[j+1]*((0.114*(1-0.114))/(0.436*0.587)) - pData[j+3]*((0.299*(1 - 0.299))/(0.615*0.587)); m_RGB-&gt;imageData[i+2] = pData[j] + pData[j+1]*((1 - 0.114)/0.436); m_RGB-&gt;imageData[i+3] = pData[j+2] + pData[j+3]*((1 - 0.299)/0.615); m_RGB-&gt;imageData[i+4] = pData[j+2] - pData[j+1]*((0.114*(1-0.114))/(0.436*0.587)) - pData[j+3]*((0.299*(1 - 0.299))/(0.615*0.587)); m_RGB-&gt;imageData[i+5] = pData[j+2] + pData[j+1]*((1 - 0.114)/0.436);*/ /*m_RGB-&gt;imageData[i] = pData[j] + 1.403 * (pData[j+3] - 128); m_RGB-&gt;imageData[i+1] = pData[j] + 0.344 * (pData[j+1] - 128) - 0.714 * (pData[j+3] - 128); m_RGB-&gt;imageData[i+2] = pData[j] + 1.773 * (pData[j+1] - 128); m_RGB-&gt;imageData[i+3] = pData[j+2] + 1.403 * (pData[j+3] - 128); m_RGB-&gt;imageData[i+4] = pData[j+2] + 0.344 * (pData[j+1] - 128) - 0.714 * (pData[j+3] - 128); m_RGB-&gt;imageData[i+5] = pData[j+2] + 1.773 * (pData[j+1] - 128);*/ BYTE Cr = pData[j+3] - 128; BYTE Cb = pData[j+1] - 128; /*m_RGB-&gt;imageData[i] = pData[j] + Cr + (Cr &gt;&gt; 2) + (Cr &gt;&gt; 3) + (Cr &gt;&gt; 5); m_RGB-&gt;imageData[i+1] = pData[j] - ((Cb &gt;&gt; 2) + (Cb &gt;&gt; 4) + (Cb &gt;&gt; 5)) - ((Cr &gt;&gt; 1) + (Cr &gt;&gt; 3) + (Cr &gt;&gt; 4) + (Cr &gt;&gt; 5)); m_RGB-&gt;imageData[i+2] = pData[j] + Cb + (Cb &gt;&gt; 1) + (Cb &gt;&gt; 2) + (Cb &gt;&gt; 6); m_RGB-&gt;imageData[i+3] = pData[j+2] + Cr + (Cr &gt;&gt; 2) + (Cr &gt;&gt; 3) + (Cr &gt;&gt; 5); m_RGB-&gt;imageData[i+4] = pData[j+2] - ((Cb &gt;&gt; 2) + (Cb &gt;&gt; 4) + (Cb &gt;&gt; 5)) - ((Cr &gt;&gt; 1) + (Cr &gt;&gt; 3) + (Cr &gt;&gt; 4) + (Cr &gt;&gt; 5)); m_RGB-&gt;imageData[i+5] = pData[j+2] + Cb + (Cb &gt;&gt; 1) + (Cb &gt;&gt; 2) + (Cb &gt;&gt; 6);*/ /*int R1 = clamp(1 * pData[j] + 0 * Cb + 1.4 * Cr, 0, 255), R2 = clamp(1 * pData[j+2] + 0 * Cb + 1.4 * Cr, 0, 255); int G1 = clamp(1 * pData[j] - 0.343 * Cb - 0.711 * Cr, 0, 255), G2 = clamp(1 * pData[j+2] - 0.343 * Cb - 0.711 * Cr, 0, 255); int B1 = clamp(1 * pData[j] + 1.765 * Cb + 0 * Cr, 0, 255), B2 = clamp(1 * pData[j+2] + 1.765 * Cb + 0 * Cr, 0, 255);*/ /*int R1 = clamp(pData[j] + 1.403 * (pData[j+3] - 128), 0, 255), R2 = clamp(pData[j+2] + 1.403 * (pData[j+3] - 128), 0, 255); int G1 = clamp(pData[j] + 0.344 * (pData[j+1] - 128) - 0.714 * (pData[j+3] - 128), 0, 255), G2 = clamp(pData[j+2] + 0.344 * (pData[j+1] - 128) - 0.714 * (pData[j+3] - 128), 0, 255); int B1 = clamp(pData[j] + 1.773 * (pData[j+1] - 128), 0, 255), B2 = clamp(pData[j+2] + 1.773 * (pData[j+1] - 128), 0, 255);*/ int R1 = clamp((298 * (pData[j] - 16) + 409 * (pData[j+3] - 128) + 128) &gt;&gt; 8, 0, 255), R2 = clamp((298 * (pData[j+2] - 16) + 409 * (pData[j+3] - 128) + 128) &gt;&gt; 8, 0, 255); int G1 = clamp((298 * (pData[j] - 16) - 100 * (pData[j+1] - 128) - 208 * (pData[j+3] - 128) + 128) &gt;&gt; 8, 0, 255), G2 = clamp((298 * (pData[j+2] - 16) - 100 * (pData[j+1] - 128) - 208 * (pData[j+3] - 128) + 128) &gt;&gt; 8, 0, 255); int B1 = clamp((298 * (pData[j] - 16) + 516 * (pData[j+1] - 128) + 128) &gt;&gt; 8, 0, 255), B2 = clamp((298 * (pData[j+2] - 16) + 516 * (pData[j+1] - 128) + 128) &gt;&gt; 8, 0, 255); //printf("R: %d, G: %d, B: %d, R': %d, G': %d, B': %d \n", R1, G1, B1, R2, G2, B2); m_RGB-&gt;imageData[i] = (char)R1; m_RGB-&gt;imageData[i+1] = (char)G1; m_RGB-&gt;imageData[i+2] = (char)B1; m_RGB-&gt;imageData[i+3] = (char)R2; m_RGB-&gt;imageData[i+4] = (char)G2; m_RGB-&gt;imageData[i+5] = (char)B2; /*m_RGB-&gt;imageData[i] = (char)(clamp(1.164 * (pData[j] - 16) + 1.793 * (Cr), 0, 255)); m_RGB-&gt;imageData[i+1] = (char)(clamp(1.164 * (pData[j] - 16) - 0.534 * (Cr) - 0.213 * (Cb), 0, 255)); m_RGB-&gt;imageData[i+2] = (char)(clamp(1.164 * (pData[j] - 16) + 2.115 * (Cb), 0, 255)); m_RGB-&gt;imageData[i+3] = (char)(clamp(1.164 * (pData[j+2] - 16) + 1.793 * (Cr), 0, 255)); m_RGB-&gt;imageData[i+4] = (char)(clamp(1.164 * (pData[j+2] - 16) - 0.534 * (Cr) - 0.213 * (Cb), 0, 255)); m_RGB-&gt;imageData[i+5] = (char)(clamp(1.164 * (pData[j+2] - 16) + 2.115 * (Cb), 0, 255));*/ } </code></pre> <p>Any help is greatly appreciated.</p>
0
3,119
Setting Up ActiveMQ
<p>I have followed a tutorial to install ActiveMQ <a href="http://servicebus.blogspot.com/2011/02/installing-apache-active-mq-on-ubuntu.html">http://servicebus.blogspot.com/2011/02/installing-apache-active-mq-on-ubuntu.html</a></p> <p>I dont quite understand this part of the tutorial</p> <pre><code>Now, you must create the data/jmx.password and data/jmx.access files </code></pre> <p>How should I work this out?</p> <p>I tried running the service by</p> <pre><code>sudo /etc/init.d/activemq start </code></pre> <p>and I get this response</p> <pre><code>INFO: Loading '/etc/default/activemq' INFO: Using java '/usr/bin/java' INFO: Starting - inspect logfiles specified in logging.properties and log4j.properties to get details INFO: changing to user 'activemq' to invoke java No directory, logging in with HOME=/ INFO: pidfile created : '/opt/activemq/data/activemq-iandjx-GA-MA785GMT-USB3.pid' (pid '6092') </code></pre> <p>but I'm still unable to connect to </p> <pre><code>http://localhost:8161 </code></pre> <p>Thanks in advance.</p> <p>I also tried <code>sudo apt-get install activemq</code> then</p> <pre><code>activemq </code></pre> <p>which gave me </p> <pre><code>INFO: Loading '/usr/share/activemq/activemq-options' INFO: Using java '/usr/lib/jvm/java-6-openjdk//bin/java' mkdir: missing operand Try `mkdir --help' for more information. /usr/bin/activemq: 399: /usr/bin/activemq: /usr/lib/jvm/java-6-openjdk//bin/java -Xms512M -Xmx512M -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Dactivemq.classpath="/var/lib/activemq/conf;" -Dactivemq.home="/usr/share/activemq" -Dactivemq.base="/var/lib/activemq/" -Dactivemq.conf="/var/lib/activemq/conf" -Dactivemq.data="/var/lib/activemq/data" -jar "/usr/share/activemq/bin/run.jar" : not found Tasks provided by the sysv init script: restart - stop running instance (if there is one), start new instance console - start broker in foreground, useful for debugging purposes status - check if activemq process is running setup - create the specified configuration file for this init script (see next usage section) Configuration of this script: The configuration of this script can be placed on /etc/default/activemq or /home/iandjx/.activemqrc. To use additional configurations for running multiple instances on the same operating system rename or symlink script to a name matching to activemq-instance-&lt;INSTANCENAME&gt;. This changes the configuration location to /etc/default/activemq-instance-&lt;INSTANCENAME&gt; and $HOME/.activemqrc-instance-&lt;INSTANCENAME&gt;. Configuration files in /etc have higher precedence. </code></pre>
0
1,069
how do i store the value of stars rating in mysql database
<p>Hi I have form that contains Ratings, Name, email, and comments. I am able to insert the user input data for name, email and comments. But don't know how to store the star ratings in database. Anyone please help me. thanks</p> <pre><code> &lt;?php if(isset($_POST['submit'])) { $name = $_POST['name']; $email = $_POST['email']; $comments = $_POST['comments']; $ratings = $_POST['ratings']; $link = mysqli_connect("localhost", "root", "", "imakr"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $res = mysqli_query($link, "insert into imakr.customer_review(name, email, comments, ratings) values('$name','$email','$comments', '$ratings')"); if($res) { echo "Your feedback is saved"; } else { echo " OOPs!! there is some error. Please check the fields"; } } ?&gt; &lt;form id="customer_review" name="cust_rev"action="" method="post" onsubmit="return validate()"&gt; &lt;table width="535" border="0"&gt; &lt;tr&gt; &lt;td&gt;Rate This Product: &lt;/td&gt; &lt;td&gt; &lt;span id="rateStatus"&gt;Rate Me...&lt;/span&gt; &lt;span id="ratingSaved"&gt;Rating Saved!&lt;/span&gt; &lt;div id="rateMe" title="Rate Me..."&gt; &lt;a onclick="rateIt(this)" id="_1" title="Poor" onmouseover="rating(this)" onmouseout="off(this)"&gt;&lt;span class="ratings"&gt;1&lt;/span&gt;&lt;/a&gt; &lt;a onclick="rateIt(this)" id="_2" title="Not Bad" onmouseover="rating(this)" onmouseout="off(this)"&gt;&lt;span class="ratings"&gt;2&lt;/span&gt;&lt;/a&gt; &lt;a onclick="rateIt(this)" id="_3" title="Pretty Good" onmouseover="rating(this)" onmouseout="off(this)"&gt;&lt;span class="ratings"&gt;3&lt;/span&gt;&lt;/a&gt; &lt;a onclick="rateIt(this)" id="_4" title="Excellent" onmouseover="rating(this)" onmouseout="off(this)"&gt;&lt;span class="ratings"&gt;4&lt;/span&gt;&lt;/a&gt; &lt;a onclick="rateIt(this)" id="_5" title="Marvellous" onmouseover="rating(this)" onmouseout="off(this)"&gt;&lt;span class="ratings"&gt;5&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="129"&gt;&lt;span class="titles"&gt;Name&lt;/span&gt;&lt;span class="star"&gt;*&lt;/span&gt;:&lt;/td&gt; &lt;td width="396"&gt;&lt;label for="name"&gt;&lt;/label&gt; &lt;input type="text" name="name" id="name" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="titles"&gt;Email&lt;/span&gt;&lt;span class="star"&gt;*&lt;/span&gt;:&lt;/td&gt; &lt;td&gt;&lt;label for="email"&gt;&lt;/label&gt; &lt;input type="text" name="email" id="email" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="61"&gt;Comments:&lt;/td&gt; &lt;td&gt;&lt;label for="comments"&gt;&lt;/label&gt; &lt;textarea name="comments" id="comments" cols="45" rows="5" onchange="maxlength('comments', 500)"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;input type="submit" name="submit" id="submit" value="Submit" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;/form&gt; </code></pre>
0
1,526
Display point style on legend in chart.js
<p><a href="https://jsfiddle.net/43Tesseracts/qmhhc089/" rel="nofollow noreferrer">https://jsfiddle.net/43Tesseracts/qmhhc089/</a></p> <p>For this chart's first dataset <code>XPData</code>, how do I set the legend style to use the point instead of the line?</p> <p>I'm hoping all I need to do is add: <code>showLines: false</code> according to the <a href="http://www.chartjs.org/docs/#line-chart-scatter-line-charts" rel="nofollow noreferrer">Scatter Line Chart docs</a>, but I can't figure out where to put this setting.</p> <p>Here is the data set (see fiddle):</p> <pre><code>var XPData = { label: 'XP Earned', //fill: false, //backgroundColor: "rgba(0,0,0,0)", //borderColor: "rgba(0,0,0,0)", pointBorderColor: "#444", pointBackgroundColor: "#444", data: [], showLines: false, }; </code></pre> <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>/*jshint esversion: 6 */ var ctx = document.getElementById("myChart"); class DataPoint { constructor(x, y) { this.x = x; this.y = y; } } var days = 85; var chillax = 72.5; // XP DATA SET var XPData = { label: 'XP Earned', //fill: false, //backgroundColor: "rgba(0,0,0,0)", //borderColor: "rgba(0,0,0,0)", pointBorderColor: "#444", pointBackgroundColor: "#444", data: [], showLines: false, options: { legend: { labels: { usePointStyle: true } } }, }; // XP Data generation var total = 0; for (var i = 0; i &lt; 35; i++) { total += 10 * Math.floor(Math.random() + 0.5); total += 5 * Math.floor(Math.random() + 0.5); total += 5 * Math.floor(Math.random() + 0.5); var p = new DataPoint(i + 1, total); XPData.data.push(p); } // XP Trend Data var XPTrendData = { label: 'XP Trend', fill: false, pointRadius: 0, lineTension: 0, borderDash: [5, 5], borderColor: "#ccc", backgroundColor: "rgba(0,0,0,0)", data: [], }; // XP Trend calculaion var total = 0; var days_so_far = XPData.data.length; total = XPData.data[days_so_far - 1].y; var average_per_day = total / days_so_far; var trend_total = total; for (i = days_so_far; i &lt; days; i++) { p = new DataPoint(i, trend_total); XPTrendData.data.push(p); trend_total += average_per_day; } // Chillax Line Data Set var ChillaxLineData = { label: 'Chillax Line', pointRadius: 0, backgroundColor: "rgba(0,0,0,0)", borderColor: "#337AB7", data: [], }; // Chill Line Generation for (i = 1; i &lt; days; i++) { p = new DataPoint(i, Math.floor(i * chillax * 10 / days)); ChillaxLineData.data.push(p); } var options = { scaleUse2Y: true, scales: { xAxes: [{ type: 'linear', position: 'bottom', ticks: { max: days, min: 0, stepSize: 5, }, scaleLabel: { display: true, labelString: 'Days of Class' }, }], yAxes: [{ id: "y-axis-XP", position: 'right', ticks: { max: 1000, min: 0, stepSize: 50, }, scaleLabel: { display: true, labelString: 'XP' }, gridLines: {}, }, { id: "y-axis-percent", position: 'left', ticks: { max: 100, min: 0, stepSize: 5, }, scaleLabel: { display: true, labelString: 'Percent' }, gridLines: { /*show: true, color: "rgba(255, 255, 255, 1)", lineWidth: 1, drawOnChartArea: true, drawTicks: true, zeroLineWidth: 1, zeroLineColor: "rgba(255,255,255,1)", */ }, } ], }, title: { text: 'A Map of Your Progress', display: true, }, legend: { position: 'top', }, }; var data = { datasets: [XPData, XPTrendData, ChillaxLineData, ] }; var myChart = new Chart(ctx, { type: 'line', data: data, options: options, });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.min.js"&gt;&lt;/script&gt; &lt;canvas id="myChart" width="400" height="250"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
0
1,994
Angular: Cannot Get /
<p>I am trying to open, build and run someone else's Angular 4 project but I am not able to view the project when I run it my way. I don't see what is going wrong or what I should do now. I already had everything in place to use NPM and NodeJS</p> <p>The steps I took were:</p> <ul> <li>Open up the project</li> <li>npm install</li> <li>ng serve</li> </ul> <p>The project compiles the right way. (I have an own Angular app and I know how this looks like) The console is showing: </p> <blockquote> <p>'** NG Live Development Server is listening on localhost:4200, open your browser on <a href="http://localhost:4200" rel="noreferrer">http://localhost:4200</a> **'.</p> </blockquote> <p>Then, when I opened up a web browser, I navigated to localhost:4200 and a web page with the following text were shown: </p> <blockquote> <p>'Cannot GET /'</p> </blockquote> <p>And on the console was the following text:</p> <blockquote> <p>'GET <a href="http://localhost:4200/" rel="noreferrer">http://localhost:4200/</a> 404 (Not Found)'</p> </blockquote> <p>The project should work fine but I am not able to navigate to a working URL on the web page. Routing is set-up another way as I am used to doing this. In app.module.ts the following is implemented:</p> <p>app.module.ts</p> <pre><code>const appRoutes: Routes = [ { path: '', redirectTo: 'tree', pathMatch: 'full' }, { path: 'admin', component: AdminPanelComponent, canActivate: [AuthGuard], children: [{path:'', component: PanelComponent},{path: 'add', component: AddTreeComponent}, {path:'manage-trees', component:ManageTreesComponent}, {path:'manage-users', component: ManageUsersComponent}, {path:'view-trees', component: ViewTreeComponent}]}, {path:'tree', component: TreeComponent}, {path:'error', component: ErrorComponent}, {path:'unauthorized', component: UnauthorizedComponent}, {path:'login', component: LoginComponent}, {path:'entire-tree', component: EntireTreeComponent}, { path: '**', component: PageNotFoundComponent }, ]; </code></pre> <p>Also opening up a web page like; localhost:4200/tree does not work. When I let angular stop serving the web page, the web page displays: "this site can't be reached'. So I think there is running something at localhost:4200... Also, another project of this person behaves the same way.</p> <p><a href="https://i.stack.imgur.com/PKZlU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PKZlU.png" alt="enter image description here"></a></p> <p>Does anybody know what is going on? </p> <p><strong>EDIT</strong></p> <p>app.module.ts</p> <pre><code>RouterModule.forRoot(appRoutes, { useHash: true }) </code></pre> <p>Package.json</p> <pre><code>{ "name": "xxx", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angular/http": "^4.0.0", "@angular/platform-browser": "^4.0.0", "@angular/platform-browser-dynamic": "^4.0.0", "@angular/router": "^4.0.0", "angular-oauth2-oidc": "^1.0.20", "angular-polyfills": "^1.0.1", "angular2-jwt": "^0.2.3", "angular2-spinner": "^1.0.10", "bootstrap": "^3.3.7", "core-js": "^2.4.1", "ngx-bootstrap": "^1.8.0", "rxjs": "^5.1.0", "zone.js": "^0.8.4" }, "devDependencies": { "@angular/cli": "1.2.4", "@angular/compiler-cli": "^4.0.0", "@angular/language-service": "^4.0.0", "@types/jasmine": "2.5.45", "@types/node": "~6.0.60", "codelyzer": "~3.0.1", "jasmine-core": "~2.6.2", "jasmine-spec-reporter": "~4.1.0", "karma": "~1.7.0", "karma-chrome-launcher": "~2.1.1", "karma-cli": "~1.0.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "karma-coverage-istanbul-reporter": "^1.2.1", "protractor": "~5.1.2", "ts-node": "~3.0.4", "tslint": "~5.3.2", "typescript": "~2.3.3" } } </code></pre> <p>I also see an icon next to the tab name with the label: "Error".</p> <p><strong>OBSERVATION:</strong></p> <p>New observation:</p> <p>After I ran <code>npm install -g angular-cli</code> I wasn't able to run <code>ng serve</code>. (You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli)</p> <p>Then I ran <code>npm install -g @angular/cli@latest</code> and I was able to use <code>ng serve</code> again. </p> <p><strong>OBSERVATION 2:</strong></p> <p>After building the app with: 'ng build ...' there is no index.html in the 'dist' folder... When I set the website online, there is just a folder structure instead of a nice website. I think that's because there is no index.html.</p>
0
1,811
Facebook Javascript SDK error "Object [object Object] has no method 'init`
<p>One of the first things that needs to be done in order to load the SDK for interacting with Facebook, is to run:</p> <p><code>FB.init(params)</code></p> <blockquote> <p>This method is used to initialize and setup the SDK. . . . . . All other SDK methods must be called after this one, because they won't exist until you do.</p> </blockquote> <p><a href="https://developers.facebook.com/docs/javascript/reference/FB.init/" rel="nofollow">Facebook JavaScript SDK: .init()</a></p> <p>I'm getting the error msg:</p> <p><code>Object [object Object] has no method "init"</code></p> <p>I'm not getting an error that <code>FB</code> is undefined, so I'm assuming that at least part of the <code>Facebook Javascript SDK</code> loaded.</p> <p>When the <code>SDK</code> loads, Facebook puts contents into a <code>&lt;div&gt;</code> element: <code>&lt;div id="fb-root"&gt;&lt;/div&gt;</code></p> <p>Just for the fun of it, I used <code>.innerHTML</code> to see if I could extract anything out of that <code>&lt;div&gt;</code>.</p> <pre><code>var fbRootContent = document.getElementById('fb-root').innerHTML; console.log("fbRoot Content: " + fbRootContent); </code></pre> <p>And it does show that something got injected into that <code>&lt;div&gt;</code>. So, . . . I'm assuming that at least some of the <code>Facebook Javascript SDK</code> loaded.</p> <p>One possible issue, is that I'm using Google Apps Script, and lots of content gets sanitized and stripped out before it is served. So it's a possibility that, even though some of the SDK is loading, some of it is getting stripped out by the sanitation process.</p> <p>I'm simply trying to determine if it's possible to load the <code>Facebook Javascript SDK</code> into Apps Script. I haven't had any luck so far. Here is the latest code I've used in the attempt to test whether the SDK can be loaded or not.</p> <pre><code>&lt;div id="fb-root"&gt;&lt;/div&gt; &lt;label id="lblToHid"&gt;Load Facebook Javascript SDK&lt;/label&gt; &lt;br&gt; &lt;br&gt; &lt;button id="btnTest"&gt;test&lt;/button&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://connect.facebook.net/en_US/all.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { $("#lblToHid").hide(); $("#btnTest").click(function(){ $("#lblToHid").show(); }); callFB(); fbAsyncInit(); }); function callFB(){ console.log("callFB ran: "); window.fbAsyncInit = function() { console.log("AsyncInit ran"); console.log("Here is the object FB: " + FB); var fbRootContent = document.getElementById('fb-root').innerHTML; console.log("fbRoot Content: " + fbRootContent); FB.init({ appId : 'myAppID Here', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); console.log("callFB done running: "); }; }; &lt;/script&gt; </code></pre> <p>Note that I am not loading the SDK asynchronously. I'm doing that on purpose to test if it will load or not. Note the line:</p> <pre><code>&lt;script src="https://connect.facebook.net/en_US/all.js"&gt;&lt;/script&gt; </code></pre> <p>Facebook suggests loading the SDK a different way. Why? Because it might slow down the initial load of your app.</p> <p>So, why am I getting the error: <code>Object [object Object] has no method "init"</code></p> <p>And is it possible to load the <code>Facebook Javascript SDK</code> into Google Apps Script?</p> <p>I'm using jQuery: <code>$(document).ready</code>, </p> <p><a href="http://learn.jquery.com/using-jquery-core/document-ready/" rel="nofollow">jQuery $(document).ready()</a></p> <p>so <code>FB.init</code> shouldn't be getting called until the <code>&lt;script&gt;</code> tag has loaded the Facebook SDK.</p>
0
1,411
Sorting in pyqt tablewidget
<p>How can I sort a coloumn in pyqt by the highest number? Currently I have <code>setSortingEnabled(True)</code> and that only sorts it by the most numbers (ex. 1,1,1,1,2,2,2,3,3) i want to do it by the highest number for example (ex. 58,25,15,10). Thanks!</p> <p>Data Update:</p> <pre><code>def setmydata(self): for n, key in enumerate(self.data): for m, item in enumerate(self.data[key]): newitem = QtGui.QTableWidgetItem(item) self.setItem(m, n, newitem) </code></pre> <p>Whole code:</p> <pre><code>import sys from PyQt4.QtGui import QTableWidget from PyQt4 import QtGui,QtCore,Qt import MySQLdb as mdb from functools import partial import time class Window(QtGui.QDialog): process_column_signal = QtCore.pyqtSignal() def __init__(self,parent=None): super(Window, self).__init__() self.layout = QtGui.QVBoxLayout(self) self.db = mdb.connect('serv','user','pass','db') self.model = self.db.cursor() self.initialData = self.get_data_status() self.table1 = MyTableStatus(self.initialData, 145, 4) callback = partial(self.process_column,self.table1) self.process_column_signal.connect(callback) self.layout.addWidget(self.table1) self.timer_status = QtCore.QTimer() self.timer_status.timeout.connect(self.updateAllViews) self.timer_status.timeout.connect(self.some_method) # check every half-second self.timer_status.start(1000*5) def some_method(self): self.process_column_signal.emit() def get_data_status(self): self.model.execute("""SELECT cpu_juliet,cpu,cpu_julietleft FROM status WHERE date = (SELECT MAX(date) FROM status)""") rows_status_cpu = self.model.fetchone() self.listb1 = ['%s' % rows_status_cpu[0],'%s' % rows_status_cpu[2],'%s' % rows_status_cpu[1],'%s' % rows_status_cpu[1]]#['%s %s' % self.rows_status] self.model.execute("""SELECT disk_queue_juliet FROM status WHERE date = (SELECT MAX(date) FROM status)""") rows_status_disk_queue = self.model.fetchone() self.lista1 = 'Juliet','Julietleft','Pong','Hulk' self.listc1 = ['%s' % rows_status_disk_queue,'%s' % rows_status_disk_queue,'%s' % rows_status_disk_queue,'%s' % rows_status_disk_queue ] if self.listb1[0] &gt;= '80' or self.listc1[0] &gt;= '9': server_status_Juliet = 'WARNING' else: server_status_Juliet = 'Normal' if self.listb1[1] &gt;= '80' or self.listc1[1] &gt;= '9': server_status_Julietleft = 'WARNING' else: server_status_Julietleft = 'Normal' if self.listb1[2] &gt;= '80' or self.listc1[2] &gt;= '9': server_status_Pong = 'WARNING' else: server_status_Pong = 'Normal' if self.listb1[3] &gt;= '80' or self.listc1[3] &gt;= '9': server_status_Hulk = 'WARNING' else: server_status_Hulk = 'Normal' self.listd1 = ['%s' % server_status_Juliet,'%s' % server_status_Julietleft,'%s' % server_status_Pong,'%s' % server_status_Hulk] # if server_status_Hulk == "WARNING": #or server_status_Pong == "WARNING" or server_status_Julietleft == "WARNING" or server_status_Juliet == "WARNING": # self.serverstatus.setStyleSheet("QTabWidget {color: red}") #status label conditions self.mystruct1 = {'A':self.lista1, 'B':self.listb1, 'C':self.listc1, 'D':self.listd1} return self.mystruct1 def updateAllViews(self): _ = self.get_data_status() self.updateTable() def updateTable(self): self.table1.updateFromDict(self.mystruct1) def process_column(table1, processCol=1): colCount = table1.table1.rowCount() for row in xrange(table1.table1.rowCount()): for col in xrange(4): try: item = table1.table1.item(row, 3) text = item.text() if (float(text) &gt;= 20.0 ): for col in xrange(colCount): print row item = table1.table1.item(row,col) item.setBackground(QtGui.QBrush(QtCore.Qt.yellow)) except: pass class MyTableStatus(QTableWidget): def __init__(self, thestruct, *args): QTableWidget.__init__(self, *args) self.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred) self.setHorizontalHeaderLabels(['Server', 'Avg. Disk Queue','CPU Load',"Status"]) self.setSortingEnabled(False) self.data = {} self.setmydata() def updateFromDict(self, aDict): self.data.clear() self.data.update(aDict) self.setmydata() def setmydata(self): for n, key in enumerate(self.data): for m, item in enumerate(self.data[key]): newitem = QtGui.QTableWidgetItem(item) self.setItem(m, n, newitem) def main(): app = QtGui.QApplication(sys.argv) app.setStyle(QtGui.QStyleFactory.create("plastique")) main_window = Window() main_window.repaint() main_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre>
0
2,592
VB.net Simple Multithreading
<p>I have a Private Sub Fill(), which im trying to call from button1, in the form of </p> <pre><code>Dim t1 As System.Threading.Thread = New System.Threading.Thread(AddressOf Me.Fill) t1.Start() </code></pre> <p>However, when I run the program nothing happens. I click the button numerous times and the function isnt being executed. What gives? The Fill function is basically a outputting bunch of html from IE into a textbox, running regex and outputting the results in a listbox.</p> <p>Can anyone help me get this working? I'd appreciate the help. <strong>EDIT:</strong> Below, is the Fill function that I am trying to get working. The function itself works, when i try it without multithreading. But not with it...</p> <pre><code>Private Sub Fill() Try For Each links In ListBox2.Items Dim blah As Boolean = False Do While blah = False Application.DoEvents() If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then blah = True WebBrowser1.Navigate(links) Application.DoEvents() Me.Refresh() 'OUTPUT THE REGEX IN RTB Try RichTextBox1.Text = WebBrowser1.Document.Body.OuterHtml RichTextBox1.Update() Application.DoEvents() Me.Refresh() 'INTRODUCE REGEX If CheckBox1.Checked = True Then Dim R As New Regex("&lt;/H3&gt;&amp;lt;.*gt;") For Each M As Match In R.Matches(RichTextBox1.Text) Dim email As String = M.Value.Substring(9).Split("&amp;;").GetValue(0).ToString ListBox1.Items.Add(email) Next End If Catch ex As Exception Label1.Text = "Error recieved. Program will not stop" Me.Refresh() End Try Application.DoEvents() Me.Refresh() End If Loop Next Catch ex As Exception End Try End Sub </code></pre>
0
1,159
How to make an asynchronous Dart call synchronous?
<p>I'm on the way to evaluate Dart for a German company by porting various Java programs to Dart and compare and analyze the results. In the browser Dart wins hands down. For server software performance seemed to be a serious isssue (see <a href="https://stackoverflow.com/questions/28026648/how-to-improve-dart-performance-of-data-conversion-to-from-binary">this question of me</a>) but that got mostly defused.</p> <p>Now I'm in the area of porting some "simple" command-line tools where I did not expect any serious problems at all but there is at least one. Some of the tools do make HTTP requests to collect some data and the stand-alone Dart virtual machine only supports them in an asynchronous fashion. Looking through all I could find it does not seem to be possible to use any asynchronous call in a mostly synchronous software.</p> <p>I understand that I could restructure the available synchronous software into an asynchronous one. But this would transform a well-designed piece of software into something less readable and more difficult to debug and maintain. For some software pieces this just does not make sense. My question: Is there an (overlooked by me) way to embed an asynchronous call into a synchronously called method?</p> <p>I imagine that it would not be to difficult to provide a system call, usable only from within the main thread, which just transfers the execution to the whole list of queued asynchronous function calls (without having to end the main thread first) and as soon as the last one got executed returns and continues the main thread.</p> <p>Something which might look like this:</p> <pre class="lang-dart prettyprint-override"><code>var synchFunction() { var result; asyncFunction().then(() { result = ...; }); resync(); // the system call to move to and wait out all async execution return result; } </code></pre> <p>Having such a method would simplify the lib APIs as well. Most "sync" calls could be removed because the re-synchronisation call would do the job. It seems to be such a logical idea that I still think it somehow exists and I have missed it. Or is there a serious reason why that would not work? <hr> After thinking about the received answer from <code>lm</code> (see below) for two days I still do not understand why the encapsulation of an asynchronous Dart call into a synchronous one should not be possible. It is done in the "normal" synchronous programing world all the time. Usually you can wait for a resynchronization by either getting a "Done" from the asynchronous routine or if something fails continue after a timeout.</p> <p>With that in mind my first proposal could be enhanced like that: </p> <pre class="lang-dart prettyprint-override"><code>var synchFunction() { var result; asyncFunction() .then(() { result = ...; }) .whenComplete(() { continueResync() }); // the "Done" message resync(timeout); // waiting with a timeout as maximum limit // Either we arrive here with the [result] filled in or a with a [TimeoutException]. return result; } </code></pre> <p>The <code>resync()</code> does the same that would normally happen after ending the <code>main</code> method of an isolate, it starts executing the queued asynchronous functions (or waits for events to make them executable). As soon as it encounters a <code>continueResync()</code> call a flag is set which stops this asynchronous execution and <code>resync()</code> returns to the main thread. If no <code>continueResync()</code> call is encountered during the given <code>timeout</code> period it too aborts the asynchronous execution and leaves <code>resync()</code> with a <code>TimeoutException</code>.</p> <p>For some groups of software which benefit from straight synchronous programing (not the client software and not the server software) such a feature would solve lots of problems for the programer who has to deal with asynchrounous-only libraries.</p> <p>I believe that I have also found a solution for the main argument in <code>lm</code>'s argumentation below. Therefore my question still stands with respect to this "enhanced" solution which I proposed: <strong>Is there anything which really makes it impossible to implement that in Dart?</strong></p>
0
1,058
path fill color in d3
<p>Good day,</p> <p>Coder, I am new to d3 and json. i want to create a simple map projection that will identify the population of each country that was saved in csv file. </p> <p>I already created the map projection and now i am stock for almost a week on how to fill the country based on the population on my csv file..</p> <p>In that code below it can identified the highest or lowest population of the world by using the circle, but i dont like to use circle simply because it can overlap each other, all i want is to fill the country either green,blue or red red being the highest and green being the lowest. </p> <p>here is my sample csv file</p> <p>country, population,lat, lon PHILIPPINES,10, 13, 122 CANADA, 2000, 60, -95 JAPAN, 500, 36, 138 AFGHANISTAN, 200, 33, 65 CHINA, 2000, 35, 105</p> <p>here is my code</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;meta charset="utf-8"&gt; &lt;style&gt; path { fill: silver; } div.tooltip { position: absolute; text-align: center; width: 140px; height: 45px; padding: 2px; font: 12px sans-serif; background: lightsteelblue; border: 0px; border-radius: 8px; pointer-events: none; z-index:50; } .overlay { fill: none; pointer-events: all; } .state { fill: #aaa; } .county-border, .state-border { fill: none; stroke: #fff; stroke-linejoin: round; stroke-linecap: round; } .frame { stroke: #333; fill: none; pointer-events: all; } .feature { stroke: #ccc; } &lt;/style&gt; &lt;body&gt; &lt;!--&lt;script src="http://d3js.org/d3.v3.min.js"&gt;&lt;/script&gt; &lt;script src="http://d3js.org/topojson.v1.min.js"&gt;&lt;/script&gt;--&gt; &lt;script src="Script/d3.v3.min.js"&gt;&lt;/script&gt; &lt;script src="Script/topojson/topojson.js"&gt;&lt;/script&gt; &lt;script src="Script/queue-master/queue.min.js"&gt;&lt;/script&gt; &lt;script&gt; // &lt;script src="http://d3js.org/d3.v2.js"&gt;&lt;/script&gt; &lt;div id="d"&gt;&lt;/div&gt; &lt;script&gt; var MalwareCountry = [ // "Australia", "Algeria", //"Brunei", "Cameroon", "Canada", "Cyprus", "Philippines", "Manila", // "United States of America", "Washington D.C", //"Mexico", "Mexico", //"New Zealand", //"Hong Kong", //"India", //"Indonesia", "China","Beijng", "Japan", "Tokyo", "Afghanistan" //"Singapore", //"South Korea", //"Taiwan", //"Thailand", //"Vietnam", //"Austria", //"Belgium", //"France", //"Germany", //"Iran", //"Ireland", //"Israel", //"Italy", //"Luxembourg", //"Netherlands", //"Russia", //"Saudi Arabia", //"Spain", //"Switzerland", //"Turkey", //"United Arab Emirates", //"United Kingdom", //"Albania", //"Bosnia and Herzegowina", //"Crotia", //"Czech Republic", //"Hungary", //"Denmark", //"Finland", //"Iceland", //"Macedonia", //"Montenegro", //"Norway", //"Poland", //"Romania", //"Serbia", //"Slovenia", //"Slovakia", //"Sweden", //"Bulgaria", //"Malaysia", "Mozambique" ]; var div = d3.select("div") .append("div") .attr("class", "tooltip") .style("opacity", .1); var coldomain = [50, 150, 350, 750, 1500] var extcoldomain = [10, 50, 150, 350, 750, 1500] var legendary_labels = ["&lt; 50", "50+", "150+", "350+", "750+", "&gt; 1500"] var color = d3.scale.threshold() // .domain(coldomain) //.range(["#adfcad", "#ffcb40", "#ffba00", "#ff7d73", "#ff4e40", "#ff1300"]); var color = d3.scale.category20b() function getColorForCountry(name){ if (MalwareCountry.indexOf(name) &lt; 0) { return "#FFFFFF"; //return "#bbb"; }else { return color(); } } var margin = { top: 0, right: 0, bottom: 0, left: 0 }, width = 960 - margin.left - margin.right, height = 480 - margin.top - margin.bottom; var projection = d3.geo.equirectangular() .center([0, 5]) .scale(150) .translate([width / 2, height / 2]) .rotate([0, 0]) .precision(.9); var path = d3.geo.path() .projection(projection); var zoom = d3.behavior.zoom() .translate(projection.translate()) .scale(projection.scale()) .scaleExtent([height, 10 * height]) .on("zoom", move); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .call(zoom); var feature = svg.append("g") .selectAll(".feature"); svg.append("rect") .attr("class", "frame") .attr("width", width) .attr("height", height); d3.json("Script/topojson/examples/worldmap-100.json", function(data) { feature = feature .data(data.features) .enter().append("path") .attr("class", "feature") .attr("d", path) .style("fill", function (d) { return getColorForCountry(d.properties.name) }); }); var g = svg.append("g"); d3.csv("data/s.csv", function (error, data) { var circle = g.selectAll("circle") .data(feature) .enter() .append("circle") .attr("cx", function (d) { return projection([d.lon, d.lat])[0]; }) .attr("cy", function (d) { return projection([d.lon, d.lat])[1]; }) .attr("r", function (d) { return Math.sqrt(d.population) / 2 }) .style("fill", function (d) { if (d.population &gt;= 500 &amp;&amp; d.population &lt;= 800) { return "blue" } else if (d.population &gt;= 800) { return "red" } else { return "green" } }) }) function move() { projection.translate(d3.event.translate).scale(d3.event.scale); feature.attr("d", path); } var legend = svg.selectAll("g.legend") .data(extcoldomain) .enter().append("g") .attr("class", "legend"); var ls_w = 20, ls_h = 20; legend.append("rect") .attr("x", 20) .attr("y", function (d, i) { return height - (i * ls_h) - 2 * ls_h; }) .attr("width", ls_w) .attr("height", ls_h) .style("fill", function (d, i) { return color(d); }) .style("opacity", 0.8); legend.append("text") .attr("x", 50) .attr("y", function (d, i) { return height - (i * ls_h) - ls_h - 4; }) .text(function (d, i) { return legendary_labels[i]; }); &lt;/script&gt; </code></pre> <p>is there any trick that can help me regarding this problem. </p> <p>thanks</p>
0
2,892
“the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded” from superagent in Android React Native
<p>I'm using <code>superagent</code> to upload files from my React Native app. It works perfectly fine on iOS, but on Android it gives this error:</p> <blockquote> <p>Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.</p> </blockquote> <p>I've created a minimal example here <a href="https://snack.expo.io/@twohill/upload-example" rel="nofollow noreferrer">https://snack.expo.io/@twohill/upload-example</a> and copied the code below in case the snack goes away:</p> <pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react'; import { Text, View, StyleSheet, TouchableOpacity } from 'react-native'; import Constants from 'expo-constants'; import * as DocumentPicker from 'expo-document-picker'; import superagent from 'superagent'; import AssetExample from './components/AssetExample'; import { Card } from 'react-native-paper'; const upload = (file, setMessage) =&gt; { const { name } = file; superagent.post('https://example.org/uploads') // &lt;-- change this URL to your server that accepts uploads and is CORS enabled .set('Authorization', 'BEARER xxxyyy') // &lt;-- JWT token here .attach('uri', file, name) .then( result =&gt; setMessage(JSON.stringify({result})), error =&gt; setMessage(JSON.stringify({error})) ); }; const pickDocuments = async (setMessage) =&gt; { const file = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true }); if (file.type === "success") { upload(file, setMessage); } } export default class App extends Component { state = { message: null, } render() { const { message } = this.state; return ( &lt;View style={styles.container}&gt; &lt;TouchableOpacity onPress={() =&gt; pickDocuments(message =&gt; this.setState({message}))}&gt; &lt;Text style={styles.paragraph}&gt; Tap to upload a file &lt;/Text&gt; &lt;Card&gt; &lt;AssetExample /&gt; &lt;/Card&gt; &lt;Card&gt;&lt;Text&gt;{message}&lt;/Text&gt;&lt;/Card&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, }, paragraph: { margin: 24, fontSize: 18, fontWeight: 'bold', textAlign: 'center', }, }); </code></pre> <p>If I console.log the error it gives the following:</p> <pre class="lang-none prettyprint-override"><code>Request has been terminated Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc. * http://192.168.1.3:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&amp;dev=true&amp;minify=false&amp;hot=false:282311:24 in crossDomainError - node_modules\@sentry\utils\dist\instrument.js:224:24 in &lt;anonymous&gt; - node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent - node_modules\react-native\Libraries\Network\XMLHttpRequest.js:566:23 in setReadyState - node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse - node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0 - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0 * [native code]:null in callFunctionReturnFlushedQueue </code></pre> <p>As far as I can tell, on Android the app never tries an upload. My server runs <code>express</code> and has the <code>cors</code> middleware enabled with the default configuration</p> <pre><code>{ "origin": "*", "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", "preflightContinue": false, "optionsSuccessStatus": 204 } </code></pre> <p>Any ideas what to do here? I get the feeling that the Android is baulking at the "*" origin, but have no idea what to put in place for a mobile app.</p> <p>Or am I barking up the wrong tree completely?</p>
0
1,587
Nice inset border in CSS3
<p>I'm really loving this border style I've seen around on the tubes lately:</p> <p><img src="https://i.stack.imgur.com/Fl8af.png" alt="enter image description here"></p> <p>It'll probably look better if you just view it on the site: <a href="http://markdotto.com/bootstrap/" rel="nofollow noreferrer">http://markdotto.com/bootstrap/</a></p> <p>I'm particularly interested in how they're creating this effect, it seems that the bottom border is highlighted while the top is darkened. I know how I'd do this in Photoshop, but how are they doing it in CSS? </p> <pre><code>code, pre { background-color: rgba(0, 0, 0, 0); background-repeat: repeat-x; background-image: -khtml-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.15)), to(rgba(0, 0, 0, 0))); /* Konqueror */ background-image: -moz-linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0)); /* FF 3.6+ */ background-image: -ms-linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0)); /* IE10 */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0.15)), color-stop(100%, rgba(0, 0, 0, 0))); /* Safari 4+, Chrome 2+ */ background-image: -webkit-linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0)); /* Safari 5.1+, Chrome 10+ */ background-image: -o-linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0)); /* Opera 11.10 */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='rgba(0, 0, 0, 0.15)', endColorstr='rgba(0, 0, 0, 0)', GradientType=0); /* IE6 &amp; IE7 */ -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='rgba(0, 0, 0, 0.15)', endColorstr='rgba(0, 0, 0, 0)', GradientType=0)"; /* IE8+ */ background-image: linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0)); /* the standard */ background-color: rgba(0, 0, 0, 0.3); font-family: "Monaco", Courier New, monospace; font-size: 12px; font-weight: normal; line-height: 20px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25); -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.25), 0 1px 0 rgba(255, 255, 255, 0.25); -moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.25), 0 1px 0 rgba(255, 255, 255, 0.25); box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.25), 0 1px 0 rgba(255, 255, 255, 0.25); } code { padding: 3px 6px; -moz-border-radius: 3px; border-radius: 3px; } pre { margin: 20px 0; padding: 20px; color: #fff; -moz-border-radius: 6px; border-radius: 6px; white-space: pre-wrap; } </code></pre> <p>I'm not interested so much in the background as the border. You'll have to visit the site to truly appreciate it. </p>
0
1,050
Android Set Text of TextView in Fragment that is in FragmentPagerAdapter
<p>This one is driving me nuts. Basically, I want to create a <code>ViewPager</code> and add a few <code>Fragment</code>s to it. Then, all I want to do, it set a value in one of the <code>Fragment</code>'s <code>TextView</code>s. I can add the <code>Fragment</code>s fine, and they attach, but when I go to <code>findViewById()</code> for one of the <code>TextView</code>s in the first <code>Fragment</code> it throws a <code>NullPointerException</code>. I, for the life of me, can't figure out why.</p> <p>Here's my code so far, let me know if more is needed please.</p> <pre><code>public class SheetActivity extends FragmentActivity { // ///////////////////////////////////////////////////////////////////////// // Variable Declaration // ///////////////////////////////////////////////////////////////////////// private ViewPager viewPager; private PagerTitleStrip titleStrip; private String type; private FragmentPagerAdapter fragmentPager; //UPDATE @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sheet); viewPager = (ViewPager) findViewById(R.id.viewPager); titleStrip = (PagerTitleStrip) findViewById(R.id.viewPagerTitleStrip); // Determine which type of sheet to create Intent intent = getIntent(); this.type = intent.getStringExtra("type"); FragmentManager manager = getSupportFragmentManager(); switch (type) { case "1": viewPager.setAdapter(new InstallAdapter(manager)); break; case "2": viewPager.setAdapter(new InstallAdapter(manager)); break; } fragmentPager = (FragmentPagerAdapter) viewPager.getAdapter(); //UPDATE } @Override public void onResume() { super.onResume(); fragmentPager.getItem(0).setText("something"); //UPDATE } class MyAdapter extends FragmentPagerAdapter { private final String[] TITLES = { "Title1", "Title2" }; private final int PAGE_COUNT = TITLES.length; private ArrayList&lt;Fragment&gt; FRAGMENTS = null; public MyAdapter(FragmentManager fm) { super(fm); FRAGMENTS = new ArrayList&lt;Fragment&gt;(); FRAGMENTS.add(new FragmentA()); FRAGMENTS.add(new FragmentB()); } @Override public Fragment getItem(int pos) { return FRAGMENTS.get(pos); } @Override public int getCount() { return PAGE_COUNT; } @Override public CharSequence getPageTitle(int pos) { return TITLES[pos]; } } } </code></pre> <p>All of <code>Fragment</code>s I created only have the <code>onCreateView()</code> method overridden so I can display the proper XML layout. Other than that they are 'stock'. Why can't I interact with elements in any of the <code>Fragment</code>s?</p> <p><strong>UPDATE:</strong></p> <p>So do something like this?</p> <pre><code>public class FragmentA extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) { return inflater.inflate(R.layout.fragment_a, container, false); } public void setText(String text) { TextView t = (TextView) getView().findViewById(R.id.someTextView); //UPDATE t.setText(text); } } </code></pre> <p><strong>XML LAYOUT FOR FRAGMENT A</strong></p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/someTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="22sp" /&gt; &lt;/LinearLayout&gt; </code></pre>
0
1,677
Ant JUnit ClassNotFoundException
<p>I realize there are a lot of similar questions as <a href="https://stackoverflow.com/questions/10658636/new-to-ant-classnotfoundexception-with-junit">this one</a>, however after reading over most of them I seem to be having the same problem, but for different reasons.</p> <p>I'm running a <code>&lt;junit&gt;</code> task inside my Ant build and am getting a <code>ClassNotFoundException</code>. In most of the similarly-related questions (such as the one above), this turned out to be various degrees of the author simply not configuring the JUnit classpath correctly. Although it may very well be the same for me, none of the suggestions to any of these other questions have worked for me.</p> <p>My project directory structure:</p> <pre><code>MyProject/ src/main/java/ FakeObject.java ...the rest of my Java main source src/test/java FakeObjectUnitTest.java ...the rest of my Java test source bin/main FakeObject.class ...the rest of main Java binaries bin/test FakeObjectUnitTest.class ...the rest of main Java binaries lib/main ...my main dependencies lib/test junit-4.10.jar hamcrest-1.1.jar ...the rest of my test dependencies gen/reports ...where JUnit should be placing all test reports build/ build.xml build.properties </code></pre> <p>In <code>src/test/java/FakeObjectUnitTest.java</code>:</p> <pre><code>// Package and imports omitted public class FakeObjectUnitTest { @Test public void doSomething() { int x = 5; Assert.assertEquals(x, 5); } } </code></pre> <p>My <code>build.xml</code>:</p> <pre><code>&lt;project name="" basedir=".."&gt; &lt;!-- Main classpath. --&gt; &lt;path id="main.class.path"&gt; &lt;fileset dir="bin/main"/&gt; &lt;/path&gt; &lt;!-- Test classpath. --&gt; &lt;path id="test.class.path"&gt; &lt;fileset dir="bin/test"/&gt; &lt;/path&gt; &lt;!-- JUnit classpath. --&gt; &lt;path id="junit.class.path"&gt; &lt;fileset dir="lib/main" includes="*.jar"/&gt; &lt;fileset dir="lib/test" includes="*.jar"/&gt; &lt;path refid="main.class.path"/&gt; &lt;path refid="test.class.path"/&gt; &lt;/path&gt; &lt;!-- All previous targets omitted for brevity (such as for compiling, etc.), but I assure you all that they work and compile FakeObject.java/FakeObjectUnitTest.java into FakeObject.class/FakeObjectUnitTest.class respectively, and place them in the correct bin directories. --&gt; &lt;target name="run-junit" depends="compile"&gt; &lt;property name="junit.path" refid="junit.class.path"/&gt; &lt;echo message="JUnit ClassPath is: ${junit.path}"/&gt; &lt;junit printsummary="yes" haltonerror="yes" haltonfailure="yes"&gt; &lt;classpath refid="junit.class.path"/&gt; &lt;formatter type="xml"/&gt; &lt;batchtest todir="gen/reports"&gt; &lt;fileset dir="src/test/java"&gt; &lt;include name="**/*UnitTest*.java"/&gt; &lt;/fileset&gt; &lt;/batchtest&gt; &lt;/junit&gt; &lt;/target&gt; &lt;/project&gt; </code></pre> <p>When I run this target from the command-line:</p> <pre><code>run-junit: [echo] Conducting unit tests with JUnit. [echo] JUnit ClassPath is: /&lt;path-to-my-project&gt;/MyProject/lib/test/hamcrest-1.1.jar:/&lt;path-to-my-project&gt;/MyProject/lib/test/junit-4.10.jar:/&lt;path-to-my-project&gt;/MyProject/bin/main/com/myproject/client/FakeObject.class:/&lt;path-to-my-project&gt;/MyProject/bin/test/com/myproject/client/FakeObjectUnitTest.class [junit] Running com.myproject.client.FakeObjectUnitTest [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0 sec </code></pre> <p>I do this to <em>prove</em> that it sees <code>FakeObjectUnitTest.class</code> on the JUnit classpath. However, it fails with an error. When I go into the XML TEST report for this test, I see the following:</p> <pre><code>&lt;error message="com.myproject.client.FakeObjectUnitTest" type="java.lang.ClassNotFoundException"&gt;java.lang.ClassNotFoundException: com.myproject.client.FakeObjectUnitTest at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) &lt;/error&gt; </code></pre> <p>When I run Ant in verbose mode (<code>-v</code>) the only <em>hint</em> I see are a bunch of warnings along the lines of:</p> <blockquote> <p>Ignoring Exception java.util.zip.ZipException: error in opening zip file reading resource x</p> </blockquote> <p>...where <code>x</code> is the name of a class file.</p> <p>I found <a href="https://stackoverflow.com/questions/6015092/zipexception-when-running-junit-tests">this</a> question on SO, and the problem turned out to be that the author had added class files to the classpath, not JARs (which makes JUnit unhappy). So I tried removing <code>main.class.path</code> and <code>test.class.path</code> from <code>junit.class/path</code> and then I get an exception that none of the class files can be found.</p> <p>Any ideas or thoughts as to what is going on? Thanks in advance, and sorry for the <code>-v</code> question here, but I figured the more details, the better.</p>
0
2,237
The Google Play services resources were not found - Push Notifications
<p>I'm following the Google Tutorial to install <strong>Push Notification</strong> on Android. I'm using <strong>Google Play Services Module</strong> because the Google Cloud Messaging was recently <em>deprecated</em>.</p> <p>Tutorial : <a href="http://developer.android.com/google/gcm/client.html" rel="nofollow noreferrer">Google Cloud Messaging - Google Play Services</a></p> <p>But when I launch the app I have this errors :</p> <pre><code>11-06 13:37:30.119 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.119 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.119 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1816 (common_google_play_services_install_title) in Lcom/google/android/gms/R$string; 11-06 13:37:30.119 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1812 (common_google_play_services_enable_title) in Lcom/google/android/gms/R$string; 11-06 13:37:30.119 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1826 (common_google_play_services_update_title) in Lcom/google/android/gms/R$string; 11-06 13:37:30.119 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1823 (common_google_play_services_unsupported_title) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1820 (common_google_play_services_network_error_title) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1818 (common_google_play_services_invalid_account_title) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1813 (common_google_play_services_install_button) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1810 (common_google_play_services_enable_button) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1824 (common_google_play_services_update_button) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1815 (common_google_play_services_install_text_tablet) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1814 (common_google_play_services_install_text_phone) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1811 (common_google_play_services_enable_text) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1825 (common_google_play_services_update_text) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1822 (common_google_play_services_unsupported_text) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1819 (common_google_play_services_network_error_text) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1817 (common_google_play_services_invalid_account_text) in Lcom/google/android/gms/R$string; 11-06 13:37:30.129 20097-20097/com.thedjnivek.android.emarchespublics W/dalvikvm﹕ VFY: unable to resolve static field 1821 (common_google_play_services_unknown_issue) in Lcom/google/android/gms/R$string; 11-06 13:37:30.139 20097-20097/com.thedjnivek.android.emarchespublics E/GooglePlayServicesUtil﹕ The Google Play services resources were not found. Check your project configuration to ensure that the resources are included. 11-06 13:37:30.220 20097-20097/com.thedjnivek.android.emarchespublics E/GooglePlayServicesUtil﹕ The Google Play services resources were not found. Check your project configuration to ensure that the resources are included. </code></pre> <p>You can see here my <strong>source code</strong></p> <pre><code>//basic import ... import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; public class AppMainTabActivity extends FragmentActivity { public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; /** * Substitute you own sender ID here. This is the project number you got * from the API Console, as described in "Getting Started." */ String SENDER_ID = "7984****78"; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; TextView mDisplay; GoogleCloudMessaging gcm; AtomicInteger msgId = new AtomicInteger(); SharedPreferences prefs; Context context; String regid; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); // Check device for Play Services APK. If check succeeds, proceed with // GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); if (regid.isEmpty()) { registerInBackground(); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } // You need to do the Play Services APK check here too. @Override protected void onResume() { super.onResume(); checkPlayServices(); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } /** * Gets the current registration ID for application on GCM service. * &lt;p&gt; * If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing * registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGCMPreferences(Context context) { // This sample app persists the registration ID in shared preferences, but // how you store the regID in your app is up to you. return getSharedPreferences(AppMainTabActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } /** * Registers the application with GCM servers asynchronously. * &lt;p&gt; * Stores the registration ID and app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask() { @Override protected Object doInBackground(Object[] objects) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, // so it can use GCM/HTTP or CCS to send messages to your app. // The request to your server should be authenticated if your app // is using accounts. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device // will send upstream messages to a server that echo back the // message using the 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(Object o) { mDisplay.append(o + "\n"); Logger.logit("onPostExecute","o"); } }.execute(null, null, null); } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP * or CCS to send messages to your app. Not needed for this demo since the * device sends upstream messages to a server that echoes back the message * using the 'from' address in the message. */ private void sendRegistrationIdToBackend() { // Your implementation here. PushNotification.register(OpenUDID.value(this), regid, new AsyncHRHandler(this, true) { @Override public void onSuccess(String s) { super.onSuccess(s); } }); } /** * Stores the registration ID and app versionCode in the application's * {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } } </code></pre> <p>However <strong>Google Play Service</strong> has been <em>added</em>.</p> <p><img src="https://i.stack.imgur.com/Mhtrh.png" alt="Project Tree thedjnivek"></p> <p>On my <strong>module settings</strong></p> <p><img src="https://i.stack.imgur.com/Tlh87.png" alt="Module settings thedjnivek"></p> <p><strong>AndroidManifest.xml</strong></p> <p> </p> <pre><code>&lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/&gt; &lt;uses-permission android:name="android.permission.INTERNET"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&gt; &lt;uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt; &lt;uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt; &lt;!-- For notification push --&gt; &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt; &lt;permission android:name="com.thedjnivek.android.emarchespublics.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt; &lt;uses-permission android:name="com.thedjnivek.android.emarchespublics.permission.C2D_MESSAGE" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"&gt; &lt;receiver android:name=".GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" &gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;category android:name="com.thedjnivek.android.emarchespublics" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;service android:name=".GcmIntentService" /&gt; &lt;activity android:name=".fragmentmodule.AppMainTabActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustResize|stateVisible"&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:name=".activity.PDFActivity" android:label="activity_pdf"/&gt; &lt;meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIza**************mGE4Mq88"/&gt; &lt;/application&gt; </code></pre> <p></p> <p><strong>build.gradle</strong></p> <pre><code>buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.6.+' } } apply plugin: 'android' dependencies { compile fileTree(dir: 'libs', include: '*.jar') compile: "com.google.android.gms:play-services:3.+" } android { compileSdkVersion 17 buildToolsVersion "17.0.0" defaultConfig { minSdkVersion 8 targetSdkVersion 16 } } </code></pre> <p>I don't know where the problem is. Someone can't help me ? Thanks a lot !</p>
0
6,862
Filtering database rows with spring-data-jpa and spring-mvc
<p>I have a spring-mvc project that is using spring-data-jpa for data access. I have a domain object called <code>Travel</code> which I want to allow the end-user to apply a number of filters to it.</p> <p>For that, I've implemented the following controller:</p> <pre><code>@Autowired private TravelRepository travelRep; @RequestMapping("/search") public ModelAndView search( @RequestParam(required= false, defaultValue="") String lastName, Pageable pageable) { ModelAndView mav = new ModelAndView("travels/list"); Page&lt;Travel&gt; travels = travelRep.findByLastNameLike("%"+lastName+"%", pageable); PageWrapper&lt;Travel&gt; page = new PageWrapper&lt;Travel&gt;(travels, "/search"); mav.addObject("page", page); mav.addObject("lastName", lastName); return mav; } </code></pre> <p>This works fine: The user has a form with a <code>lastName</code> input box which can be used to filter the Travels. </p> <p>Beyond lastName, my <code>Travel</code> domain object has a lot more attributes by which I'd like to filter. I think that if these attributes were all strings then I could add them as <code>@RequestParam</code>s and add a spring-data-jpa method to query by these. For instance I'd add a method <code>findByLastNameLikeAndFirstNameLikeAndShipNameLike</code>.</p> <p>However, I don't know how should I do it when I need to filter for foreign keys. So my <code>Travel</code> has a <code>period</code> attribute that is a foreign key to the <code>Period</code> domain object, which I need to have it as a dropdown for the user to select the <code>Period</code>. </p> <p>What I want to do is when the period is null I want to retrieve all travels filtered by the lastName and when the period is not null I want to retrieve all travels for this period filtered by the lastName. </p> <p>I know that this can be done if I implement two methods in my repository and use an <code>if</code> to my controller:</p> <pre><code>public ModelAndView search( @RequestParam(required= false, defaultValue="") String lastName, @RequestParam(required= false, defaultValue=null) Period period, Pageable pageable) { ModelAndView mav = new ModelAndView("travels/list"); Page travels = null; if(period==null) { travels = travelRep.findByLastNameLike("%"+lastName+"%", pageable); } else { travels = travelRep.findByPeriodAndLastNameLike(period,"%"+lastName+"%", pageable); } mav.addObject("page", page); mav.addObject("period", period); mav.addObject("lastName", lastName); return mav; } </code></pre> <p>Is there a way to do this <em>without</em> using the <code>if</code> ? My Travel has not only the period but also other attributes that need to be filtered using dropdowns !! As you can understand, the complexity would be exponentially increased when I need to use more dropdowns because all the combinations'd need to be considered :(</p> <p><b>Update 03/12/13</b>: Continuing from M. Deinum's excelent answer, and after actually implementing it, I'd like to provide some comments for completeness of the question/asnwer:</p> <ol> <li><p>Instead of implementing <code>JpaSpecificationExecutor</code> you should implement <code>JpaSpecificationExecutor&lt;Travel&gt;</code> to avoid type check warnings.</p></li> <li><p>Please take a look at kostja's excellent answer to this question <a href="https://stackoverflow.com/questions/11138118/really-dynamic-jpa-criteriabuilder">Really dynamic JPA CriteriaBuilder</a> since you <em>will</em> need to implement this if you want to have correct filters.</p></li> <li><p>The best documentation I was able to find for the Criteria API was <a href="http://www.ibm.com/developerworks/library/j-typesafejpa/" rel="noreferrer">http://www.ibm.com/developerworks/library/j-typesafejpa/</a>. This is a rather long read but I totally recommend it - after reading it most of my questions for Root and CriteriaBuilder were answered :)</p></li> <li><p>Reusing the <code>Travel</code> object was not possible because it contained various other objects (who also contained other objects) which I needed to search for using <code>Like</code> - instead I used a <code>TravelSearch</code> object that contained the fields I needed to search for.</p></li> </ol> <p><b>Update 10/05/15</b>: As per @priyank's request, here's how I implemented the TravelSearch object:</p> <pre><code>public class TravelSearch { private String lastName; private School school; private Period period; private String companyName; private TravelTypeEnum travelType; private TravelStatusEnum travelStatus; // Setters + Getters } </code></pre> <p>This object was used by TravelSpecification (most of the code is domain specific but I'm leaving it there as an example):</p> <pre><code>public class TravelSpecification implements Specification&lt;Travel&gt; { private TravelSearch criteria; public TravelSpecification(TravelSearch ts) { criteria= ts; } @Override public Predicate toPredicate(Root&lt;Travel&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) { Join&lt;Travel, Candidacy&gt; o = root.join(Travel_.candidacy); Path&lt;Candidacy&gt; candidacy = root.get(Travel_.candidacy); Path&lt;Student&gt; student = candidacy.get(Candidacy_.student); Path&lt;String&gt; lastName = student.get(Student_.lastName); Path&lt;School&gt; school = student.get(Student_.school); Path&lt;Period&gt; period = candidacy.get(Candidacy_.period); Path&lt;TravelStatusEnum&gt; travelStatus = root.get(Travel_.travelStatus); Path&lt;TravelTypeEnum&gt; travelType = root.get(Travel_.travelType); Path&lt;Company&gt; company = root.get(Travel_.company); Path&lt;String&gt; companyName = company.get(Company_.name); final List&lt;Predicate&gt; predicates = new ArrayList&lt;Predicate&gt;(); if(criteria.getSchool()!=null) { predicates.add(cb.equal(school, criteria.getSchool())); } if(criteria.getCompanyName()!=null) { predicates.add(cb.like(companyName, "%"+criteria.getCompanyName()+"%")); } if(criteria.getPeriod()!=null) { predicates.add(cb.equal(period, criteria.getPeriod())); } if(criteria.getTravelStatus()!=null) { predicates.add(cb.equal(travelStatus, criteria.getTravelStatus())); } if(criteria.getTravelType()!=null) { predicates.add(cb.equal(travelType, criteria.getTravelType())); } if(criteria.getLastName()!=null ) { predicates.add(cb.like(lastName, "%"+criteria.getLastName()+"%")); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); } } </code></pre> <p>Finally, here's my search method:</p> <pre><code>@RequestMapping("/search") public ModelAndView search( @ModelAttribute TravelSearch travelSearch, Pageable pageable) { ModelAndView mav = new ModelAndView("travels/list"); TravelSpecification tspec = new TravelSpecification(travelSearch); Page&lt;Travel&gt; travels = travelRep.findAll(tspec, pageable); PageWrapper&lt;Travel&gt; page = new PageWrapper&lt;Travel&gt;(travels, "/search"); mav.addObject(travelSearch); mav.addObject("page", page); mav.addObject("schools", schoolRep.findAll() ); mav.addObject("periods", periodRep.findAll() ); mav.addObject("travelTypes", TravelTypeEnum.values()); mav.addObject("travelStatuses", TravelStatusEnum.values()); return mav; } </code></pre> <p>Hope I helped!</p>
0
2,670
Errors installing PyAudio "Failed Building Wheel for PyAudio"
<p>I have been having trouble finding a fix for getting PyAudio installed on my machine. I have tried a few different solutions and i do have the prerequisite library "portaudio" installed using homebrew. I have also looked for solutions to the gcc error that appears at the bottom of the output and to which solutions only generated a different error that read "Error: command ‘clang’ failed with exit status 1". I feel at this point it is some lack of understanding of the implications of these error messages due to a lack of experience in python that keeps me from understanding a resolution. Any help is greatly appreciated. Thank you.</p> <pre><code>MacBook-Pro-2:~ MyName$ pip install pyaudio Collecting pyaudio Using cached PyAudio-0.2.11.tar.gz Building wheels for collected packages: pyaudio Running setup.py bdist_wheel for pyaudio ... error Complete output from command /Users/MyName/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-build-r_jfrp4_/pyaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/tmpxdj3hlo2pip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.7-x86_64-3.6 copying src/pyaudio.py -&gt; build/lib.macosx-10.7-x86_64-3.6 running build_ext building '_portaudio' extension creating build/temp.macosx-10.7-x86_64-3.6 creating build/temp.macosx-10.7-x86_64-3.6/src gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/MyName/anaconda3/include -arch x86_64 -I/Users/MyName/anaconda3/include -arch x86_64 -DMACOSX=1 -I/Users/MyName/anaconda3/include/python3.6m -c src/_portaudiomodule.c -o build/temp.macosx-10.7-x86_64-3.6/src/_portaudiomodule.o In file included from src/_portaudiomodule.c:33: In file included from /usr/local/include/pa_mac_core.h:48: In file included from /System/Library/Frameworks/AudioUnit.framework/Headers/AudioUnit.h:1: In file included from /System/Library/Frameworks/AudioToolbox.framework/Headers/AudioUnit.h:16: In file included from /System/Library/Frameworks/AudioToolbox.framework/Headers/AudioComponent.h:167: In file included from /System/Library/Frameworks/CoreAudio.framework/Headers/CoreAudioTypes.h:30: In file included from /System/Library/Frameworks/CoreFoundation.framework/Headers/CFBase.h:72: /usr/local/include/Block.h:16:3: error: Never include this file directly. Use &lt;lzma.h&gt; instead. # error Never include this file directly. Use &lt;lzma.h&gt; instead. ^ /usr/local/include/Block.h:93:2: error: unknown type name 'lzma_check' lzma_check check; ^ /usr/local/include/Block.h:148:2: error: unknown type name 'lzma_vli' lzma_vli compressed_size; ^ /usr/local/include/Block.h:172:2: error: unknown type name 'lzma_vli' lzma_vli uncompressed_size; ^ /usr/local/include/Block.h:200:2: error: unknown type name 'lzma_filter' lzma_filter *filters; ^ /usr/local/include/Block.h:217:20: error: use of undeclared identifier 'LZMA_CHECK_SIZE_MAX' uint8_t raw_check[LZMA_CHECK_SIZE_MAX]; ^ /usr/local/include/Block.h:231:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int3; ^ /usr/local/include/Block.h:232:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int4; ^ /usr/local/include/Block.h:233:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int5; ^ /usr/local/include/Block.h:234:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int6; ^ /usr/local/include/Block.h:235:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int7; ^ /usr/local/include/Block.h:236:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int8; ^ /usr/local/include/Block.h:237:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum1; ^ /usr/local/include/Block.h:238:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum2; ^ /usr/local/include/Block.h:239:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum3; ^ /usr/local/include/Block.h:240:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum4; ^ /usr/local/include/Block.h:261:2: error: unknown type name 'lzma_bool' lzma_bool ignore_check; ^ /usr/local/include/Block.h:263:2: error: unknown type name 'lzma_bool' lzma_bool reserved_bool2; ^ /usr/local/include/Block.h:264:2: error: unknown type name 'lzma_bool' lzma_bool reserved_bool3; ^ fatal error: too many errors emitted, stopping now [-ferror-limit=] 20 errors generated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for pyaudio Running setup.py clean for pyaudio Failed to build pyaudio Installing collected packages: pyaudio Running setup.py install for pyaudio ... error Complete output from command /Users/MyName/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-build-r_jfrp4_/pyaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-mxjvhl6h-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.macosx-10.7-x86_64-3.6 copying src/pyaudio.py -&gt; build/lib.macosx-10.7-x86_64-3.6 running build_ext building '_portaudio' extension creating build/temp.macosx-10.7-x86_64-3.6 creating build/temp.macosx-10.7-x86_64-3.6/src gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/MyName/anaconda3/include -arch x86_64 -I/Users/MyName/anaconda3/include -arch x86_64 -DMACOSX=1 -I/Users/MyName/anaconda3/include/python3.6m -c src/_portaudiomodule.c -o build/temp.macosx-10.7-x86_64-3.6/src/_portaudiomodule.o In file included from src/_portaudiomodule.c:33: In file included from /usr/local/include/pa_mac_core.h:48: In file included from /System/Library/Frameworks/AudioUnit.framework/Headers/AudioUnit.h:1: In file included from /System/Library/Frameworks/AudioToolbox.framework/Headers/AudioUnit.h:16: In file included from /System/Library/Frameworks/AudioToolbox.framework/Headers/AudioComponent.h:167: In file included from /System/Library/Frameworks/CoreAudio.framework/Headers/CoreAudioTypes.h:30: In file included from /System/Library/Frameworks/CoreFoundation.framework/Headers/CFBase.h:72: /usr/local/include/Block.h:16:3: error: Never include this file directly. Use &lt;lzma.h&gt; instead. # error Never include this file directly. Use &lt;lzma.h&gt; instead. ^ /usr/local/include/Block.h:93:2: error: unknown type name 'lzma_check' lzma_check check; ^ /usr/local/include/Block.h:148:2: error: unknown type name 'lzma_vli' lzma_vli compressed_size; ^ /usr/local/include/Block.h:172:2: error: unknown type name 'lzma_vli' lzma_vli uncompressed_size; ^ /usr/local/include/Block.h:200:2: error: unknown type name 'lzma_filter' lzma_filter *filters; ^ /usr/local/include/Block.h:217:20: error: use of undeclared identifier 'LZMA_CHECK_SIZE_MAX' uint8_t raw_check[LZMA_CHECK_SIZE_MAX]; ^ /usr/local/include/Block.h:231:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int3; ^ /usr/local/include/Block.h:232:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int4; ^ /usr/local/include/Block.h:233:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int5; ^ /usr/local/include/Block.h:234:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int6; ^ /usr/local/include/Block.h:235:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int7; ^ /usr/local/include/Block.h:236:2: error: unknown type name 'lzma_vli' lzma_vli reserved_int8; ^ /usr/local/include/Block.h:237:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum1; ^ /usr/local/include/Block.h:238:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum2; ^ /usr/local/include/Block.h:239:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum3; ^ /usr/local/include/Block.h:240:2: error: unknown type name 'lzma_reserved_enum' lzma_reserved_enum reserved_enum4; ^ /usr/local/include/Block.h:261:2: error: unknown type name 'lzma_bool' lzma_bool ignore_check; ^ /usr/local/include/Block.h:263:2: error: unknown type name 'lzma_bool' lzma_bool reserved_bool2; ^ /usr/local/include/Block.h:264:2: error: unknown type name 'lzma_bool' lzma_bool reserved_bool3; ^ fatal error: too many errors emitted, stopping now [-ferror-limit=] 20 errors generated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/Users/MyName/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-build-r_jfrp4_/pyaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-mxjvhl6h-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-build-r_jfrp4_/pyaudio/ </code></pre>
0
4,586
How do I use Java to read a .csv file and insert its data into SQL Server?
<p>I am very new to Java. I have a task with two steps.</p> <ol> <li>I want to read all data from a <code>.csv</code> file.</li> <li>After reading that data I have to put it into a SQL Server database.</li> </ol> <p>I have done step one. I'm able to read the <code>.csv</code> file data, but I don't know that how to insert it into a database.</p> <p>Here's my code for fetching the <code>.csv</code> file data:</p> <pre><code>import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class DBcvsdataextractor { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String fileName="D:/USPresident Wikipedia URLs Thumbs HS.csv"; try { BufferedReader br = new BufferedReader( new FileReader(fileName)); StringTokenizer st = null; int lineNumber = 0, tokenNumber = 0; while( (fileName = br.readLine()) != null) { if(lineNumber++ == 0) continue; //break comma separated line using "," st = new StringTokenizer(fileName, ","); while(st.hasMoreTokens()) { //display csv values tokenNumber++; System.out.print(st.nextToken() + '\t'); } //new line System.out.println(" "); //reset token number tokenNumber = 0; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>Now, how do I insert that data into SQL Server?</p>
0
1,045
Difference between an empty ArrayList and an ArrayList with null elements?
<p>I am coding some validators for a REST service which parse a JSON and I found out something that sounds wierd for me (I am not a <strong><em>JAVA expert</em></strong> at all).</p> <p>Consider having two <strong><em>ArrayLists</em></strong>: </p> <pre><code>ArrayList&lt;Object&gt; list1 = new ArrayList&lt;Object&gt;(); ArrayList&lt;Object&gt; list2 = new ArrayList&lt;Object&gt;(); </code></pre> <p>Both lists have something in <strong><em>common</em></strong>: they are <em>completely empty</em> (or full of null elements). But if I do:</p> <pre><code>list1.add(null); </code></pre> <p>Although both remain completely <strong><em>empty</em></strong>, <em>they have completely different behaviors</em>. And to make some methods the results are <strong><em>very different</em></strong>:</p> <pre><code>System.out.println(list1.contains(null)); //prints true! System.out.println(list2.contains(null)); //prints false System.out.println(CollectionUtils.isNotEmpty(list1)); //prints true System.out.println(CollectionUtils.isNotEmpty(list2)); //prints false System.out.println(list1.size()); //prints 1 System.out.println(list2.size()); //prints 0 </code></pre> <p>Doing some research, and looking at the implementation of each of these methods, you can determine the reason for these differences, but still do not understand why it would be valid or useful to differentiate between these lists.</p> <ul> <li>Why <strong><em>add(item)</em></strong> doesnt validate if <strong>item!=null</strong> ? </li> <li>Why <strong><em>contains(null)</em></strong> says <strong>false</strong> if the list is full of <strong>nulls</strong>?</li> </ul> <p>Thanks in advance!!!</p> <p><strong><em>EDIT:</em></strong></p> <p>I am mostly agree whit the answers, but I'm not yet convinced all. This is the implementation of the method remove:</p> <pre><code>/** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * &lt;tt&gt;i&lt;/tt&gt; such that * &lt;tt&gt;(o==null&amp;nbsp;?&amp;nbsp;get(i)==null&amp;nbsp;:&amp;nbsp;o.equals(get(i)))&lt;/tt&gt; * (if such an element exists). Returns &lt;tt&gt;true&lt;/tt&gt; if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return &lt;tt&gt;true&lt;/tt&gt; if this list contained the specified element */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index &lt; size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index &lt; size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } /* * Private remove method that skips bounds checking and does not * return the value removed. */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved &gt; 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work } </code></pre> <p>So, now if i do:</p> <pre><code>ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); list.add(null); System.out.println(list.contains(null)); //prints true! list.remove(null); System.out.println(list.contains(null)); //prints false! </code></pre> <p><strong><em>what I'm missing?</em></strong></p>
0
1,362
Get item by id in Room
<p>I'm using Room + LiveData in my Android project. Following to Google Blueprints, I've implemented data layer of my application.</p> <p>This is how my Dao looks like:</p> <pre><code>@Query("SELECT * FROM events WHERE id=:arg0") fun loadSingle(id: String): LiveData&lt;Event&gt; </code></pre> <p>I'm calling it from my EventRepository:</p> <pre><code>fun loadSingle(eventId: String): LiveData&lt;RequestReader&lt;Event&gt;&gt; { return object: NetworkManager&lt;Event, Event&gt;(appExecutors!!) { override fun loadLocal(): LiveData&lt;Event&gt; { val item = eventLocal!!.loadSingle("Title 1") Crashlytics.log(Log.VERBOSE, TAG, "loadFromServer::loadLocal=$item") return item } override fun isUpdateForced(data: Event?): Boolean { Crashlytics.log(Log.VERBOSE, TAG, "loadFromServer::isUpdateForced") return data == null || requestTimeout.isAllowed(UNDEFINED_KEY.toString()) } override fun makeRequest(): LiveData&lt;ApiResponse&lt;Event&gt;&gt; { Crashlytics.log(Log.VERBOSE, TAG, "loadFromServer::makeRequest") return Database.createService(EventRemote::class.java).load(eventId) } override fun onSuccess(item: Event) { eventLocal?.save(item) } override fun onFail() { Crashlytics.log(Log.VERBOSE, TAG, "loadFromServer::onFail") requestTimeout.reset(UNDEFINED_KEY.toString()) } }.liveData } </code></pre> <p>Where NetworkManager class is (has been "taken" from <strong><a href="https://developer.android.com/topic/libraries/architecture/guide.html#addendum" rel="noreferrer">here</a></strong>):</p> <pre><code> abstract class NetworkManager&lt;ResultType, RequestType&gt; @MainThread constructor(val appExecutors: AppExecutors) { companion object { private val TAG = "TAG_NETWORK_MANAGER" } val liveData: MediatorLiveData&lt;RequestReader&lt;ResultType&gt;&gt; = MediatorLiveData() init { liveData.value = RequestReader.loading(null) val localSource: LiveData&lt;ResultType&gt; = loadLocal() Log.d(TAG, "before add::localSource=${localSource.value}") liveData.addSource(localSource, { data -&gt; Log.d(TAG, "data=$data") liveData.removeSource(localSource) if (isUpdateForced(data)) { loadRemote(localSource) } else { liveData.addSource(localSource, { reusedData -&gt; liveData.value = RequestReader.success(reusedData)}) } }) } private fun loadRemote(localSource: LiveData&lt;ResultType&gt;) { val remoteSource = makeRequest() liveData.addSource(localSource, { liveData.value = RequestReader.success(it) }) liveData.addSource(remoteSource) { response -&gt; liveData.removeSource(localSource) liveData.removeSource(remoteSource) if (response!!.isSuccessful) { appExecutors.diskIO.execute { onSuccess(processResponse(response)) appExecutors.mainThread.execute { liveData.addSource(localSource, { liveData.value = RequestReader.success(it) }) } } } else { onFail() liveData.addSource(localSource, { liveData.value = RequestReader.error("Error: ${response.errorMessage}", it) }) } } } @MainThread protected abstract fun loadLocal(): LiveData&lt;ResultType&gt; @MainThread protected abstract fun isUpdateForced(data: ResultType?): Boolean @MainThread protected abstract fun makeRequest(): LiveData&lt;ApiResponse&lt;RequestType&gt;&gt; @WorkerThread protected abstract fun onSuccess(item: RequestType) @MainThread protected abstract fun onFail() @WorkerThread protected fun processResponse(response: ApiResponse&lt;RequestType&gt;): RequestType { return response.body!! } } </code></pre> <p>And after i expect to get my LiveData in ViewModel:</p> <pre><code>open class EventSingleViewModel: ViewModel(), RepositoryComponent.Injectable { companion object { private val TAG = "TAG_EVENT_SINGLE_VIEW_MODEL" } @Inject lateinit var eventRepository: EventRepository var eventSingle: LiveData&lt;RequestReader&lt;Event&gt;&gt;? = null override fun inject(repositoryComponent: RepositoryComponent) { repositoryComponent.inject(this) eventSingle = MutableLiveData&lt;RequestReader&lt;Event&gt;&gt;() } fun load(eventId: String) { Crashlytics.log(Log.VERBOSE, TAG, "starts to loadList::eventId=$eventId") eventSingle = eventRepository.loadSingle(eventId) } } </code></pre> <p><strong>The problem.</strong> I'm getting a list of events the same way (it works!) I've described above, but with a single event (this event is already in database) it doesn't work. I've found out that localSource.value is null (in <strong>NetworkManager</strong>). Maybe my query is bad or.. something else.</p>
0
2,507
Filling empty cells in CSS Grid Layout
<p>I have a set of div tiles that I've arranged through the CSS Grid Layout as "automatically" as possible; my final idea is that even if I don't know how many tiles there are, they all get sized and placed correctly. This is working fine.</p> <p>Now, I'm looking to double the area of any tile that is clicked on. As far as I know, that means increasing the span of this tile:</p> <pre><code>grid-row: span 2; grid-column: span 2; </code></pre> <p>I'm happy with the results if I click on any tile that is not in the right-most column. When the rightmost tiles get expanded, they are wrapped down onto the next line.</p> <p>Is there any way to force these tiles to expand to the left, so that other non-active tiles are wrapped instead?</p> <p>Codepen example <a href="https://codepen.io/f2theogle/pen/RgeKvG" rel="noreferrer">here</a></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>$('div.tile').click(function() { $('div.tile').not(this).removeClass('chosen'); $(this).toggleClass('chosen'); /* Attempt to find current placement, to see if we could change the span rules based on results. Probably disregard. */ var colCount = $('div.wrapper').css('grid-template-columns').split(' ').length; console.log(colCount); var placement = $(this).css('grid-row'); console.log(placement); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; padding: 0; background-color: #eee; } .wrapper { display: grid; margin: 18px; grid-template-columns: repeat(auto-fill, minmax(252px, 1fr)); grid-auto-rows: 286px; grid-gap: 18px; } .tile { position: relative; background-color: #eee; background-color: #149; text-align: center; box-shadow: 0 3px 12px rgba(0,0,0, 0.15), 0 4px 6px rgba(0,0,0, 0.25); } .tile.chosen { grid-row: span 2; grid-column: span 2; } .tile.chosen::before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; content: " "; background-color: rgba(255,255,255,.2); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="wrapper"&gt; &lt;div class="tile"&gt;A&lt;/div&gt; &lt;div class="tile"&gt;B&lt;/div&gt; &lt;div class="tile"&gt;C&lt;/div&gt; &lt;div class="tile"&gt;D&lt;/div&gt; &lt;div class="tile"&gt;E&lt;/div&gt; &lt;div class="tile"&gt;F&lt;/div&gt; &lt;div class="tile"&gt;G&lt;/div&gt; &lt;div class="tile"&gt;H&lt;/div&gt; &lt;div class="tile"&gt;I&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
0
1,089
netTCP binding Soap Security Negotiation Failed
<p>I am writing a WCF service requires impersonate and session.<br/></p> <p>It is ok when I tried to call it on my local machine, but on the remote machine it always failed with such error:</p> <blockquote> <p>Security Support Provider Interface (SSPI) authentication failed. The server may not be running in an account with identity 'host/hostname'. If the server is running in a service account (Network Service for example), specify the account's ServicePrincipalName as the identity in the EndpointAddress for the server. If the server is running in a user account, specify the account's UserPrincipalName as the identity in the EndpointAddress for the server.</p> </blockquote> <p>If I provided a upn, it throws an identity failed exception.</p> <p>Here is my config:</p> <p>Server Config(APP):</p> <pre><code>&lt;system.serviceModel&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="default"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceAuthorization impersonateCallerForAllOperations="true" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;bindings&gt; &lt;netTcpBinding&gt; &lt;binding name="DataService.netTcpBinding"&gt; &lt;readerQuotas maxArrayLength="65535" maxBytesPerRead="2147483647" maxStringContentLength="2147483647"/&gt; &lt;reliableSession enabled="true" inactivityTimeout="24:00:00" ordered="true"/&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;message clientCredentialType="Windows" /&gt; &lt;transport clientCredentialType="Windows"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/netTcpBinding&gt; &lt;/bindings&gt; &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/&gt; &lt;services&gt; &lt;service behaviorConfiguration="default" name="DataService.DataService"&gt; &lt;endpoint address="" binding="netTcpBinding" bindingConfiguration="DataService.netTcpBinding" name="DataService.DataService" contract="DataService.IDataService"/&gt; &lt;endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://address:4504/"/&gt; &lt;add baseAddress="net.tcp://address:4503/"/&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; &lt;/system.serviceModel&gt; </code></pre> <p>Client Config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;netTcpBinding&gt; &lt;binding name="DataService.DataService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536"&gt; &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /&gt; &lt;reliableSession ordered="true" inactivityTimeout="24.00:00:00" enabled="true" /&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" /&gt; &lt;message clientCredentialType="Windows" algorithmSuite="Default" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/netTcpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="net.tcp://address:4503/" binding="netTcpBinding" bindingConfiguration="DataService.DataService" contract="ataService.IDataService" name="DataService.DataService"&gt; &lt;identity&gt; &lt;dns value="DOMAIN"/&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p>Any help would be greatly appreciated.</p>
0
2,140
"You don't have a SNAPSHOT project in the reactor projects list." when using Jenkins Maven release plugin
<p>I'm using SVN, Maven 3.0.3 on the latest version of Jenkins and the Maven Release plugin. I'm trying to use the Maven release plugin (through Jenkins) do a dry run and so am executing the options …</p> <pre><code>Executing Maven: -B -f /scratch/jenkins/workspace/myproject/myproject/pom.xml -DdevelopmentVersion=53.0.0-SNAPSHOT -DreleaseVersion=52.0.0 -Dusername=***** -Dpassword=********* -DskipTests -P prod -Dresume=false -DdryRun=true release:prepare </code></pre> <p>But the dry run is dying with the error below …</p> <pre><code>[JENKINS] Archiving /scratch/jenkins/workspace/myproject/myproject/pom.xml to /home/evotext/hudson_home/jobs/myproject/modules/org.mainco.subco$myproject/builds/2013-11-18_16-09-14/archive/org.mainco.subco/myproject/52.0.0/myproject-52.0.0.pom Waiting for Jenkins to finish collecting data mavenExecutionResult exceptions not empty message : Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.0:prepare (default-cli) on project myproject: You don't have a SNAPSHOT project in the reactor projects list. cause : You don't have a SNAPSHOT project in the reactor projects list. Stack trace : org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.0:prepare (default-cli) on project myproject: You don't have a SNAPSHOT project in the reactor projects list. at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.jvnet.hudson.maven3.launcher.Maven3Launcher.main(Maven3Launcher.java:117) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239) at org.jvnet.hudson.maven3.agent.Maven3Main.launch(Maven3Main.java:178) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at hudson.maven.Maven3Builder.call(Maven3Builder.java:129) at hudson.maven.Maven3Builder.call(Maven3Builder.java:67) at hudson.remoting.UserRequest.perform(UserRequest.java:118) at hudson.remoting.UserRequest.perform(UserRequest.java:48) at hudson.remoting.Request$2.run(Request.java:326) at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: org.apache.maven.plugin.MojoFailureException: You don't have a SNAPSHOT project in the reactor projects list. at org.apache.maven.plugins.release.PrepareReleaseMojo.prepareRelease(PrepareReleaseMojo.java:219) at org.apache.maven.plugins.release.PrepareReleaseMojo.execute(PrepareReleaseMojo.java:181) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) ... 30 more Caused by: org.apache.maven.shared.release.ReleaseFailureException: You don't have a SNAPSHOT project in the reactor projects list. at org.apache.maven.shared.release.phase.CheckPomPhase.execute(CheckPomPhase.java:111) at org.apache.maven.shared.release.phase.CheckPomPhase.simulate(CheckPomPhase.java:123) at org.apache.maven.shared.release.DefaultReleaseManager.prepare(DefaultReleaseManager.java:199) at org.apache.maven.shared.release.DefaultReleaseManager.prepare(DefaultReleaseManager.java:140) at org.apache.maven.shared.release.DefaultReleaseManager.prepare(DefaultReleaseManager.java:103) at org.apache.maven.plugins.release.PrepareReleaseMojo.prepareRelease(PrepareReleaseMojo.java:211) ... 33 more </code></pre> <p>My SVN checkout method is set to "Always checkout a fresh copy" and I have a snapshot version in question in my snapshot repository, but not in my release repository. Is there a way I can get the "reactor projects list" to look at my snapshot repo?</p> <p><b>Edit:</b> I'm including the snippet of my pom where the project gets its version -- it inherits it from a parent</p> <pre><code> &lt;parent&gt; &lt;artifactId&gt;subco&lt;/artifactId&gt; &lt;groupId&gt;org.mainco.subco&lt;/groupId&gt; &lt;version&gt;52.0.0&lt;/version&gt; &lt;/parent&gt; </code></pre>
0
2,053
EntityDataSource and Entity Framework 6
<p>I am learning ASP.NET. I came to EntityDataSorce control. I am using EF6. I have read that this control and EF6 have some issues, conflicts, but with the last update to EntityDataSource this issue has solved. <a href="http://blogs.msdn.com/b/webdev/archive/2014/02/28/announcing-the-release-of-dynamic-data-provider-and-entitydatasource-control-for-entity-framework-6.aspx" rel="noreferrer">http://blogs.msdn.com/b/webdev/archive/2014/02/28/announcing-the-release-of-dynamic-data-provider-and-entitydatasource-control-for-entity-framework-6.aspx</a></p> <p>I am trying to follow above link. First I create an .edmx model</p> <p><img src="https://i.stack.imgur.com/xgY4N.png" alt="enter image description here"></p> <p>Install new EntityDataSource Contro with NuGet</p> <p><img src="https://i.stack.imgur.com/8URUS.png" alt="enter image description here"></p> <p>I added two EntityDataSource controls and changed prefix of one of them to ef. So I have two control one of them is old and other one is new updated</p> <p><img src="https://i.stack.imgur.com/6ggxs.png" alt="enter image description here"></p> <p>When I click the old one I can see the configuration popup and reach the Configure Data Source screen. But when click on the new one there is no popup. So, how can I configure data source? What is wrong with this?</p> <p><img src="https://i.stack.imgur.com/3uLWx.png" alt="enter image description here"></p> <p>Web.config</p> <pre><code> &lt;?xml version="1.0"?&gt; &lt;!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt; &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/&gt; &lt;/configSections&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.5"&gt; &lt;assemblies&gt; &lt;add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/&gt; &lt;add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; &lt;httpRuntime targetFramework="4.5"/&gt; &lt;pages&gt; &lt;controls&gt; &lt;add tagPrefix="ef" assembly="Microsoft.AspNet.EntityDataSource" namespace="Microsoft.AspNet.EntityDataSource"/&gt; &lt;/controls&gt; &lt;/pages&gt; &lt;/system.web&gt; &lt;connectionStrings&gt; &lt;add name="SampleDbEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=OMER-HP\SQLEXPRESS2014OK;initial catalog=SampleDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient"/&gt; &lt;/connectionStrings&gt; &lt;entityFramework&gt; &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt; &lt;parameters&gt; &lt;parameter value="mssqllocaldb"/&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt; &lt;providers&gt; &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/&gt; &lt;/providers&gt; &lt;/entityFramework&gt; &lt;/configuration&gt; </code></pre> <p>Default.aspx:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication6.Default" %&gt; &lt;!DOCTYPE html&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;ef:EntityDataSource ID="EntityDataSourceNew" runat="server"&gt; &lt;/ef:EntityDataSource&gt; &lt;br /&gt; &lt;asp:EntityDataSource ID="EntityDataSourceOld" runat="server"&gt; &lt;/asp:EntityDataSource&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
1,730
"GPU process isn't usable. Goodbye."
<p>I'm experimenting with building a Windows and Mac OS app using Electron and have hit a snag.</p> <p>In short, if I try to run the application directly with Electron on Mac OS Big Sur (as opposed to building a Mac app and then running that) I get the following error returned:</p> <pre><code>[35941:0821/171720.038162:FATAL:gpu_data_manager_impl_private.cc(415)] GPU process isn't usable. Goodbye. </code></pre> <p>I am running directly with Electron using the following in my <code>package.json</code>:</p> <pre><code>&quot;scripts&quot;: { ... &quot;test&quot;: &quot;electron main.js&quot;, ... } </code></pre> <p>So far the only Mac OS environment I have access to is Big Sur so haven't tried this on earlier versions of Mac OS but from Googling it seems this error may be related to Big Sur's tightened security/sandbox constraints -- but I am guessing about that.</p> <p>In any case, after some Googling several suggestions indicated trying to run without the app sandbox, i.e. adding this to <code>main.js</code>:</p> <pre><code>app.commandLine.appendSwitch('no-sandbox'); </code></pre> <p>That's all well and good and works.</p> <p>However, if I ever want to build and distribute a signed Mac app targeting the Mac App store or a just a signed, sandboxed DMG or PKG installer, then this won't be suitable.</p> <p>If I remove the above <code>no-sandbox</code> command from <code>main.js</code> and specify the app sandbox in my entitlements <code>plist</code> as shown below the resulting signed app will not run:</p> <pre><code>&lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;true/&gt; </code></pre> <p>The app tries to open and just closes. I can try running at the command line with <code>open &lt;appname&gt;.app</code> but this throws the following error in the console:</p> <pre><code>The application cannot be opened for an unexpected reason, error=Error Domain=NSOSStatusErrorDomain Code=-10826 &quot;kLSNoLaunchPermissionErr: User doesn't have permission to launch the app (managed networks)&quot; UserInfo={_LSFunction=_LSLaunchWithRunningboard, _LSLine=2561, NSUnderlyingError=0x7fd3c9c13db0 {Error Domain=RBSRequestErrorDomain Code=5 &quot;Launch failed.&quot; UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x7fd3c9c158e0 {Error Domain=NSPOSIXErrorDomain Code=153 &quot;Unknown error: 153&quot; UserInfo={NSLocalizedDescription=Launchd job spawn failed with error: 153}}}}} </code></pre> <p>If I build a signed app with <code>no-sandbox</code> enabled, the app will run just fine on Big Sur using <code>open &lt;appname&gt;.app</code>.</p> <p>I have tried my best through Google, Stack Overflow, etc to diagnose this but am not getting anywhere. Here's to hoping the Stack Overflow community can provide me the critical clue to solving this.</p> <p>For further context, I created a new, empty Electron application and followed the <a href="https://www.electronjs.org/docs/latest/tutorial/quick-start" rel="noreferrer">Electron Quick Start Guide</a> to the section where it describes creating an empty <code>main.js</code> which technically should allow the Electron app to start -- but it won't. The same error describe above re the GPU gets thrown even without instantiating a <code>BrowserWindow</code> or writing any custom code of my own.</p> <p>NEW UPDATE: I set these environment variables to true and then tried running the app with <code>npm start</code>:</p> <ul> <li><code>ELECTRON_ENABLE_LOGGING</code></li> <li><code>ELECTRON_DEBUG_NOTIFICATIONS</code></li> <li><code>ELECTRON_ENABLE_STACK_DUMPING</code></li> </ul> <p>The result is more detailed error output:</p> <pre><code>[48836:0823/165857.676747:ERROR:icu_util.cc(179)] icudtl.dat not found in bundle [48836:0823/165857.676838:ERROR:icu_util.cc(243)] Invalid file descriptor to ICU data received. [48778:0823/165857.677376:ERROR:gpu_process_host.cc(1003)] GPU process exited unexpectedly: exit_code=5 [48778:0823/165857.677430:WARNING:gpu_process_host.cc(1317)] The GPU process has crashed 1 time(s) [48850:0823/165857.827224:ERROR:icu_util.cc(179)] icudtl.dat not found in bundle [48848:0823/165857.827255:ERROR:icu_util.cc(179)] icudtl.dat not found in bundle [48850:0823/165857.827341:ERROR:icu_util.cc(243)] Invalid file descriptor to ICU data received. [48848:0823/165857.827358:ERROR:icu_util.cc(243)] Invalid file descriptor to ICU data received. [48778:0823/165857.827836:ERROR:gpu_process_host.cc(1003)] GPU process exited unexpectedly: exit_code=5 [48778:0823/165857.827875:WARNING:gpu_process_host.cc(1317)] The GPU process has crashed 2 time(s) ... repeats until the GPU processes crashes 9 times ... [48778:0823/165903.080134:FATAL:gpu_data_manager_impl_private.cc(415)] GPU process isn't usable. Goodbye. </code></pre> <p>Haven't had time to do the research as to what ICU refers to but thought I would update with this info.</p> <p>ANOTHER UPDATE: all this has been done on Mac OS Big Sur which is my main development machine. Trying this on a Windows 10 machine, using the same Electron code, dependencies, etc and things work fine. So the problem is either related to Mac OS Big Sur or a specific local issue on my development machine which I cannot identify. Any suggestions on how to diagnose this will be much appreciated.</p> <p>ONE MORE UPDATE: Based on a guess, I created a new user on my mac, took the code in there and it ran perfectly. So -- this probably means that I need to find something installed in my profile or some corruption in my own profile/settings that is breaking things. As always, any suggestions appreciated it.</p>
0
1,737
ValueError: Traceback (most recent call last) <ipython-input-15-d27c936e2293> in <module>()
<p>I am trying to read the data from a csv file and I am getting this error:</p> <hr> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-15-d27c936e2293&gt; in &lt;module&gt;() 11 for row in header: 12 # row = [Date, Open, High, Low, Close, Volume, Adj. close] ---&gt; 13 date = datetime.strptime(row[0], '%m/%d/%Y') 14 open_price = float(row[1]) 15 high = float(row[2]) ~/anaconda3/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format) 563 """Return a class cls instance based on the input string and the 564 format string.""" --&gt; 565 tt, fraction = _strptime(data_string, format) 566 tzname, gmtoff = tt[-2:] 567 args = tt[:6] + (fraction,) ~/anaconda3/lib/python3.6/_strptime.py in _strptime(data_string, format) 360 if not found: 361 raise ValueError("time data %r does not match format %r" % --&gt; 362 (data_string, format)) 363 if len(data_string) != found.end(): 364 raise ValueError("unconverted data remains: %s" % ValueError: time data 'D' does not match format '%m/%d/%Y' </code></pre> <p>Here's my code: </p> <pre><code>import csv from datetime import datetime path ="google_stock_data.csv" file = open (path, newline = '') reader = csv.reader(file) header = next (reader) data = [] for row in header: # row = [Date, Open, High, Low, Close, Volume, Adj. close] date = datetime.strptime(row[0], '%m/%d/%Y') open_price = float(row[1]) high = float(row[2]) low = float(row[3]) close = float(row[4]) volume = float(row[5]) adj_close = float(row[6]) data.append([date, open_price, high, low, close, volume, adj_close]) print(data[0]) </code></pre> <p>NOTE: The data in the file looks like this: </p> <pre><code>Date Open High Low Close Volume Adj Close 8/19/14 585.002622 587.342658 584.002627 586.862643 978600 586.862643 8/18/14 576.11258 584.512631 576.002598 582.162619 1284100 582.162619 8/15/14 577.862619 579.382595 570.522603 573.482626 1519100 573.482626 8/14/14 576.182596 577.902645 570.882599 574.652582 985400 574.652582 </code></pre> <p>Why is that? Isn't the data being converted to the proper type? Please help. How can I fix it? </p> <p>Thanks. </p>
0
1,102
Why am I getting "undefined reference to `dladdr'" even with -ldl for this simple program?
<p>I'm working through an <a href="http://llvm.org/releases/2.6/docs/tutorial/JITTutorial1.html">LLVM Tutorial</a>, but I'm having trouble compiling. I've written a minimal example that reproduces the issue:</p> <pre><code>#include "llvm/Module.h" #include "llvm/LLVMContext.h" int main(int argc, char **argv) { llvm::Module *module = new llvm::Module("test", llvm::getGlobalContext()); return 0; } </code></pre> <p>When I try to compile, I get a bunch of 'undefined reference' erros:</p> <pre><code>clang++ `llvm-config --cxxflags` -c -o test.o test.cpp clang++ test.o `llvm-config --ldflags --libs core` -o test /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Signals.o): In function `PrintStackTrace(void*)': (.text+0x6c): undefined reference to `dladdr' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Signals.o): In function `PrintStackTrace(void*)': (.text+0x1f6): undefined reference to `dladdr' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Mutex.o): In function `llvm::sys::MutexImpl::MutexImpl(bool)': (.text+0x53): undefined reference to `pthread_mutexattr_init' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Mutex.o): In function `llvm::sys::MutexImpl::MutexImpl(bool)': (.text+0x64): undefined reference to `pthread_mutexattr_settype' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Mutex.o): In function `llvm::sys::MutexImpl::MutexImpl(bool)': (.text+0x74): undefined reference to `pthread_mutexattr_setpshared' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Mutex.o): In function `llvm::sys::MutexImpl::MutexImpl(bool)': (.text+0x88): undefined reference to `pthread_mutexattr_destroy' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Mutex.o): In function `llvm::sys::MutexImpl::tryacquire()': (.text+0x179): undefined reference to `pthread_mutex_trylock' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(RWMutex.o): In function `llvm::sys::RWMutexImpl::RWMutexImpl()': (.text+0x3e): undefined reference to `pthread_rwlock_init' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(RWMutex.o): In function `llvm::sys::RWMutexImpl::~RWMutexImpl()': (.text+0x80): undefined reference to `pthread_rwlock_destroy' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(RWMutex.o): In function `llvm::sys::RWMutexImpl::reader_acquire()': (.text+0xb9): undefined reference to `pthread_rwlock_rdlock' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(RWMutex.o): In function `llvm::sys::RWMutexImpl::reader_release()': (.text+0xe9): undefined reference to `pthread_rwlock_unlock' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(RWMutex.o): In function `llvm::sys::RWMutexImpl::writer_acquire()': (.text+0x119): undefined reference to `pthread_rwlock_wrlock' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(RWMutex.o): In function `llvm::sys::RWMutexImpl::writer_release()': (.text+0x149): undefined reference to `pthread_rwlock_unlock' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Threading.o): In function `llvm::llvm_execute_on_thread(void (*)(void*), void*, unsigned int)': (.text+0x1cc): undefined reference to `pthread_create' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Threading.o): In function `llvm::llvm_execute_on_thread(void (*)(void*), void*, unsigned int)': (.text+0x208): undefined reference to `pthread_attr_setstacksize' /usr/lib/llvm-2.9/lib/libLLVMSupport.a(Threading.o): In function `llvm::llvm_execute_on_thread(void (*)(void*), void*, unsigned int)': (.text+0x228): undefined reference to `pthread_join' clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [test] Error 1 </code></pre> <p>If I view the manpage for dladdr, it says that I need to link with <code>-ldl</code>. But I'm already doing that with <code>llvm-config</code>:</p> <pre><code>$ llvm-config --ldflags --libs core -L/usr/lib/llvm-2.9/lib -lpthread -lffi -ldl -lm -lLLVMCore -lLLVMSupport -L/usr/lib/llvm-2.9/lib </code></pre> <p>Additionally, <code>-ldl</code> appears in the correct order (i.e., after the <code>.o</code> file that requires the symbols).</p> <p>I'm at a loss for the next step in debugging this issue. Can anyone point me in the right direction? I'm running LVVM 2.9-7 on Ubuntu 12.04.</p>
0
1,623
Remove .php from urls with htaccess
<p>EDIT: current .htaccess file:</p> <pre><code>Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / ## hide .php extension snippet # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L] # To internally forward /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^(.*?)/?$ $1.php [L] </code></pre> <p>My site is hosted in a subfolder of a domain connected to a large hosting account.</p> <pre><code>basesite /iioengine /forums /.htaccess //file works /.... //other MyBB content /demos.php /index.php //iioengine.com (homepage) /.htaccess //file doesn't work /... //other iioengine php pages </code></pre> <p>Is the issue that I'm using two different htaccess files?</p> <p>Here is a link that needs to work: <a href="http://iioengine.com/demos" rel="nofollow noreferrer">http://iioengine.com/demos</a></p> <p>I noticed that this current htaccess file disrupts all of the forums URL's as well</p> <p>This no longer works: <a href="http://iioengine.com/forums/Forum-Box2D" rel="nofollow noreferrer">http://iioengine.com/forums/Forum-Box2D</a></p> <p>EDIT: Thanks for reopening, I have made some progress. Here is my current htaccess file:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d &lt;/IfModule&gt; </code></pre> <p>I still get 404 pages, but if I put this line in:</p> <p><code>RewriteRule . /index.php [L]</code></p> <p>all non-'.php' requests get forwarded to the homepage... So mod_rewrite is definitely enabled, it's just not working right. Anyone know what the issue could be? </p> <p><strong>EDIT</strong>: This is <strong>not a duplicate</strong> - none of the other solutions work for me. My question is not <em>do solutions exist</em>, its <em>why aren't they working for me</em>. No one has been able to resolve this, I have been trying many solutions myself. Isn't the point of this forum to get solutions to specific issues?</p> <p>Allow me to clarify...</p> <p>I have MyBB running in a subfolder and its rewrites work fine. This link, for instance, works: <a href="http://iioengine.com/forums/Forum-Box2D" rel="nofollow noreferrer">http://iioengine.com/forums/Forum-Box2D</a></p> <p>All the php pages that are not part of MyBB still have the .php extension in their URLs - I am trying to remove these but nothing is working. Example: <a href="http://iioengine.com/demos" rel="nofollow noreferrer">http://iioengine.com/demos</a></p> <p>... [original post]</p> <p>There is obviously a lot of information out there about this, but I have tried almost a dozen different solutions and have not gotten past a 404 page.</p> <p>Here is my site: <a href="http://iioengine.com/" rel="nofollow noreferrer">http://iioengine.com/</a>, all pages are php, and everything other than the homepage and all of the forums pages have a '.php' at the end of their URL that I would like to remove.</p> <p>In addition to redirecting non-'.php' requests to the correct pages, I would also like to remove the '.php' part even when it is part of the request (because all of my content already specifies '.php' in its hyperlinks).</p> <p>This is what I have so far, mostly taken from <a href="https://stackoverflow.com/questions/9821222/remove-php-extension-explicitly-written-for-friendly-url">this post</a>, but it doesn't work, I get a 404 page.</p> <pre><code>RewriteEngine on RewriteBase / RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f RewriteRule ^(.*)$ $1.php [L,QSA] RewriteCond %{REQUEST_URI} ^/(.*).php$ RewriteRule ^(.*)$ %1 [L,QSA] </code></pre> <p>what do I need in my htaccess file to remove the file extension from the URL in all cases? Thanks</p>
0
1,377
Type Syntax error on token(s), misplaced construct(s)
<pre><code>package list; public class LinkedList implements List { //Datenfeld private Element item; //Zeigerfeld private LinkedList next; //Konstruktor, erzeugt leere Liste public LinkedList() { item = null; next = null; } //Selektoren public Object getItem() { return item; } public LinkedList next() { return next; } //ist die Liste leer? public boolean isEmpty() { return next == null; } public Object firstElement() { if (isEmpty()) return null; else return next.item; } public int length() { if (isEmpty()) return 0; else return 1 + next.length(); } //fügt x am Kopf ein public LinkedList insert(Element x) { LinkedList l = new LinkedList(); l.item = x; l.next = next; next = l; return this; } //hängt das x ans Ende der Liste und liefert Teilliste public LinkedList append (Element x) { if (isEmpty()) return insert(x); else return next.append(x); } //liefert Null, falls x nicht in Liste //sonst Teilliste private LinkedList find(Element x) { if (isEmpty()) return null; else if (firstElement().equals(x)) return this; else return next.find(x); } //entfertn erstes x der Liste public LinkedList delete(Element x) { LinkedList l = find(x); if (l != null) return l.next = l.next.next; else return this; } //entfernt das erste Element der Liste public LinkedList delete() { if (!isEmpty()) next = next.next; return this; } public boolean isInList(Element x) { return(find(x) != null); } public String toString() { return (next == null ? " |--" : " --&gt; " + next.item + next); } static void println(Element x) { System.out.println(x.toString()); } public LinkedList add(Element x, int n) { return null; } public LinkedList remove(int n) { return null; } public Element get(int n) { return null; } public int firstIndexOf(Element x) { return 1; } public int lastIndexOf(Element x) { return 1; } LinkedList l1 = new LinkedList(); l1.insert("AA"); } </code></pre> <p>In the last line <code>(l1.insert("AA");</code> I get the error</p> <pre><code>Type Syntax error on token(s), misplaced construct(s). </code></pre> <p>Need help. Can't find the problem.</p>
0
1,299
How to Quickly Remove Items From a List
<p>I am looking for a way to quickly remove items from a C# <code>List&lt;T&gt;</code>. The documentation states that the <code>List.Remove()</code> and <code>List.RemoveAt()</code> operations are both <code>O(n)</code></p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/cd666k3e.aspx" rel="noreferrer">List.Remove</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/5cw9x18z%28v=vs.80%29.aspx" rel="noreferrer">List.RemoveAt</a></li> </ul> <p>This is severely affecting my application.</p> <p>I wrote a few different remove methods and tested them all on a <code>List&lt;String&gt;</code> with 500,000 items. The test cases are shown below...</p> <hr> <p><strong>Overview</strong></p> <p>I wrote a method that would generate a list of strings that simply contains string representations of each number ("1", "2", "3", ...). I then attempted to <code>remove</code> every 5th item in the list. Here is the method used to generate the list:</p> <pre><code>private List&lt;String&gt; GetList(int size) { List&lt;String&gt; myList = new List&lt;String&gt;(); for (int i = 0; i &lt; size; i++) myList.Add(i.ToString()); return myList; } </code></pre> <p><strong>Test 1: RemoveAt()</strong></p> <p>Here is the test I used to test the <code>RemoveAt()</code> method.</p> <pre><code>private void RemoveTest1(ref List&lt;String&gt; list) { for (int i = 0; i &lt; list.Count; i++) if (i % 5 == 0) list.RemoveAt(i); } </code></pre> <p><strong>Test 2: Remove()</strong></p> <p>Here is the test I used to test the <code>Remove()</code> method.</p> <pre><code>private void RemoveTest2(ref List&lt;String&gt; list) { List&lt;int&gt; itemsToRemove = new List&lt;int&gt;(); for (int i = 0; i &lt; list.Count; i++) if (i % 5 == 0) list.Remove(list[i]); } </code></pre> <p><strong>Test 3: Set to null, sort, then RemoveRange</strong></p> <p>In this test, I looped through the list one time and set the to-be-removed items to <code>null</code>. Then, I sorted the list (so null would be at the top), and removed all the items at the top that were set to null. NOTE: This reordered my list, so I may have to go put it back in the correct order.</p> <pre><code>private void RemoveTest3(ref List&lt;String&gt; list) { int numToRemove = 0; for (int i = 0; i &lt; list.Count; i++) { if (i % 5 == 0) { list[i] = null; numToRemove++; } } list.Sort(); list.RemoveRange(0, numToRemove); // Now they're out of order... } </code></pre> <p><strong>Test 4: Create a new list, and add all of the "good" values to the new list</strong></p> <p>In this test, I created a new list, and added all of my keep-items to the new list. Then, I put all of these items into the original list.</p> <pre><code>private void RemoveTest4(ref List&lt;String&gt; list) { List&lt;String&gt; newList = new List&lt;String&gt;(); for (int i = 0; i &lt; list.Count; i++) { if (i % 5 == 0) continue; else newList.Add(list[i]); } list.RemoveRange(0, list.Count); list.AddRange(newList); } </code></pre> <p><strong>Test 5: Set to null and then FindAll()</strong></p> <p>In this test, I set all the to-be-deleted items to <code>null</code>, then used the <code>FindAll()</code> feature to find all the items that are not <code>null</code></p> <pre><code>private void RemoveTest5(ref List&lt;String&gt; list) { for (int i = 0; i &lt; list.Count; i++) if (i % 5 == 0) list[i] = null; list = list.FindAll(x =&gt; x != null); } </code></pre> <p><strong>Test 6: Set to null and then RemoveAll()</strong></p> <p>In this test, I set all the to-be-deleted items to <code>null</code>, then used the <code>RemoveAll()</code> feature to remove all the items that are not <code>null</code></p> <pre><code>private void RemoveTest6(ref List&lt;String&gt; list) { for (int i = 0; i &lt; list.Count; i++) if (i % 5 == 0) list[i] = null; list.RemoveAll(x =&gt; x == null); } </code></pre> <hr> <p><strong>Client Application and Outputs</strong></p> <pre><code>int numItems = 500000; Stopwatch watch = new Stopwatch(); // List 1... watch.Start(); List&lt;String&gt; list1 = GetList(numItems); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); watch.Reset(); watch.Start(); RemoveTest1(ref list1); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.WriteLine(); // List 2... watch.Start(); List&lt;String&gt; list2 = GetList(numItems); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); watch.Reset(); watch.Start(); RemoveTest2(ref list2); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.WriteLine(); // List 3... watch.Reset(); watch.Start(); List&lt;String&gt; list3 = GetList(numItems); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); watch.Reset(); watch.Start(); RemoveTest3(ref list3); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.WriteLine(); // List 4... watch.Reset(); watch.Start(); List&lt;String&gt; list4 = GetList(numItems); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); watch.Reset(); watch.Start(); RemoveTest4(ref list4); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.WriteLine(); // List 5... watch.Reset(); watch.Start(); List&lt;String&gt; list5 = GetList(numItems); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); watch.Reset(); watch.Start(); RemoveTest5(ref list5); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.WriteLine(); // List 6... watch.Reset(); watch.Start(); List&lt;String&gt; list6 = GetList(numItems); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); watch.Reset(); watch.Start(); RemoveTest6(ref list6); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.WriteLine(); </code></pre> <p><strong>Results</strong></p> <pre><code>00:00:00.1433089 // Create list 00:00:32.8031420 // RemoveAt() 00:00:32.9612512 // Forgot to reset stopwatch :( 00:04:40.3633045 // Remove() 00:00:00.2405003 // Create list 00:00:01.1054731 // Null, Sort(), RemoveRange() 00:00:00.1796988 // Create list 00:00:00.0166984 // Add good values to new list 00:00:00.2115022 // Create list 00:00:00.0194616 // FindAll() 00:00:00.3064646 // Create list 00:00:00.0167236 // RemoveAll() </code></pre> <p><strong>Notes And Comments</strong></p> <ul> <li><p>The first two tests do not actually remove every 5th item from the list, because the list is being reordered after each remove. In fact, out of 500,000 items, only 83,334 were removed (should have been 100,000). I am okay with this - clearly the Remove()/RemoveAt() methods are not a good idea anyway.</p></li> <li><p>Although I tried to remove the 5th item from the list, in <em>reality</em> there will not be such a pattern. Entries to be removed will be random.</p></li> <li><p>Although I used a <code>List&lt;String&gt;</code> in this example, that will not always be the case. It could be a <code>List&lt;Anything&gt;</code></p></li> <li><p>Not putting the items in the list to begin with is <strong>not</strong> an option.</p></li> <li><p>The other methods (3 - 6) all performed much better, <em>comparatively</em>, however I am a little concerned -- In 3, 5, and 6 I was forced to set a value to <code>null</code>, and then remove all the items according to this sentinel. I don't like that approach because I can envision a scenario where one of the items in the list might be <code>null</code> and it would get removed unintentionally.</p></li> </ul> <p>My question is: What is the best way to quickly remove many items from a <code>List&lt;T&gt;</code>? Most of the approaches I've tried look really ugly, and potentially dangerous, to me. Is a <code>List</code> the wrong data structure?</p> <p>Right now, I am leaning towards creating a new list and adding the good items to the new list, but it seems like there should be a better way.</p>
0
2,969
CoreData and SwiftUI: Context in environment is not connected to a persistent store coordinator
<p>I am trying to teach myself Core Data by building a homework managing app. My code builds fine and the app runs okay until I try to add a new assignment to the list. I get this error <code>Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1c25719e8)</code> on the following line: <code>ForEach(courses, id: \.self) { course in</code>. The console also has this error: <code>Context in environment is not connected to a persistent store coordinator: &lt;NSManagedObjectContext: 0x2823cb3a0&gt;</code>.</p> <p>I know very little about Core Data and am at a loss as to what the issue might be. I have set up "Assignment" and "Course" entities in the data model, where Course has a one-to-many relationship to Assignment. Each assignment will be categorized under a particular course.</p> <p>This is the code for the view that adds a new assignment to the list:</p> <pre><code> struct NewAssignmentView: View { @Environment(\.presentationMode) var presentationMode @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Course.entity(), sortDescriptors: []) var courses: FetchedResults&lt;Course&gt; @State var name = "" @State var hasDueDate = false @State var dueDate = Date() @State var course = Course() var body: some View { NavigationView { Form { TextField("Assignment Name", text: $name) Section { Picker("Course", selection: $course) { ForEach(courses, id: \.self) { course in Text("\(course.name ?? "")").foregroundColor(course.color) } } } Section { Toggle(isOn: $hasDueDate.animation()) { Text("Due Date") } if hasDueDate { DatePicker(selection: $dueDate, displayedComponents: .date, label: { Text("Set Date:") }) } } } .navigationBarTitle("New Assignment", displayMode: .inline) .navigationBarItems(leading: Button(action: { self.presentationMode.wrappedValue.dismiss() }, label: { Text("Cancel") }), trailing: Button(action: { let newAssignment = Assignment(context: self.moc) newAssignment.name = self.name newAssignment.hasDueDate = self.hasDueDate newAssignment.dueDate = self.dueDate newAssignment.statusString = Status.incomplete.rawValue newAssignment.course = self.course self.presentationMode.wrappedValue.dismiss() }, label: { Text("Add").bold() })) } } } </code></pre> <p>EDIT: Here is the code in AppDelegate that sets up the persistent container:</p> <pre><code>lazy var persistentContainer: NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "test") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() </code></pre> <p>And the code in SceneDelegate that sets up the environment:</p> <pre><code> func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Get the managed object context from the shared persistent container. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, context) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } </code></pre>
0
1,978
Delphi Queue and Synchronize
<p>I am reading Nick Hodges online and I have discovered the Queue but it is not behaving as I've expected and I couldn't understand what him and the documentation say. Look at this code:</p> <pre><code> TThread.CreateAnonymousThread( procedure begin TThread.Queue(TThread.Current, procedure begin Memo1.Lines.Clear; Memo1.Lines.Add('start'); end); Sleep(2000); TThread.Synchronize(TThread.Current, procedure begin Memo1.Lines.Add('end'); end); end ).Start; </code></pre> <p>I always use <code>Synchronize</code> but this time I have tried with <code>Queue</code> because according to Nick it is better in case of multiple requests since they won't be "serialized" and executed one by one. The code above works fine. Why this is not working instead?</p> <pre><code> TThread.CreateAnonymousThread( procedure begin TThread.Queue(TThread.Current, procedure begin Memo1.Lines.Clear; Memo1.Lines.Add('start'); end); Sleep(2000); TThread.Queue(TThread.Current, procedure begin Memo1.Lines.Add('end'); end); end ).Start; </code></pre> <p>In this case the Memo outputs the <code>start</code> but not the end. When I call:</p> <ul> <li>Synchronize on the first and Synchronize on the second it works</li> <li>Queue on the first and Synchronize on the second it works</li> <li>Queue both times it's not working because I see only the <code>start</code> in the memo</li> </ul>
0
1,062
WPF Template Binding in ToggleButton UserControl
<p>I'm developing a basic dip-switch user control as a personal learning exercise. Originally I had it set up where you could declare some custom color properties on the user control, and they would be used on elements inside the control.</p> <p>However, I recenly discovered ToggleButtons, and rebuilt my control to take advantage of them. Since then, my custom color properties (SwitchColor and SwitchBkgndColor) no longer work properly. They are always rendered with the default colors, not the colors I specified when I place them in my Window. Here's some code:</p> <pre><code> &lt;UserControl x:Class="DipSwitchToggleBtn" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:SwitchesApp" Width="20" Height="40"&gt; &lt;ToggleButton Name="ToggleBtn" IsThreeState="False"&gt; &lt;ToggleButton.Template&gt; &lt;ControlTemplate&gt; &lt;Canvas Name="SwitchBkgnd" Background="{TemplateBinding app:DipSwitchToggleBtn.SwitchBkgndColor}" &gt; &lt;Rectangle Name="SwitchBlock" Fill="{TemplateBinding app:DipSwitchToggleBtn.SwitchColor}" Width="16" Height="16" Canvas.Top="22" Canvas.Left="2" /&gt; &lt;/Canvas&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="ToggleButton.IsChecked" Value="True"&gt; &lt;Trigger.EnterActions&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="SwitchBlock" Duration="00:00:00.05" Storyboard.TargetProperty="(Canvas.Top)" To="2" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/Trigger.EnterActions&gt; &lt;Trigger.ExitActions&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="SwitchBlock" Duration="00:00:00.05" Storyboard.TargetProperty="(Canvas.Top)" To="22" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/Trigger.ExitActions&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/ToggleButton.Template&gt; &lt;/ToggleButton&gt; &lt;/UserControl&gt; </code></pre> <p>...and the code behind:</p> <pre><code>Partial Public Class DipSwitchToggleBtn Public Property State() As Boolean Get Return Me.ToggleBtn.IsChecked End Get Set(ByVal value As Boolean) Me.ToggleBtn.IsChecked = value End Set End Property Public Sub Toggle() Me.State = Not Me.State End Sub #Region " Visual Properties " Public Shared ReadOnly SwitchColorProperty As DependencyProperty = _ DependencyProperty.Register("SwitchColor", _ GetType(Brush), GetType(DipSwitchToggleBtn), _ New FrameworkPropertyMetadata(Brushes.LightGray)) Public Property SwitchColor() As Brush Get Return GetValue(SwitchColorProperty) End Get Set(ByVal value As Brush) SetValue(SwitchColorProperty, value) End Set End Property Public Shared ReadOnly SwitchBkgndColorProperty As DependencyProperty = _ DependencyProperty.Register("SwitchBkgndColor", _ GetType(Brush), GetType(DipSwitchToggleBtn), _ New FrameworkPropertyMetadata(Brushes.Gray)) Public Property SwitchBkgndColor() As Brush Get Return GetValue(SwitchBkgndColorProperty) End Get Set(ByVal value As Brush) SetValue(SwitchBkgndColorProperty, value) End Set End Property #End Region End Class </code></pre> <p>The default Gray and LightGray show up in the VS2008 designer and the compiled app, but when I do something like this in my window:</p> <pre><code>&lt;app:DipSwitchToggleBtn x:Name="DipSwitchTest" SwitchColor="#0000FF" SwitchBkgndColor="#000000" /&gt; </code></pre> <p>The colors I specified for this instance do not get used. Everything compiles without error, but my control is still displayed with the default colors.</p> <p>I believe there is some new hierarchy at play since I nested my items in the ToggleButton.</p> <p>Any help would be appreciated. Thank you.</p>
0
2,641
php mysql compare long and lat, return ones under 10 miles
<p>Hay i want to find the distance (in miles) between 2 locations using lat and long values, and check if they are within a 10 mile radius of each other.</p> <p>When a user logs in, their lat/long values are saved in a session</p> <pre><code>$_SESSION['lat'] $_SESSION['long'] </code></pre> <p>I have 2 functions</p> <p>This one works out the distance in miles and returns a rounded value</p> <pre><code>function distance($lat1, $lng1, $lat2, $lng2){ $pi80 = M_PI / 180; $lat1 *= $pi80; $lng1 *= $pi80; $lat2 *= $pi80; $lng2 *= $pi80; $r = 6372.797; // mean radius of Earth in km $dlat = $lat2 - $lat1; $dlng = $lng2 - $lng1; $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); $km = $r * $c; return floor($km * 0.621371192); } </code></pre> <p>This one returns a bool if the distance between the 2 sets of lat and long's is under 10.</p> <pre><code>function is_within_10_miles($lat1, $lng1, $lat2, $lng2){ $d = distance($lat1, $lng1, $lat2, $lng2); if( $d &lt;= 10 ){ return True; }else{ return False; } } </code></pre> <p>Both functions work as expected, if i give 2 sets of lat/longs and the distance between them is say 20 miles, my is_within_10_miles() function returns false.</p> <p>Now, I have a database of 'locations' (4 fields - ID, name, lat, long).</p> <p>I want to find all locations that are within a 10 mile radius.</p> <p>Any ideas?</p> <p><strong>EDIT: I can loop through ALL the and perform the is_within_10_miles() on them like this</strong></p> <pre><code>$query = "SELECT * FROM `locations`"; $result = mysql_query($query); while($location = mysql_fetch_assoc($result)){ echo $location['name']." is "; echo distance($lat2, $lon2, $location['lat'], $location['lon']); echo " miles form your house, is it with a 10 mile radius? "; if( is_within_10_miles($lat2, $lon2, $location['lat'], $location['lon']) ){ echo "yeah"; }else{ echo "no"; } echo "&lt;br&gt;"; </code></pre> <p>}</p> <p>A sample result would be</p> <pre><code>goodison park is 7 miles form your house, is it with a 10 mile radius? yeah </code></pre> <p>I need to somehow perform the is_within_10_miles function within my query.</p> <p>EDIT EDIT</p> <p>This legend from <a href="http://www.zcentric.com/blog/2007/03/calculate_distance_in_mysql_wi.html" rel="noreferrer">http://www.zcentric.com/blog/2007/03/calculate_distance_in_mysql_wi.html</a> came up with this...</p> <pre><code>SELECT ((ACOS(SIN($lat * PI() / 180) * SIN(lat * PI() / 180) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * COS(($lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM members HAVING distance&lt;='10' ORDER BY distance ASC </code></pre> <p>It actually works. Problem is that i want to select * rows, rather than selecting them one by one. How do i do that?</p>
0
1,181
JQGrid - SetRowData - Returns success but no data updated
<p>I am trying to add/edit data into my JQGrid. Currently the first column is populated and then the other six are blank and are dependent upon the first column. So I need to <strong>add or "edit the blank" the data in the other six columns while the first remains the same.</strong> </p> <p>Right now I am just trying to get access into the JQGrid to edit my current data. The function below is what I have setup so far. It gets passed the time (the first columns data), the number of ohms (data to enter the grid), and the column name. It builds my data set and then tries to add it to rowid 0. This is hardcoded just because I'm trying to get it to work right now. Then I access the JQGrid, add the rowdata and it actually returns a success, but nothing has been added to the JQGrid.</p> <p>*note - this is all done within my javascript file</p> <pre><code>function AddRow(elapsedTime, numMOhms, mColumn) { switch(mColumn) { case 'a': case 'A': dataToAdd = [{TestTime:elapsedTime,RdgA:numMOhms,CorrA:"",RdgB:"",CorrB:"",RdgC:"",CorrC:""}]; break; case 'b': case 'B': dataToAdd = [{TestTime:elapsedTime,RdgA:"",CorrA:"",RdgB:numMOhms,CorrB:"",RdgC:"",CorrC:""}]; break; case 'c': case 'C': dataToAdd = [{TestTime:elapsedTime,RdgA:"",CorrA:"",RdgB:"",CorrB:"",RdgC:numMOhms,CorrC:""}]; break; } alert(JSON.stringify(dataToAdd)); var success = jQuery("#polarizationTable").jqGrid('setRowData',0,dataToAdd[0]); if(success) { alert("y"); } DrawGraph(true); } </code></pre> <p>if you replace the last bit with this:</p> <pre><code>for(var i=0;i&lt;=dataToAdd.length;i++) jQuery("#polarizationTable").jqGrid('addRowData',i+1,dataToAdd[i]); </code></pre> <p>I can get it to add, but it is a dumb add and just appends that data to the end instead of updating data in that row. I tried modifying it with hardcode and removing the for loop, and no luck.</p> <p>Here is what my colModel/colNames looks like.</p> <pre><code>colNames:['Minutes','Reading A', 'Corr A', 'Reading B','Corr B','Reading C','Corr C'], colModel:[ {name:'TestTime',index:'TestTime', align:"center", sortable:false}, {name:'RdgA',index:'RdgA', align:"center", sortable:false}, {name:'CorrA',index:'CorrA', align:"center", sortable:false}, {name:'RdgB',index:'RdgB', align:"center", sortable:false}, {name:'CorrB',index:'CorrB', align:"center", sortable:false}, {name:'RdgC',index:'RdgC', align:"center", sortable:false}, {name:'CorrC',index:'CorrC', align:"center", sortable:false} ], </code></pre>
0
1,089
Needing a working example on how to use QThreadPool
<p>I want to use multiThreading webkit with <code>QThreadPool</code></p> <p>My code is:</p> <p><strong>webkitrunnable.cpp:</strong></p> <pre><code>webkitRunnable::webkitRunnable(QUrl inputURL) : url(inputURL) { init(); } void webkitRunnable::run() { qDebug() &lt;&lt; "run ..."; qDebug() &lt;&lt; "webkit runnable --&gt; " &lt;&lt; url; loadPage(url); } void webkitRunnable::init() { qDebug() &lt;&lt; "WebKit--&gt; init webkit"; webView = new QWebView; connect(webView, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool))); manager = new QNetworkAccessManager(this); manager = webView-&gt;page()-&gt;networkAccessManager(); webView-&gt;page()-&gt;setNetworkAccessManager(manager); connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*))); } void webkitRunnable::finishLoading(bool) { qDebug() &lt;&lt; "WebKit--&gt; finish loading"; } void webkitRunnable::replyFinished(QNetworkReply* Reply) { qDebug() &lt;&lt; "WebKit--&gt; reply Finished"; } void webkitRunnable::loadPage(QUrl url) { qDebug() &lt;&lt; "WebKit--&gt; load Page"; webView-&gt;load(url); webView-&gt;setFocus(); } </code></pre> <p><strong>webkitrunnable.h:</strong></p> <pre><code>class webkitRunnable : public QObject, public QRunnable { Q_OBJECT public: webkitRunnable(QUrl inputURL); void loadPage(QUrl url); protected: void run(); signals: public slots: void finishLoading(bool); void replyFinished(QNetworkReply*); private: void init(); QUrl url; QNetworkAccessManager *manager; QWebView *webView; }; </code></pre> <p><strong>mythread.cpp:</strong></p> <pre><code>MyThread::MyThread(QObject *parent) : QObject(parent) { threadPool = new QThreadPool(this); threadPool-&gt;setMaxThreadCount(20); webkit = new webkitRunnable(QUrl("http://www.google.com/")); } MyThread::~MyThread() { delete threadPool; } void MyThread::startMultiThreadLoad(QUrl url) { webkit = new webkitRunnable(url); connect(webkit, SIGNAL(threadFinished(int)), this, SLOT(finished(int)), Qt::QueuedConnection); for (int i = 0; i &lt; threadPool-&gt;maxThreadCount(); i++) { threadPool-&gt;start(webkit); qDebug() &lt;&lt; "start(active):" &lt;&lt; threadPool-&gt;activeThreadCount(); } } void MyThread::finished(int number) { qDebug() &lt;&lt; "thread number is: " &lt;&lt; number; qDebug() &lt;&lt; "finished(active):" &lt;&lt; threadPool-&gt;activeThreadCount(); } </code></pre> <p>mythread.h:</p> <pre><code>class MyThread : public QObject { Q_OBJECT public: explicit MyThread(QObject *parent = 0); ~MyThread(); void startMultiThreadLoad(QUrl url); public slots: void finished(int); private: webkitRunnable* webkit; QUrl globalURL; QThreadPool *threadPool; }; </code></pre> <p>Whenever <code>webkit-&gt;load()</code> is executed, I got the following Application Output in Qt Creator:</p> <pre><code>QObject: Cannot create children for a parent that is in a different thread. (Parent is QNetworkAccessManager(0x6f1598), parent's thread is QThread(0x65dfd0), current thread is QThread(0x6ccd28) </code></pre> <p>How can I solve it? Can anyone give an example? Thanks</p>
0
1,380
possible ways to store JSON in dynamodb
<p>I am working on an implementation where my system will be integrated with an external application. This external application generates long and different json for every request.</p> <p>I want to store this json in dynamodb, what would be the best approach to do that? Currently, I have created a POJO class with below property. In this definition property, I set the API response json as string.</p> <pre><code>@DynamoDBAttribute(attributeName = "definition") private String definition; </code></pre> <p>Then create object of POJO, and save it to dynamodb using <code>this.dynamoDBMapper.save(obj);</code> </p> <p>Questions:</p> <p>1 - Is this a good approach to store JSON in dynamodb as string?</p> <p>2 - What if I want to search by any property of this json in dynamodb?</p> <p>3 - Is there a better way to store this json so it can be searchable also?</p> <p>Also, this json is always different so I can't map it to POJO class, that's why I am trying to store it as a string.</p> <p>Below is my sample POJO object that I am storing in dynamo db.</p> <pre><code>@DynamoDBTable(tableName = "job") public class Job { @DynamoDBHashKey(attributeName = "inbound_job") private Long inboundId; @DynamoDBAttribute(attributeName = "outbound_job") private Long outboundId; @DynamoDBAttribute(attributeName = "definition") private String definition; } </code></pre> <p>Below is respective json stored in dynamodb.</p> <pre><code>{ "inbound_job": { "N": "3138788" }, "outbound_id": { "N": "909092" }, "jobDefinition": { "S": "{\r\n\t\"_id\": \"5ae1d9848376948a370d6962\",\r\n\t\"index\": 4,\r\n\t\"guid\": \"32bb8da0-a84a-4b3c-8775-c20216fa04b7\",\r\n\t\"isActive\": true,\r\n\t\"balance\": \"$2,683.96\",\r\n\t\"picture\": \"http:\/\/placehold.it\/32x32\",\r\n\t\"age\": 38,\r\n\t\"eyeColor\": \"brown\",\r\n\t\"name\": \"Swanson Hughes\",\r\n\t\"gender\": \"male\",\r\n\t\"company\": \"BIOSPAN\",\r\n\t\"email\": \"swansonhughes@biospan.com\",\r\n\t\"phone\": \"+1 (999) 559-2315\",\r\n\t\"address\": \"851 Lyme Avenue, Shepardsville, American Samoa, 8015\",\r\n\t\"about\": \"Sit officia culpa in est Lorem. Officia occaecat nostrud Lorem officia non sint enim excepteur. Laboris dolore consectetur velit occaecat ullamco non nisi.\\r\\n\",\r\n\t\"registered\": \"2015-12-12T11:22:53 +08:00\",\r\n\t\"latitude\": 47.732205,\r\n\t\"longitude\": -164.823761,\r\n\t\"tags\": [\r\n\t\t\"velit\",\r\n\t\t\"anim\",\r\n\t\t\"id\",\r\n\t\t\"tempor\",\r\n\t\t\"et\",\r\n\t\t\"eu\",\r\n\t\t\"amet\"\r\n\t],\r\n\t\"friends\": [{\r\n\t\t\t\"id\": 0,\r\n\t\t\t\"name\": \"Kaye Fields\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"id\": 1,\r\n\t\t\t\"name\": \"Knapp Reed\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"id\": 2,\r\n\t\t\t\"name\": \"Hodge Morse\"\r\n\t\t}\r\n\t],\r\n\t\"greeting\": \"Hello, Swanson Hughes! You have 3 unread messages.\",\r\n\t\"favoriteFruit\": \"strawberry\"\r\n}" } } </code></pre> <p>I also want to search by any json property of "definition" attribute.</p> <p>Let me know your thoughts.</p> <p>Regards.</p>
0
1,289
Elasticsearch Parse Exception error when attempting to index PDF
<p>I'm just getting started with elasticsearch. Our requirement has us needing to index thousands of PDF files and I'm having a hard time getting just ONE of them to index successfully.</p> <p>Installed the Attachment Type plugin and got response: <code>Installed mapper-attachments</code>.</p> <p>Followed the <a href="http://www.elasticsearch.org/tutorials/2011/07/18/attachment-type-in-action.html" rel="noreferrer">Attachment Type in Action tutorial</a> but the process hangs and <strong>I don't know how to interpret the error message</strong>. Also tried the <a href="https://gist.github.com/1075067" rel="noreferrer">gist</a> which hangs in the same place.</p> <pre><code>$ curl -X POST "localhost:9200/test/attachment/" -d json.file {"error":"ElasticSearchParseException[Failed to derive xcontent from (offset=0, length=9): [106, 115, 111, 110, 46, 102, 105, 108, 101]]","status":400} </code></pre> <p>More details:</p> <p>The <code>json.file</code> contains an embedded Base64 PDF file (as per instructions). The first line of the file <em>appears</em> correct (to me anyway): <code>{"file":"JVBERi0xLjQNJeLjz9MNCjE1OCAwIG9iaiA8</code>...</p> <p>I'm not sure if maybe the <code>json.file</code> is invalid or if maybe elasticsearch just isn't set up to parse PDFs properly?!?</p> <p><strong>Encoding</strong> - Here's how we're encoding the PDF into <code>json.file</code> (as per tutorial):</p> <pre><code>coded=`cat fn6742.pdf | perl -MMIME::Base64 -ne 'print encode_base64($_)'` json="{\"file\":\"${coded}\"}" echo "$json" &gt; json.file </code></pre> <p>also tried:</p> <pre><code>coded=`openssl base64 -in fn6742.pdf </code></pre> <p>log: </p> <pre><code>[2012-06-07 12:32:16,742][DEBUG][action.index ] [Bailey, Paul] [test][0], node[AHLHFKBWSsuPnTIRVhNcuw], [P], s[STARTED]: Failed to execute [index {[test][attachment][DauMB-vtTIaYGyKD4P8Y_w], source[json.file]}] org.elasticsearch.ElasticSearchParseException: Failed to derive xcontent from (offset=0, length=9): [106, 115, 111, 110, 46, 102, 105, 108, 101] at org.elasticsearch.common.xcontent.XContentFactory.xContent(XContentFactory.java:147) at org.elasticsearch.common.xcontent.XContentHelper.createParser(XContentHelper.java:50) at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:451) at org.elasticsearch.index.mapper.DocumentMapper.parse(DocumentMapper.java:437) at org.elasticsearch.index.shard.service.InternalIndexShard.prepareCreate(InternalIndexShard.java:290) at org.elasticsearch.action.index.TransportIndexAction.shardOperationOnPrimary(TransportIndexAction.java:210) at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction.performOnPrimary(TransportShardReplicationOperationAction.java:532) at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction$1.run(TransportShardReplicationOperationAction.java:430) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) </code></pre> <p>Hoping someone can help me see what I'm missing or did wrong? </p>
0
1,155
How do I fill white background while resize image
<p>Current background is black. How to change the color to be white?</p> <p> <pre><code> #assuming the mime type is correct switch ($imgtype) { case 'image/jpeg': $source = imagecreatefromjpeg($source_image); break; case 'image/gif': $source = imagecreatefromgif($source_image); break; case 'image/png': $source = imagecreatefrompng($source_image); break; default: die('Invalid image type.'); } #Figure out the dimensions of the image and the dimensions of the desired thumbnail $src_w = imagesx($source); $src_h = imagesy($source); #Do some math to figure out which way we'll need to crop the image #to get it proportional to the new size, then crop or adjust as needed $width = $info[0]; $height = $info[1]; $x_ratio = $tn_w / $src_w; $y_ratio = $tn_h / $src_h; if (($x_ratio * $height) &lt; $tn_w) { $new_h = ceil($x_ratio * $height); $new_w = $tn_w; } else { $new_w = ceil($y_ratio * $width); $new_h = $tn_h; } $x_mid = $new_w / 2; $y_mid = $new_h / 2; $newpic = imagecreatetruecolor(round($new_w), round($new_h)); imagecopyresampled($newpic, $source, 0, 0, 0, 0, $new_w, $new_h, $src_w, $src_h); $final = imagecreatetruecolor($tn_w, $tn_h); imagecopyresampled($final, $newpic, 0, 0, ($x_mid - ($tn_w / 2)), ($y_mid - ($tn_h / 2)), $tn_w, $tn_h, $tn_w, $tn_h); #if we need to add a watermark if ($wmsource) { #find out what type of image the watermark is $info = getimagesize($wmsource); $imgtype = image_type_to_mime_type($info[2]); #assuming the mime type is correct switch ($imgtype) { case 'image/jpeg': $watermark = imagecreatefromjpeg($wmsource); break; case 'image/gif': $watermark = imagecreatefromgif($wmsource); break; case 'image/png': $watermark = imagecreatefrompng($wmsource); break; default: die('Invalid watermark type.'); } #if we're adding a watermark, figure out the size of the watermark #and then place the watermark image on the bottom right of the image $wm_w = imagesx($watermark); $wm_h = imagesy($watermark); imagecopy($final, $watermark, $tn_w - $wm_w, $tn_h - $wm_h, 0, 0, $tn_w, $tn_h); } if (imagejpeg($final, $destination, $quality)) { return true; } return false; } </code></pre> <p>Black &amp; White </p> <p><img src="https://i.stack.imgur.com/AjIFv.jpg" alt="alt text"></p>
0
1,337
Get nested dict items using Jinja2 in Flask
<p>for this dictionary with this Flask controller</p> <pre><code>projects = { 'life-calc':{'url':'life-calc', 'title': 'Life Calculator'}, 'text-game':{'url':'text-game', 'title':'Text Adventure'}, 'fill-it-up':{'url':'fill-it-up', 'title':'Fill It Up'}, 'rock-paper-scissors':{'url':'rock-paper-scissors', 'title':'Rock, Paper, Scissors'}, 'bubble-popper':{'url':'bubble-popper', 'title':'Bubble Popper'} } @app.route('/') def index(): return render_template("index.html", projects = projects) </code></pre> <p>and the template as such</p> <pre><code> &lt;h1&gt; List of My Projects &lt;/h1&gt; &lt;ol&gt; &lt;li&gt; &lt;a href = "life-calc"&gt;Life Calculator&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href = "text-game"&gt;Adventure Game&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href = "fill-it-up"&gt;Fill It Up&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href = "rock-paper-scissors"&gt;Rock Paper Scissors&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href = "bubble-popper"&gt;Bubble Popper&lt;/a&gt; &lt;/li&gt; &lt;/ol&gt; &lt;p&gt;test section below&lt;/p&gt; &lt;ol&gt; {% for project in projects %} &lt;li&gt;&lt;a href = "{{ project['url'] }}"&gt;{{ project['title'] }}&lt;/a&gt; &lt;/li&gt; {% endfor %} &lt;/ol&gt; {% endblock %} </code></pre> <p>How can I access the items in the dict to print a list of my projects as in the HTML above the test?</p> <p>I solved my own problem with help from <a href="https://stackoverflow.com/questions/19141073/rendering-a-python-dict-in-jinja2-werkzeug">Rendering a python dict in Jinja2 / Werkzeug</a> The template block should be </p> <pre><code>{% for key, value in projects.iteritems() %} &lt;li&gt;&lt;a href={{value['url']}}&gt;{{value['title']}}&lt;/a&gt;&lt;/li&gt; {% endfor %} </code></pre> <p>But I'm still curious as to how to access further nested dictionaries, and if this is the smartest way to create a simple menu.</p>
0
1,181
Android Location.distanceBetween and Location.distanceTo difference
<p>I encounter some issues on trying to calculate distance between one location and a list of others (in order to get the closest one). I tried by using Location.distanceBetween(...) and location.distanceTo(...), the two method are working but both of them send me different data and not any of them seems right.</p> <p>My data came from a Class ConcessionDistance which is a basic extension of HashMap containing location data (as integer convert as string) and some other stuff that we don't need here.</p> <pre><code>private ArrayList&lt;ConcessionDistance&gt; getMapsConcessionsDistancesFromPoint(ArrayList&lt;ConcessionDistance&gt; al, Location currentLocation) { Location dest; float distance1,distance2; float[] curDist = new float[1]; double lati,longi; Log.i("DBTableConcessions","getMapsConcessionsDistancesFromPoint: Generation d'une map de donnée de concession"); for(ConcessionDistance curConc : al){ //Distance by method 1 dest = new Location(LOCATION_PROVIDER); lati = new Double((new Integer(curConc.get("concession_latitude"))) /1e6); longi = new Double((new Integer(curConc.get("concession_longitude"))) /1e6); dest.setLatitude(lati); dest.setLongitude(longi); distance1 = currentLocation.distanceTo(dest); //Distance by method2 Location.distanceBetween( currentLocation.getLatitude(), currentLocation.getLongitude(), (double) ((new Integer(curConc.get("concession_latitude"))) /1000000), (double) ((new Integer(curConc.get("concession_longitude"))) /1000000), curDist); distance2 = curDist[0]; Log.i("DBTableConcessions","distance :"+distance1+" ou "+distance2);//+" ,lat :"+lati+" ,long "+longi); //+"curDist{0="+curDist[0]+",1="+curDist[1]+",2="+curDist[2]+"}" //Saving one of the distance curConc.put("distance",String.valueOf(distance1)); } return al; } </code></pre> <p>Can some one help me, to figure out where is the problem? I think of a conversion problem but I'm to deep in the problem to solve it myself :(</p> <p>Any help will be welcome. Thanks by advance.</p> <p><b>Edit</b>: Here is part of my LogCat: I send to the emulator the gps location of "Strasbourg" (those are cities from east-france) and process distance to all those cities:</p> <pre><code>06-29 06:37:37.215: INFO/DBTableConcessions(809): distance from EVRY :346254.66 ou 373061.38 06-29 06:37:37.235: INFO/DBTableConcessions(809): distance from HAGUENAU CEDEX :105491.984 ou 0.0 06-29 06:37:37.235: INFO/DBTableConcessions(809): distance from BESANCON CEDEX :110127.08 ou 134302.03 06-29 06:37:37.265: INFO/DBTableConcessions(809): distance from BREST CEDEX 9 :852829.1 ou 820181.7 06-29 06:37:37.295: INFO/DBTableConcessions(809): distance from HOENHEIM :87783.39 ou 0.0 06-29 06:37:37.326: INFO/DBTableConcessions(809): distance from COLMAR :28067.428 ou 0.0 06-29 06:37:37.355: INFO/DBTableConcessions(809): distance from BELFORT :40919.13 ou 134302.03 06-29 06:37:37.446: INFO/DBTableConcessions(809): distance from SARREBOURG :81606.31 ou 0.0 </code></pre> <p>The real distance (given by google maps) between those cities and <b>"Strasbourg"</b> are :<br/> <b>Evry</b> : 520km ( method1 : miss 175km, method2 : miss 145km)<br/> <b>Haguenau</b> : 30km ( method1: add 70km, method2: return 0)<br/> <b>Besancon</b> : 250km (method1: miss 140km, method2: miss 120km)<br/> <b>Brest</b> : 1070km (method1: miss 200km, method2: miss 230km)<br/> <b>Hoenheim</b> : 5km (method1: add 80km, method2: return 0)<br/> <b>Colmar</b> : 75km (method1: miss 50km, method2: return 0)<br/> <b>Belfort</b> : 155km (method1: miss 110km, method2: miss 20km)<br/> <b>Sarrebourg</b> : 75km (method1: miss 5km, method2: return 0)<br/></p> <p>So we can notice that the second method return 0 when real distance is below ~100km, wherease for the method1 I can't see any logic inhere :/</p>
0
1,505
Twitter Bootstrap 3 inline and horizontal form
<p>I'm trying to migrate my Bootstrap 2 form to Bootstrap 3.<br /> My current code and fiddle: <a href="http://jsfiddle.net/mavent/Z4TRx/" rel="nofollow noreferrer">http://jsfiddle.net/mavent/Z4TRx/</a></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>.navbar-sam-main .navbar-toggle{ z-index:1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Latest compiled and minified CSS --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;!-- Optional theme --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"&gt; &lt;!-- Latest compiled and minified JavaScript --&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;div class="" id="myDialog1"&gt; &lt;div class="" id="myDialog2"&gt; &lt;form role="form" class="" id="contactForm" onsubmit="send(); return false;"&gt; &lt;label&gt;Please fill the form&lt;/label&gt; &lt;br/&gt;&lt;br/&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;My Label 2&lt;/label&gt; &lt;input type="text" class="form-control" name="name" id="name" required="required" value="myName"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;My Label 3&lt;/label&gt; &lt;input type="email" class="form-control" name="email" id="email" required="required"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="message"&gt;My Label 4&lt;/label&gt; &lt;textarea class="form-control" name="message" id="message" required="required"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-primary" id="submit" style="margin-left: 40px"&gt;Send&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I want inline behaviour, my label 2 will be next to text input, my label 3 will be next to text input. I also need horizontal behaviour, my label 4 will be on top of the textarea. My label 2's and my label 3's text box will be 4 column width, my label 4's width will be full width of the form.</p> <p><img src="https://i.stack.imgur.com/gtfFM.jpg" alt="enter image description here" /></p> <p>How can I do this in Bootstrap 3 ?</p>
0
1,385
Plot legend below the graphs and legend title above the legend in ggplot2
<p>I have a dataframe <code>df</code>:</p> <pre><code>structure(list(y = c(2268.14043972082, 2147.62290922552, 2269.1387550775, 2247.31983098201, 1903.39138268307, 2174.78291538358, 2359.51909126411, 2488.39004804939, 212.851575751527, 461.398994384333, 567.150629704352, 781.775113821961, 918.303706148872, 1107.37695799186, 1160.80594193377, 1412.61328924168, 1689.48879626486, 260.737164468854, 306.72700499362, 283.410379620422, 366.813913489692, 387.570173754128, 388.602676983443, 477.858510450125, 128.198042456082, 535.519377609133, 1028.8780498564, 1098.54431357711, 1265.26965941035, 1129.58344809909, 820.922447928053, 749.343583476846, 779.678206156474, 646.575242339517, 733.953282899613, 461.156280127354, 906.813018662913, 798.186995701282, 831.365377249207, 764.519073183124, 672.076289062505, 669.879217186302, 1341.47673353751, 1401.44881976186, 1640.27575962036), P = c(1750.51986303926, 1614.11541634798, 951.847023338079, 1119.3682884872, 1112.38984390156, 1270.65773075982, 1234.72262170166, 1338.46096616983, 1198.95775346458, 1136.69287367165, 1265.46480803983, 1364.70149818063, 1112.37006707489, 1346.49240261316, 1740.56677791104, 1410.99217295647, 1693.18871380948, 901.760176040232, 763.971046562772, 994.8699095021, 972.755147593882, 1011.41669411398, 643.705302958842, 537.54384616157, 591.212003320456, 464.405641604215, 0, 0, 0, 0, 0, 246.197052353527, 265.237238116562, 1260.68540103734, 398.080919081345, 0, 374.611004248261, 527.686996757984, 765.678002953529, 661.830007851124, 484.864011824131, 612.936006393284, 672.088483441621, 625.397994920611, 785.390003710985), x = c(49, 50, 51, 52, 53, 54, 55, 56, 1, 2, 3, 4, 5, 14, 15, 16, 17, 2, 3, 4, 5, 6, 10, 11, 3, 30, 64, 66, 67, 68, 69, 34, 35, 37, 39, 2, 17, 18, 99, 100, 102, 103, 67, 70, 72), Te = c(9.10006221322572, 7.65505467142961, 8.21480062559674, 8.09251754304318, 8.466220758789, 8.48094407814006, 8.77304120569444, 8.31727518543397, 8.14410265791868, 8.80921738865237, 9.04091478341757, 9.66233618146246, 8.77015716015164, 9.46037931956657, 9.59702379240667, 10.1739258740118, 9.39524442215692, 0.616491147620629, 0.631476354027448, 0.129135682201776, 1.87297579763483, 2.53941370394744, -0.518422834982312, 1.34466852591922, 1.05118063842584, 1.79515935418336, 6.65555189859301, 6.38647333946436, 6.48427760143803, 6.33587322941382, 7.3501870975794, 3.04366850755114, 1.94656549866681, 3.61970174782833, 4.41939287295897, 9.47923019665153, 8.87480698915229, 8.06993784515111, 2.31976094801132, 2.65270969716837, 2.21586561444892, 2.66012522311856, 5.72634186318572, 4.63445162539409, 6.18505171198551 )), .Names = c("y", "P", "x", "Te"), row.names = c(NA, -45L), class = "data.frame") </code></pre> <p>I want to plot this data like I did with ggplot:</p> <pre><code>library(ggplot2) gg3 &lt;- ggplot(df) + geom_point(aes(x = x, y = y, size=P, colour=Te), alpha=0.7, inherit.aes = FALSE)+ scale_colour_gradient(low="#00FF33", high ="#FF0000")+ labs(colour="T", size="P")+ xlab("x") + ylab("y")+ # ylim(0,3000)+ scale_size(range = c(3, 8)) + theme_bw(base_size = 12, base_family = "Helvetica") + theme(panel.grid.minor = element_line(colour="grey", size=0.5)) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) print(gg3) </code></pre> <p>It is quite what I want but I would like to have the legend below the plot with an horizontal direction and the legend title on the top of the legend. I kind of managed to put the legend below the plot by adding this command line <code>theme(legend.position="bottom", legend.direction="horizontal")</code>. However, I could not really manage to achieve to put the legend title on top of the legend. Does anyone know how I could do it?</p>
0
1,812
How to render a partial view (using razor) after user click?
<p>I've been searching for a solution, but every thing I tried didn't help, although it seems very easy. I'm sure some of you will know what should I do.</p> <p>I am using ASP.NET MVC4 (razor). I have a side menu, and all I want is that another partial view will be rendered (depends on the menu item's being clicked). I have a div on my page that should contain this partial view. The command: </p> <pre><code> @Html.Partial("_TitleDescription") </code></pre> <p>works just fine, but it's statically render the partial view (on compilation time). I want it to render it dynamically with every button the user clicked in the menu.</p> <p>I tried:</p> <pre><code> @Ajax.ActionLink("Location", "Location", "Product", new { id = @Model.ID }, new AjaxOptions() { UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, HttpMethod = "GET"}) </code></pre> <p>I tried:</p> <pre><code> &lt;script type="text/javascript"&gt; function getView() { $('#detailsDiv').load("@Url.Action("Location" , "Product" )"); } &lt;/script&gt; &lt;a href='javascript:getView();'&gt;Get Partial View&lt;/a&gt; &lt;div id="detailsDiv"&gt;&lt;/div&gt; </code></pre> <p>and also like this:</p> <pre><code> &lt;div id="detailsDiv"&gt; @{ Html.RenderPartial("_TitleDescription", null); } &lt;/div&gt; </code></pre> <p>but nothing works for me.</p> <hr> <p>EDIT:</p> <p>I tried the two answers but non of them works... so here is my controller:</p> <pre><code> public ActionResult Location(int id = 0) { Product product = unitOfWork.ProductRepository.GetById(id); return PartialView("Location.cshtml", product); } </code></pre> <p>I put a breakpoint and I'm hitting it every time, but still nothing is changing in the view... :(</p> <p>This is what i tried again:</p> <pre><code> &lt;div id="detailsDiv"&gt;&lt;/div&gt; &lt;a href="#" onclick="loadLocation()"&gt;Location&lt;/a&gt; &lt;script type="text/javascript"&gt; function loadLocation() { $.get('@Url.Action("Location","Product", new { id = 15 } )', function (data) { $('#detailsDiv').load(data); }); } &lt;/script&gt; </code></pre> <p>and I also tried this:</p> <pre><code> &lt;div id="detailsDiv"&gt;&lt;/div&gt; @Html.ActionLink("Pages","Location","Product",new {id = 15},new {@class="menu"}) &lt;script type="text/javascript"&gt; $(function () { $(".menu").click(function (e) { e.preventDefault(); $("#detailsDiv").load($(this).attr("href")) }); }); &lt;/script&gt; </code></pre>
0
1,083
installing Gdal on Windows 10 with python 3.6.4: fatal error C1083: Cannot open include file: 'cpl_port.h'
<p>So I am trying to pip install gdal but got an error. </p> <pre><code> extensions/gdal_wrap.cpp(3168): fatal error C1083: Cannot open include file: 'cpl_port.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.13.26128\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2 </code></pre> <p>So I am running the following:</p> <ul> <li>Python 3.6.4 anaconda distribution</li> <li>Windows 10 (x64)</li> <li>Microsoft Visual 2017 Redistribute both x64 and x86 (both installed by the vs builder tool)</li> </ul> <p>MS Visual was installed because of this error before</p> <pre><code>error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools </code></pre> <p>Here is the trace log for the error:</p> <pre><code> C:\Users\0\Desktop\&gt;pip install gdal Collecting gdal Using cached GDAL-2.2.4.tar.gz Building wheels for collected packages: gdal Running setup.py bdist_wheel for gdal ... error Complete output from command c:\users\0\envs\ecoscan\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\0\\AppData\\Local\\Temp\\pip-build-wc3za_f8\\gdal\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\0\AppData\Local\Temp\tmp9t7nk1ompip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 copying gdal.py -&gt; build\lib.win-amd64-3.6 copying ogr.py -&gt; build\lib.win-amd64-3.6 copying osr.py -&gt; build\lib.win-amd64-3.6 copying gdalconst.py -&gt; build\lib.win-amd64-3.6 copying gnm.py -&gt; build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\osgeo copying osgeo\gdal.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\gdalconst.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\gdalnumeric.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\gdal_array.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\gnm.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\ogr.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\osr.py -&gt; build\lib.win-amd64-3.6\osgeo copying osgeo\__init__.py -&gt; build\lib.win-amd64-3.6\osgeo Fixing build\lib.win-amd64-3.6\gdal.py build\lib.win-amd64-3.6\ogr.py build\lib.win-amd64-3.6\osr.py build\lib.win-amd64-3.6\gdalconst.py build\lib.win-amd64-3.6\gnm.py build\lib.win-amd64-3.6\osgeo\gdal.py build\lib.win-amd64-3.6\osgeo\gdalconst.py build\lib.win-amd64-3.6\osgeo\gdalnumeric.py build\lib.win-amd64-3.6\osgeo\gdal_array.py build\lib.win-amd64-3.6\osgeo\gnm.py build\lib.win-amd64-3.6\osgeo\ogr.py build\lib.win-amd64-3.6\osgeo\osr.py build\lib.win-amd64-3.6\osgeo\__init__.py Skipping optional fixer: ws_comma Fixing build\lib.win-amd64-3.6\gdal.py build\lib.win-amd64-3.6\ogr.py build\lib.win-amd64-3.6\osr.py build\lib.win-amd64-3.6\gdalconst.py build\lib.win-amd64-3.6\gnm.py build\lib.win-amd64-3.6\osgeo\gdal.py build\lib.win-amd64-3.6\osgeo\gdalconst.py build\lib.win-amd64-3.6\osgeo\gdalnumeric.py build\lib.win-amd64-3.6\osgeo\gdal_array.py build\lib.win-amd64-3.6\osgeo\gnm.py build\lib.win-amd64-3.6\osgeo\ogr.py build\lib.win-amd64-3.6\osgeo\osr.py build\lib.win-amd64-3.6\osgeo\__init__.py Skipping optional fixer: ws_comma running build_ext building 'osgeo._gdal' extension creating build\temp.win-amd64-3.6 creating build\temp.win-amd64-3.6\Release creating build\temp.win-amd64-3.6\Release\extensions C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.13.26128\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -I../../port -I../../gcore -I../../alg -I../../ogr/ -I../../ogr/ogrsf_frmts -I../../gnm -I../../apps -Ic:\users\0\anaconda3\include -Ic:\users\0\anaconda3\include -I. "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.13.26128\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\cppwinrt" /EHsc /Tpextensions/gdal_wrap.cpp /Fobuild\temp.win-amd64-3.6\Release\extensions/gdal_wrap.obj gdal_wrap.cpp extensions/gdal_wrap.cpp(3168): fatal error C1083: Cannot open include file: 'cpl_port.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.13.26128\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2 </code></pre> <p>Any ideas how to fix this? I just want use the <code>ogr2ogr</code> in gdal to convert .shp to GeoJSON then to topojson. </p>
0
2,126
Is async HttpClient from .Net 4.5 a bad choice for intensive load applications?
<p>I recently created a simple application for testing the HTTP call throughput that can be generated in an asynchronous manner vs a classical multithreaded approach.</p> <p>The application is a able to perform a predefined number of HTTP calls and at the end it displays the total time needed to perform them. During my tests, all HTTP calls were made to my local IIS sever and they retrieved a small text file (12 bytes in size).</p> <p>The most important part of the code for the asynchronous implementation is listed below:</p> <pre><code>public async void TestAsync() { this.TestInit(); HttpClient httpClient = new HttpClient(); for (int i = 0; i &lt; NUMBER_OF_REQUESTS; i++) { ProcessUrlAsync(httpClient); } } private async void ProcessUrlAsync(HttpClient httpClient) { HttpResponseMessage httpResponse = null; try { Task&lt;HttpResponseMessage&gt; getTask = httpClient.GetAsync(URL); httpResponse = await getTask; Interlocked.Increment(ref _successfulCalls); } catch (Exception ex) { Interlocked.Increment(ref _failedCalls); } finally { if(httpResponse != null) httpResponse.Dispose(); } lock (_syncLock) { _itemsLeft--; if (_itemsLeft == 0) { _utcEndTime = DateTime.UtcNow; this.DisplayTestResults(); } } } </code></pre> <p>The most important part of the multithreading implementation is listed below:</p> <pre><code>public void TestParallel2() { this.TestInit(); ServicePointManager.DefaultConnectionLimit = 100; for (int i = 0; i &lt; NUMBER_OF_REQUESTS; i++) { Task.Run(() =&gt; { try { this.PerformWebRequestGet(); Interlocked.Increment(ref _successfulCalls); } catch (Exception ex) { Interlocked.Increment(ref _failedCalls); } lock (_syncLock) { _itemsLeft--; if (_itemsLeft == 0) { _utcEndTime = DateTime.UtcNow; this.DisplayTestResults(); } } }); } } private void PerformWebRequestGet() { HttpWebRequest request = null; HttpWebResponse response = null; try { request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "GET"; request.KeepAlive = true; response = (HttpWebResponse)request.GetResponse(); } finally { if (response != null) response.Close(); } } </code></pre> <p>Running the tests revealed that the multithreaded version was faster. It took it around 0.6 seconds to complete for 10k requests, while the async one took around 2 seconds to complete for the same amount of load. This was a bit of a surprise, because I was expecting the async one to be faster. Maybe it was because of the fact that my HTTP calls were very fast. In a real world scenario, where the server should perform a more meaningful operation and where there should also be some network latency, the results might be reversed.</p> <p>However, what really concerns me is the way HttpClient behaves when the load is increased. Since it takes it around 2 seconds to deliver 10k messages, I thought it would take it around 20 seconds to deliver 10 times the number of messages, but running the test showed that it needs around 50 seconds to deliver the 100k messages. Furthermore, it usually takes it more than 2 minutes to deliver 200k messages and often, a few thousands of them (3-4k) fail with the following exception:</p> <blockquote> <p>An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.</p> </blockquote> <p>I checked the IIS logs and operations that failed never got to the server. They failed within the client. I ran the tests on a Windows 7 machine with the default range of ephemeral ports of 49152 to 65535. Running netstat showed that around 5-6k ports were being used during tests, so in theory there should have been many more available. If the lack of ports was indeed the cause of the exceptions it means that either netstat didn't properly report the situation or HttClient only uses a maximum number of ports after which it starts throwing exceptions.</p> <p>By contrast, the multithread approach of generating HTTP calls behaved very predictable. I took it around 0.6 seconds for 10k messages, around 5.5 seconds for 100k messages and as expected around 55 seconds for 1 million messages. None of the messages failed. Further more, while it ran, it never used more than 55 MB of RAM (according to Windows Task Manager). The memory used when sending messages asynchronously grew proportionally with the load. It used around 500 MB of RAM during the 200k messages tests.</p> <p>I think there are two main reasons for the above results. The first one is that HttpClient seems to be very greedy in creating new connections with the server. The high number of used ports reported by netstat means that it probably doesn't benefit much from HTTP keep-alive.</p> <p>The second is that HttpClient doesn't seem to have a throttling mechanism. In fact this seems to be a general problem related to async operations. If you need to perform a very large number of operations they will all be started at once and then their continuations will be executed as they are available. In theory this should be ok, because in async operations the load is on external systems but as proved above this is not entirely the case. Having a big number of requests started at once will increase the memory usage and slow down the entire execution.</p> <p>I managed to obtain better results, memory and execution time wise, by limiting the maximum number of asynchronous requests with a simple but primitive delay mechanism:</p> <pre><code>public async void TestAsyncWithDelay() { this.TestInit(); HttpClient httpClient = new HttpClient(); for (int i = 0; i &lt; NUMBER_OF_REQUESTS; i++) { if (_activeRequestsCount &gt;= MAX_CONCURENT_REQUESTS) await Task.Delay(DELAY_TIME); ProcessUrlAsyncWithReqCount(httpClient); } } </code></pre> <p>It would be really useful if HttpClient included a mechanism for limiting the number of concurrent requests. When using the Task class (which is based on the .Net thread pool) throttling is automatically achieved by limiting the number of concurrent threads.</p> <p>For a complete overview, I have also created a version of the async test based on HttpWebRequest rather than HttpClient and managed to obtain much better results. For a start, it allows setting a limit on the number of concurrent connections (with ServicePointManager.DefaultConnectionLimit or via config), which means that it never ran out of ports and never failed on any request (HttpClient, by default, is based on HttpWebRequest, but it seems to ignore the connection limit setting).</p> <p>The async HttpWebRequest approach was still about 50 - 60% slower than the multithreading one, but it was predictable and reliable. The only downside to it was that it used a huge amount of memory under big load. For example it needed around 1.6 GB for sending 1 million requests. By limiting the number of concurrent requests (like I did above for HttpClient) I managed to reduce the used memory to just 20 MB and obtain an execution time just 10% slower than the multithreading approach.</p> <p>After this lengthy presentation, my questions are: Is the HttpClient class from .Net 4.5 a bad choice for intensive load applications? Is there any way to throttle it, which should fix the problems I mention about? How about the async flavor of HttpWebRequest?</p> <p><strong>Update (thanks @Stephen Cleary)</strong></p> <p>As it turns out, HttpClient, just like HttpWebRequest (on which it is based by default), can have its number of concurrent connections on the same host limited with ServicePointManager.DefaultConnectionLimit. The strange thing is that according to <a href="http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit.aspx" rel="noreferrer">MSDN</a>, the default value for the connection limit is 2. I also checked that on my side using the debugger which pointed that indeed 2 is the default value. However, it seems that unless explicitly setting a value to ServicePointManager.DefaultConnectionLimit, the default value will be ignored. Since I didn't explicitly set a value for it during my HttpClient tests I thought it was ignored.</p> <p>After setting ServicePointManager.DefaultConnectionLimit to 100 HttpClient became reliable and predictable (netstat confirms that only 100 ports are used). It is still slower than async HttpWebRequest (by about 40%), but strangely, it uses less memory. For the test which involves 1 million requests, it used a maximum of 550 MB, compared to 1.6 GB in the async HttpWebRequest.</p> <p>So, while HttpClient in combination ServicePointManager.DefaultConnectionLimit seem to ensure reliability (at least for the scenario where all the calls are being made towards the same host), it still looks like its performance is negatively impacted by the lack of a proper throttling mechanism. Something that would limit the concurrent number of requests to a configurable value and put the rest in a queue would make it much more suitable for high scalability scenarios.</p>
0
2,795
java.lang.ClassNotFoundException: com.fasterxml.jackson.core.JsonProcessingException
<p>I'm using <code>templateRest</code> to post <code>User</code> object to <code>Rest Server</code> but I encoutered the following error:</p> <blockquote> <p>Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException at edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:33) Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.core.JsonProcessingException at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more</p> </blockquote> <p>Here is the file <code>RestClientTest.java</code></p> <pre><code>public class RestClientTest { public static void main(String[] args) throws IOException{ RestTemplate rt = new RestTemplate(); // System.out.println("Rest Response" + loadUser("quypham")); // URL url = new URL("http://localhost:8080/rest/user/create"); rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); rt.getMessageConverters().add(new StringHttpMessageConverter()); // Map&lt;String,String&gt; vars = new HashMap&lt;String,String&gt;(); User user = new User(); user.setUserName("datpham"); user.setPassWord("12345"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR,1960); user.setBirthDay(calendar.getTime()); user.setAge(12); String uri = new String("http://localhost:8080/rest/user/create"); User returns = rt.postForObject(uri, user,User.class); // createUser(user); System.out.println("Rest Response" + loadUser("datpham")); } </code></pre> <p>Here is the file <code>UserRestServiceController.java</code></p> <pre><code>@Controller public class UserRestServiceController { @Autowired public UserDao userDao; @RequestMapping(value = "/rest/user/create",method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void addUser(@RequestBody User user){ userDao.save(user); } </code></pre> <p>Here is the file pom.xml</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/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;edu.java.spring.service&lt;/groupId&gt; &lt;artifactId&gt;springDAT-service&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;name&gt;springDAT-service Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;4.0.3.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;4.0.3.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context-support&lt;/artifactId&gt; &lt;version&gt;4.0.3.RELEASE&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;4.0.3.RELEASE&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;4.0.3.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version&gt;4.0.3.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;5.1.0.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.derby&lt;/groupId&gt; &lt;artifactId&gt;derby&lt;/artifactId&gt; &lt;version&gt;10.12.1.1&lt;/version&gt; &lt;/dependency&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;1.9.13&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;springMOTHER-service&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.12.4&lt;/version&gt; &lt;configuration&gt; &lt;skipTests&gt;true&lt;/skipTests&gt; &lt;argLine&gt;-Xmx2524m&lt;/argLine&gt; &lt;/configuration&gt; &lt;/plugin&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;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;encoding&gt;UTF-8&lt;/encoding&gt; &lt;fork&gt;true&lt;/fork&gt; &lt;compilerArgs&gt; &lt;arg&gt;-XDignore.symbol.file&lt;/arg&gt; &lt;/compilerArgs&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt; &lt;version&gt;9.3.0.M1&lt;/version&gt; &lt;configuration&gt; &lt;jvmArgs&gt;-Xmx1048m -Xms536m -XX:PermSize=128m -XX:MaxPermSize=512m&lt;/jvmArgs&gt; &lt;reload&gt;manual&lt;/reload&gt; &lt;systemProperties&gt; &lt;systemProperty&gt; &lt;name&gt;lib&lt;/name&gt; &lt;value&gt;${basedir}/target/spring-mvc/WEB-INF/lib&lt;/value&gt; &lt;/systemProperty&gt; &lt;/systemProperties&gt; &lt;scanIntervalSeconds&gt;3&lt;/scanIntervalSeconds&gt; &lt;connectors&gt; &lt;connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"&gt; &lt;port&gt;8080&lt;/port&gt; &lt;maxIdleTime&gt;60000&lt;/maxIdleTime&gt; &lt;/connector&gt; &lt;/connectors&gt; &lt;contextPath&gt;/&lt;/contextPath&gt; &lt;webAppSourceDirectory&gt;${basedir}/src/main/webapp&lt;/webAppSourceDirectory&gt; &lt;webXml&gt;${basedir}/src/main/webapp/WEB-INF/web.xml&lt;/webXml&gt; &lt;classesDirectory&gt;${basedir}/target/classes&lt;/classesDirectory&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I have browsed information on google, afterwards I have tried to add jackson 2.4 in pom.xml but didn't seem to work:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;2.4.0-rc3&lt;/version&gt; &lt;/dependency&gt; </code></pre>
0
4,575
why do I get 'inject' undefined error when using Jasmine with Angular?
<p>I am Jasmine/AngularJS unit testing newbie. I created a simple angular app to add two numbers so that I can learn how to write unit tests for Angular App. The <a href="http://docs.angularjs.org/guide/dev_guide.unit-testing#!" rel="noreferrer">Angular Doc on unit test is incomplete</a>.Based on the blogs and stack overflow answers, I build my first test and I am running into 'injector' undefined error. I am using Jasmine framework for the unit testing. <br> <strong>HTML</strong></p> <pre><code>&lt;body&gt; &lt;div ng-controller="additionCtrl"&gt; First Number: &lt;input ng-model="NumberOne"/&gt;&lt;br/&gt; Second Number: &lt;input ng-model="NumberTwo"/&gt; &lt;button ng-click="add(NumberOne, NumberTwo)"&gt;Add&lt;/button&gt;&lt;br/&gt; Result: {{Result}} &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"&gt;&lt;/script&gt; &lt;script src="Scripts/additionCtrl.js"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre> <p><strong>Controller:</strong></p> <pre><code>function additionCtrl($scope) { $scope.NumberOne = 0; $scope.NumberTwo = 0; $scope.Result = 0; $scope.add = function (a, b) { }; } </code></pre> <p>Jasmine spec file.</p> <pre><code>describe("Addition", function () { var $scope, ctrl; beforeEach(inject(function ($rootScope, $controller) { this.scope = $rootScope.$new(); ctrl = $controller('additionCtrl', { $scope: this.scope }); })); it("should add two integer numbers.", inject(function ($controller) { expect(ctrl.add(2, 3)).toEqual(5); })); }); </code></pre> <p>Specrunner.html</p> <pre><code> &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="lib/angular-mocks.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="lib/jasmine-1.3.1/jasmine.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="lib/jasmine-1.3.1/jasmine-html.js"&gt;&lt;/script&gt; &lt;!-- include source files here... --&gt; &lt;script type="text/javascript" src="../App/Scripts/additionCtrl.js"&gt;&lt;/script&gt; &lt;!-- include spec files here... --&gt; &lt;script type="text/javascript" src="spec/addition.spec.js"&gt;&lt;/script&gt; </code></pre> <p>This is a failing test and once the test fails with the expected result then I can modify the code to make it pass, but I am facing the problem with somehow angular mock is not getting injector. <br> I saw an example where I can newup a controller instead of using injector, but I would like to try to learn on using injector so that I am set up more complex tests.<br> I might be missing something simple here. Please direct me to any write up I might have missed.<br> Thanks</p>
0
1,043
jQuery to make HTML5 Canvas Responsive
<p>How can I make my HTML5 Animation (Canvas) responsive using jQuery ? </p> <p>Since my Canvas is 1100px Width by 800px Height (for a greater effect on bigger screens) I the canvas to start resizing for screens smaller than 1200 px width.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;canvas id="canvas" width="1100" height="800" style="background-color:#ffffff"&gt;&lt;/canvas&gt; </code></pre> <p><strong>Script :</strong></p> <pre><code>var canvas, stage, exportRoot; function init() { canvas = document.getElementById("canvas"); images = images||{}; var manifest = [ {src:"images/preloader/_282.png", id:"_282"}, {src:"images/preloader/Bitmap10.png", id:"Bitmap10"}, {src:"images/preloader/Bitmap11.png", id:"Bitmap11"}, {src:"images/preloader/Bitmap12.png", id:"Bitmap12"}, {src:"images/preloader/Bitmap13.png", id:"Bitmap13"}, {src:"images/preloader/Bitmap14.png", id:"Bitmap14"}, {src:"images/preloader/Bitmap15.png", id:"Bitmap15"}, {src:"images/preloader/Bitmap16.png", id:"Bitmap16"}, {src:"images/preloader/Bitmap17.png", id:"Bitmap17"}, {src:"images/preloader/Bitmap18.png", id:"Bitmap18"}, {src:"images/preloader/Bitmap2.png", id:"Bitmap2"}, {src:"images/preloader/Bitmap3.png", id:"Bitmap3"}, {src:"images/preloader/Bitmap4.png", id:"Bitmap4"}, {src:"images/preloader/Bitmap5.png", id:"Bitmap5"}, {src:"images/preloader/Bitmap6.png", id:"Bitmap6"}, {src:"images/preloader/Bitmap7.png", id:"Bitmap7"}, {src:"images/preloader/Bitmap8.png", id:"Bitmap8"}, {src:"images/preloader/Bitmap9.png", id:"Bitmap9"}, {src:"images/preloader/flash0aiAssets.png", id:"flash0aiAssets"} ]; var loader = new createjs.LoadQueue(false); loader.addEventListener("fileload", handleFileLoad); loader.addEventListener("complete", handleComplete); loader.loadManifest(manifest); } function handleFileLoad(evt) { if (evt.item.type == "image") { images[evt.item.id] = evt.result; } } function handleComplete() { exportRoot = new lib.preloadercs6(); stage = new createjs.Stage(canvas); stage.addChild(exportRoot); stage.update(); createjs.Ticker.setFPS(24); createjs.Ticker.addEventListener("tick", stage); } </code></pre> <p><strong>PS:</strong> Also, if there is any other way of doing it even without using jQuery, I'm open to whatever can solve my problem.</p> <p>Thanks</p> <h2><strong>UPDATE</strong></h2> <p>I found something and put it together but it doesn't work :</p> <pre><code>(function($){ $(window).resize(function(){ windowResize(); }); })(jQuery); function windowResize(){ stage.canvas.width = window.innerWidth; stage.canvas.height = window.innerHeight; var test = (window.innerHeight/800)*1; exportRoot.scaleX = exportRoot.scaleY = test; } </code></pre>
0
1,346
No plugin found for prefix 'exec' in the current project and in the plug in groups org.codehaus.mojo
<p>I have read several questions with similar issue and the Help 1 page. Unfortunately, I am stuck. </p> <p>One possible reason could be caused by proxy but there is no such proxy here. Additionally, all maven projects in my PC have been successfully updated when I update it from Eclipse. So I discard this possibility. </p> <p>Other thing I checked was to look for codehaus in my local repository and I find it (C:\Users\myUser.m2\repository\org\codehaus\mojo). </p> <p>Another try, I tried add pluginGroups/pluginGroup in settings. The project is a very simple hello word using spring batch with only a Tasklet and its execute method. There isn't public static void main method.</p> <p>Command.exe with the whole error printed after I added the Matteo recommendation:</p> <pre><code>C:\temp\TaskletJavaConfig\spring-batch-helloworld&gt;mvn compile exec:java -e Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook Picked up _JAVA_OPTIONS: -Xrunjvmhook -Xbootclasspath/a:C:\PROGRA~2\HP\QUICKT~1\ bin\JAVA_S~1\classes;C:\PROGRA~2\HP\QUICKT~1\bin\JAVA_S~1\classes\jasmine.jar [INFO] Error stacktraces are turned on. [INFO] Scanning for projects... Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/exec-maven-p lugin/1.1/exec-maven-plugin-1.1.pom [WARNING] Failed to retrieve plugin descriptor for org.codehaus.mojo:exec-maven- plugin:1.1: Plugin org.codehaus.mojo:exec-maven-plugin:1.1 or one of its depende ncies could not be resolved: Failed to read artifact descriptor for org.codehaus .mojo:exec-maven-plugin:jar:1.1 Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -deploy-plugin/2.7/maven-deploy-plugin-2.7.pom [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:mave n-deploy-plugin:2.7: Plugin org.apache.maven.plugins:maven-deploy-plugin:2.7 or one of its dependencies could not be resolved: Failed to read artifact descripto r for org.apache.maven.plugins:maven-deploy-plugin:jar:2.7 Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -site-plugin/3.3/maven-site-plugin-3.3.pom [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:mave n-site-plugin:3.3: Plugin org.apache.maven.plugins:maven-site-plugin:3.3 or one of its dependencies could not be resolved: Failed to read artifact descriptor fo r org.apache.maven.plugins:maven-site-plugin:jar:3.3 Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -antrun-plugin/1.3/maven-antrun-plugin-1.3.pom [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:mave n-antrun-plugin:1.3: Plugin org.apache.maven.plugins:maven-antrun-plugin:1.3 or one of its dependencies could not be resolved: Failed to read artifact descripto r for org.apache.maven.plugins:maven-antrun-plugin:jar:1.3 Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -assembly-plugin/2.2-beta-5/maven-assembly-plugin-2.2-beta-5.pom [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:mave n-assembly-plugin:2.2-beta-5: Plugin org.apache.maven.plugins:maven-assembly-plu gin:2.2-beta-5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-assembly-plugin:jar:2.2-b eta-5 Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -dependency-plugin/2.8/maven-dependency-plugin-2.8.pom [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:mave n-dependency-plugin:2.8: Plugin org.apache.maven.plugins:maven-dependency-plugin :2.8 or one of its dependencies could not be resolved: Failed to read artifact d escriptor for org.apache.maven.plugins:maven-dependency-plugin:jar:2.8 Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -release-plugin/2.3.2/maven-release-plugin-2.3.2.pom [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:mave n-release-plugin:2.3.2: Plugin org.apache.maven.plugins:maven-release-plugin:2.3 .2 or one of its dependencies could not be resolved: Failed to read artifact des criptor for org.apache.maven.plugins:maven-release-plugin:jar:2.3.2 Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metada ta.xml Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven -metadata.xml [WARNING] Could not transfer metadata org.codehaus.mojo/maven-metadata.xml from/ to central (https://repo.maven.apache.org/maven2): sun.security.validator.Valida torException: PKIX path building failed: sun.security.provider.certpath.SunCertP athBuilderException: unable to find valid certification path to requested target [WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xm l from/to central (https://repo.maven.apache.org/maven2): sun.security.validator .ValidatorException: PKIX path building failed: sun.security.provider.certpath.S unCertPathBuilderException: unable to find valid certification path to requested target [WARNING] Failure to transfer org.codehaus.mojo/maven-metadata.xml from https:// repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer metadata org.codehaus.mojo/maven- metadata.xml from/to central (https://repo.maven.apache.org/maven2): sun.securit y.validator.ValidatorException: PKIX path building failed: sun.security.provider .certpath.SunCertPathBuilderException: unable to find valid certification path t o requested target [WARNING] Failure to transfer org.apache.maven.plugins/maven-metadata.xml from h ttps://repo.maven.apache.org/maven2 was cached in the local repository, resoluti on will not be reattempted until the update interval of central has elapsed or u pdates are forced. Original error: Could not transfer metadata org.apache.maven. plugins/maven-metadata.xml from/to central (https://repo.maven.apache.org/maven2 ): sun.security.validator.ValidatorException: PKIX path building failed: sun.sec urity.provider.certpath.SunCertPathBuilderException: unable to find valid certif ication path to requested target [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.094 s [INFO] Finished at: 2016-01-13T12:48:00-06:00 [INFO] Final Memory: 13M/123M [INFO] ------------------------------------------------------------------------ [ERROR] No plugin found for prefix 'exec' in the current project and in the plug in groups [org.codehaus.mojo, org.apache.maven.plugins] available from the repos itories [local (C:\Users\myUser\.m2\repository), central (https://repo.maven.ap ache.org/maven2)] -&gt; [Help 1] org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException: No plugin found for prefix 'exec' in the current project and in the plugin groups [org.codehaus. mojo, org.apache.maven.plugins] available from the repositories [local (C:\Users \myUser\.m2\repository), central (https://repo.maven.apache.org/maven2)] at org.apache.maven.plugin.prefix.internal.DefaultPluginPrefixResolver.r esolve(DefaultPluginPrefixResolver.java:93) at org.apache.maven.lifecycle.internal.MojoDescriptorCreator.findPluginF orPrefix(MojoDescriptorCreator.java:265) at org.apache.maven.lifecycle.internal.MojoDescriptorCreator.getMojoDesc riptor(MojoDescriptorCreator.java:219) at org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalcul ator.calculateTaskSegments(DefaultLifecycleTaskSegmentCalculator.java:103) at org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalcul ator.calculateTaskSegments(DefaultLifecycleTaskSegmentCalculator.java:83) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(Lifecycl eStarter.java:89) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Laun cher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.jav a:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(La uncher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java: 356) [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please rea d the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundF orPrefixException C:\temp\TaskletJavaConfig\spring-batch-helloworld&gt; </code></pre> <p>Evidence that there is no proxy </p> <pre><code>C:\temp\TaskletJavaConfig\spring-batch-helloworld&gt;netsh winhttp show proxy Current WinHTTP proxy settings: Direct access (no proxy server). </code></pre> <p>pom.xml </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;com.test&lt;/groupId&gt; &lt;artifactId&gt;spring-batch-helloworld&lt;/artifactId&gt; &lt;version&gt;20131227&lt;/version&gt; &lt;name&gt;spring batch hello world&lt;/name&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;!-- pluginRepositories&gt; &lt;pluginRepository&gt; &lt;id&gt;numberformat-releases&lt;/id&gt; &lt;url&gt;https://raw.github.com/numberformat/20130213/master/repo&lt;/url&gt; &lt;/pluginRepository&gt; &lt;/pluginRepositories--&gt; &lt;properties&gt; &lt;spring.framework.version&gt;3.2.1.RELEASE&lt;/spring.framework.version&gt; &lt;spring.batch.version&gt;3.0.0.M2&lt;/spring.batch.version&gt; &lt;/properties&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;spring-s3&lt;/id&gt; &lt;name&gt;Spring Maven 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;dependency&gt; &lt;groupId&gt;commons-lang&lt;/groupId&gt; &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.batch&lt;/groupId&gt; &lt;artifactId&gt;spring-batch-core&lt;/artifactId&gt; &lt;version&gt;${spring.batch.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.batch&lt;/groupId&gt; &lt;artifactId&gt;spring-batch-infrastructure&lt;/artifactId&gt; &lt;version&gt;${spring.batch.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.17&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.8.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;hsqldb&lt;/groupId&gt; &lt;artifactId&gt;hsqldb&lt;/artifactId&gt; &lt;version&gt;1.8.0.7&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;!-- added after Matteo recommendation--&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.1&lt;/version&gt; &lt;configuration&gt; &lt;mainClass&gt;org.springframework.batch.core.launch.support.CommandLineJobRunner&lt;/mainClass&gt; &lt;arguments&gt; &lt;argument&gt;com.test.config.HelloWorldJobConfig&lt;/argument&gt; &lt;argument&gt;helloWorldJob&lt;/argument&gt; &lt;/arguments&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;!-- build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;github.numberformat&lt;/groupId&gt; &lt;artifactId&gt;blog-plugin&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;configuration&gt; &lt;gitUrl&gt;https://github.com/numberformat/wordpress/tree/master/${project.version}/${project.artifactId}&lt;/gitUrl&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;1&lt;/id&gt; &lt;phase&gt;site&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;generate&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build--&gt; &lt;!-- Run the application using: mvn compile exec:java -Dexec.mainClass=org.springframework.batch.core.launch.support.CommandLineJobRunner -Dexec.args="com.test.config.HelloWorldJobConfig helloWorldJob" --&gt; &lt;/project&gt; </code></pre> <p>Settings.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"&gt; &lt;pluginGroups&gt; &lt;pluginGroup&gt;org.codehaus.mojo&lt;/pluginGroup&gt; &lt;/pluginGroups&gt; &lt;proxies&gt; &lt;/proxies&gt; &lt;servers&gt; &lt;/servers&gt; &lt;mirrors&gt; &lt;/mirrors&gt; &lt;profiles&gt; &lt;/profiles&gt; &lt;/settings&gt; </code></pre> <p>Logs with only mvn org.codehaus.mojo</p> <pre><code>C:\temp\TaskletJavaConfig\spring-batch-helloworld&gt;mvn org.codehaus.mojo:exec-mav en-plugin:1.1:java Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook Picked up _JAVA_OPTIONS: -Xrunjvmhook -Xbootclasspath/a:C:\PROGRA~2\HP\QUICKT~1\ bin\JAVA_S~1\classes;C:\PROGRA~2\HP\QUICKT~1\bin\JAVA_S~1\classes\jasmine.jar [INFO] Scanning for projects... Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/exec-maven-p lugin/1.1/exec-maven-plugin-1.1.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.356 s [INFO] Finished at: 2016-01-13T15:29:20-06:00 [INFO] Final Memory: 10M/123M [INFO] ------------------------------------------------------------------------ [ERROR] Plugin org.codehaus.mojo:exec-maven-plugin:1.1 or one of its dependencie s could not be resolved: Failed to read artifact descriptor for org.codehaus.moj o:exec-maven-plugin:jar:1.1: Could not transfer artifact org.codehaus.mojo:exec- maven-plugin:pom:1.1 from/to central (https://repo.maven.apache.org/maven2): sun .security.validator.ValidatorException: PKIX path building failed: sun.security. provider.certpath.SunCertPathBuilderException: unable to find valid certificatio n path to requested target -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit ch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please rea d the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResoluti onException C:\temp\TaskletJavaConfig\spring-batch-helloworld&gt;mvn compile mvn org.codehaus.m ojo:exec-maven-plugin:1.1:java Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook Picked up _JAVA_OPTIONS: -Xrunjvmhook -Xbootclasspath/a:C:\PROGRA~2\HP\QUICKT~1\ bin\JAVA_S~1\classes;C:\PROGRA~2\HP\QUICKT~1\bin\JAVA_S~1\classes\jasmine.jar [INFO] Scanning for projects... Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/exec-maven-p lugin/1.1/exec-maven-plugin-1.1.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.250 s [INFO] Finished at: 2016-01-13T15:31:03-06:00 [INFO] Final Memory: 11M/123M [INFO] ------------------------------------------------------------------------ [ERROR] Plugin org.codehaus.mojo:exec-maven-plugin:1.1 or one of its dependencie s could not be resolved: Failed to read artifact descriptor for org.codehaus.moj o:exec-maven-plugin:jar:1.1: Could not transfer artifact org.codehaus.mojo:exec- maven-plugin:pom:1.1 from/to central (https://repo.maven.apache.org/maven2): sun .security.validator.ValidatorException: PKIX path building failed: sun.security. provider.certpath.SunCertPathBuilderException: unable to find valid certificatio n path to requested target -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit ch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please rea d the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResoluti onException </code></pre>
0
8,357
error TS5023: Unknown compiler option 'enableIvy'
<p>I am trying to add IVY to my angular 7 beta project. So, I added <code>enableIvy: true</code> to <code>src/tsconfig.app.json</code> in <code>compilerOptions</code> section</p> <p>But when I run <code>ng build --prod --aot --output-hashing none</code> I get below error.</p> <pre><code>error TS5023: Unknown compiler option 'enableIvy'. Error: error TS5023: Unknown compiler option 'enableIvy'. at AngularCompilerPlugin._setupOptions (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:112:19) at new AngularCompilerPlugin (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:61:14) at _createAotPlugin (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/typescript.js:41:12) at Object.getAotConfig (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/typescript.js:63:19) at BrowserBuilder.buildWebpackConfig (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/src/browser/index.js:81:37) at MergeMapSubscriber.rxjs_1.of.pipe.operators_1.concatMap [as project] (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/src/browser/index.js:31:38) at MergeMapSubscriber._tryNext (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/operators/mergeMap.js:65:27) at MergeMapSubscriber._next (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/operators/mergeMap.js:55:18) at MergeMapSubscriber.Subscriber.next (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/Subscriber.js:64:18) at TapSubscriber._next (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/operators/tap.js:62:26) at TapSubscriber.Subscriber.next (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/Subscriber.js:64:18) at MergeMapSubscriber.notifyNext (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/operators/mergeMap.js:84:26) at InnerSubscriber._next (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/InnerSubscriber.js:25:21) at InnerSubscriber.Subscriber.next (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/Subscriber.js:64:18) at ForkJoinSubscriber.notifyComplete (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/observable/forkJoin.js:79:25) at InnerSubscriber._complete (/Users/k26686/aniruddh/develop/experiment/shepherd/node_modules/@angular-devkit/build-angular/node_modules/rxjs/internal/InnerSubscriber.js:32:21) </code></pre> <p>Any one resolved this.</p>
0
1,235
Visual Studio 2012 Web Deploy Publish ignores selected Configuration for transform and build
<p>When I create a publish profile I have the option to select which Configuration I want the publish to use for this profile. The options are like Debug, Release or any custom defined one like Staging. The problem is that if I select any Configuration other than Release or Debug, say Staging, visual studio totally ignores my selection and uses Web.Release.config for transform and build. Am I doing something wrong or is this by design? It seems that Publish only recognizes Release and Debug as acceptable Configuration. Any thoughts on this issue?</p> <p>I am using Visual Studio 2012 RTM. </p> <p><strong>Update 1 :: "NightlyLive - Any CPU" configuration selected:</strong></p> <p>Here I select my own custom Configuration "NightlyLive":</p> <p><img src="https://i.stack.imgur.com/tlGpv.png" alt="enter image description here"></p> <p>And here is what happens when I publish:</p> <pre><code>6&gt;------ Build started: Project: UI.Next, Configuration: Release Any CPU ------ 7&gt;------ Publish started: Project: UI.Next, Configuration: Release Any CPU ------ 7&gt;Transformed Web.config using [...]\UI.Next\Web.Release.config into obj\Release\TransformWebConfig\transformed\Web.config. </code></pre> <p>As you can see it builds the project using Release Any CPU (instead of NightlyLive - Any CPU) and also it transforms the Web.config using Web.Release.config (instead of Web.NightlyLive.config).</p> <p><strong>Update 2 :: Profile name renamed to "NightlyLive":</strong></p> <p>Here i rename the profile name from "test" to "NightlyLive". </p> <p><img src="https://i.stack.imgur.com/denan.png" alt="enter image description here"></p> <p>Here is the console output:</p> <pre><code>6&gt;------ Build started: Project: UI.Next, Configuration: Release Any CPU ------ 7&gt;------ Publish started: Project: UI.Next, Configuration: Release Any CPU ------ 7&gt;Transformed Web.config using [...]\UI.Next\Web.Release.config into obj\Release\TransformWebConfig\transformed\Web.config. 7&gt;[...]\UI.Next\Web.NightlyLive.config(23,18): Warning : Argument 'debug' did not match any attributes 7&gt;[...]\UI.Next\obj\Release\TransformWebConfig\transformed\Web.config(78,6): Warning : No attributes found to remove 7&gt;Transformed obj\Release\TransformWebConfig\transformed\Web.config using [...]\UI.Next\\Web.NightlyLive.config into obj\Release\ProfileTransformWebConfig\transformed\Web.config. </code></pre> <p>So here, still it is building using Release Any CPU. </p> <p>But for Web.config it first transforms using Web.Release.config then it does a second transformation on top of the previous one using Web.NightlyLive.config.</p> <p>The double transformation i think is by design and makes sense. But the fact that you have to rename your profile name to the configuration name to force use your custom transformation file, does not look right.</p> <p><strong>Update 3 :: TestSolution added</strong></p> <p>You can download the stripped down solution from <a href="http://sdrv.ms/OSJNcS" rel="noreferrer">here</a>.</p> <p>First I created a brand new vs2012 solution and everything worked fine. So I decided to strip down my current solution and upload as test case. </p> <p><em>Please note that my solution was originally a vs2010 solution that i opened in vs2012 and vs2012 did the necessary modifications to the solution.</em> </p> <p><strong>Update 4 :: Verdict</strong></p> <p>I guess my solution configurations were all messed up. So basically to solve this issue, I deleted all my customized solution and project configurations and created them again along with the web.config transform files.</p> <p><strong>Problem solved.</strong></p>
0
1,031
How to get array from JSON Object?
<p>i want to get the array of json objects from a json object. But it doesnt work. Can anybody help me?</p> <p>The output is: </p> <pre><code>Exception in thread "main" org.json.JSONException: JSONObject["value"] not found. </code></pre> <p>Source Code: </p> <pre><code>import org.json.*; public class JsonIO { public static void parseJson(StringBuffer sb){ JSONObject obj = new JSONObject(sb); JSONArray arr = obj.getJSONArray("value"); for (int i = 0; i&lt; arr.length(); i++){ System.out.println(arr.getJSONObject(i).getString("Name")); } } } </code></pre> <p>The input is: </p> <pre><code>{ "@odata.context":"https://www.nameofshop......de/odata/$metadata#Product","value":[ { "ProductTypeId":5,"ParentGroupedProductId":0,"VisibleIndividually":true,"Name":"Build your own computer","ShortDescription":"Build it","FullDescription":"&lt;p&gt;Fight back against cluttered workspaces with the stylish IBM zBC12 All-in-One desktop PC, featuring powerful computing resources and a stunning 20.1-inch widescreen display with stunning XBRITE-HiColor LCD technology. The black IBM zBC12 has a built-in microphone and MOTION EYE camera with face-tracking technology that allows for easy communication with friends and family. And it has a built-in DVD burner and Sony's Movie Store software so you can create a digital entertainment library for personal viewing at your convenience. Easy to setup and even easier to use, this JS-series All-in-One includes an elegantly designed keyboard and a USB mouse.&lt;/p&gt;","AdminComment":null,"ProductTemplateId":1,"VendorId":0,"ShowOnHomePage":true,"MetaKeywords":null,"MetaDescription":null,"MetaTitle":null,"AllowCustomerReviews":true,"ApprovedRatingSum":0,"NotApprovedRatingSum":0,"ApprovedTotalReviews":0,"NotApprovedTotalReviews":0,"SubjectToAcl":false,"LimitedToStores":false,"Sku":null,"ManufacturerPartNumber":null,"Gtin":null,"IsGiftCard":false,"GiftCardTypeId":0,"OverriddenGiftCardAmount":null,"RequireOtherProducts":false,"RequiredProductIds":null,"AutomaticallyAddRequiredProducts":false,"IsDownload":false,"DownloadId":0,"UnlimitedDownloads":false,"MaxNumberOfDownloads":0,"DownloadExpirationDays":null,"DownloadActivationTypeId":0,"HasSampleDownload":false,"SampleDownloadId":0,"HasUserAgreement":false,"UserAgreementText":null,"IsRecurring":false,"RecurringCycleLength":0,"RecurringCyclePeriodId":0,"RecurringTotalCycles":0,"IsRental":false,"RentalPriceLength":0,"RentalPricePeriodId":0,"IsShipEnabled":true,"IsFreeShipping":true,"ShipSeparately":false,"AdditionalShippingCharge":0.0000,"DeliveryDateId":0,"IsTaxExempt":false,"TaxCategoryId":2,"IsTelecommunicationsOrBroadcastingOrElectronicServices":false,"ManageInventoryMethodId":1,"UseMultipleWarehouses":false,"WarehouseId":0,"StockQuantity":10000,"DisplayStockAvailability":true,"DisplayStockQuantity":false,"MinStockQuantity":0,"LowStockActivityId":1,"NotifyAdminForQuantityBelow":1,"BackorderModeId":0,"AllowBackInStockSubscriptions":false,"OrderMinimumQuantity":1,"OrderMaximumQuantity":10000,"AllowedQuantities":null,"AllowAddingOnlyExistingAttributeCombinations":false,"DisableBuyButton":false,"DisableWishlistButton":false,"AvailableForPreOrder":false,"PreOrderAvailabilityStartDateTimeUtc":null,"CallForPrice":false,"Price":1200.0000,"OldPrice":0.0000,"ProductCost":0.0000,"SpecialPrice":null,"SpecialPriceStartDateTimeUtc":null,"SpecialPriceEndDateTimeUtc":null,"CustomerEntersPrice":false,"MinimumCustomerEnteredPrice":0.0000,"MaximumCustomerEnteredPrice":0.0000,"BasepriceEnabled":false,"BasepriceAmount":0.0000,"BasepriceUnitId":0,"BasepriceBaseAmount":0.0000,"BasepriceBaseUnitId":0,"MarkAsNew":true,"MarkAsNewStartDateTimeUtc":null,"MarkAsNewEndDateTimeUtc":null,"HasTierPrices":false,"HasDiscountsApplied":false,"Weight":2.0000,"Length":2.0000,"Width":2.0000,"Height":2.0000,"AvailableStartDateTimeUtc":null,"AvailableEndDateTimeUtc":null,"DisplayOrder":0,"Published":true,"Deleted":true,"CreatedOnUtc":"2016-04-19T11:41:10.163+01:00","UpdatedOnUtc":"2016-04-19T11:41:10.163+01:00","ProductType":"SimpleProduct","BackorderMode":"NoBackorders","DownloadActivationType":"0","GiftCardType":"Virtual","LowStockActivity":"DisableBuyButton","ManageInventoryMethod":"ManageStock","RecurringCyclePeriod":"Days","RentalPricePeriod":"Days","Id":1 },{ "ProductTypeId":5,"ParentGroupedProductId":0,"VisibleIndividually":true,"Name":"Digital Storm VANQUISH 3 Custom Performance PC","ShortDescription":"Digital Storm Vanquish 3 Desktop PC","FullDescription":"&lt;p&gt;Blow the doors off today\u2019s most demanding games with maximum detail, speed, and power for an immersive gaming experience without breaking the bank.&lt;/p&gt;&lt;p&gt;Stay ahead of the competition, VANQUISH 3 is fully equipped to easily handle future upgrades, keeping your system on the cutting edge for years to come.&lt;/p&gt;&lt;p&gt;Each system is put through an extensive stress test, ensuring you experience zero bottlenecks and get the maximum performance from your hardware.&lt;/p&gt;","AdminComment":null,"ProductTemplateId":1,"VendorId":0,"ShowOnHomePage":false,"MetaKeywords":null,"MetaDescription":null,"MetaTitle":null,"AllowCustomerReviews":true,"ApprovedRatingSum":0,"NotApprovedRatingSum":0,"ApprovedTotalReviews":0,"NotApprovedTotalReviews":0,"SubjectToAcl":false,"LimitedToStores":false,"Sku":null,"ManufacturerPartNumber":null,"Gtin":null,"IsGiftCard":false,"GiftCardTypeId":0,"OverriddenGiftCardAmount":null,"RequireOtherProducts":false,"RequiredProductIds":null,"AutomaticallyAddRequiredProducts":false,"IsDownload":false,"DownloadId":0,"UnlimitedDownloads":false,"MaxNumberOfDownloads":0,"DownloadExpirationDays":null,"DownloadActivationTypeId":0,"HasSampleDownload":false,"SampleDownloadId":0,"HasUserAgreement":false,"UserAgreementText":null,"IsRecurring":false,"RecurringCycleLength":0,"RecurringCyclePeriodId":0,"RecurringTotalCycles":0,"IsRental":false,"RentalPriceLength":0,"RentalPricePeriodId":0,"IsShipEnabled":true,"IsFreeShipping":false,"ShipSeparately":false,"AdditionalShippingCharge":0.0000,"DeliveryDateId":0,"IsTaxExempt":false,"TaxCategoryId":2,"IsTelecommunicationsOrBroadcastingOrElectronicServices":false,"ManageInventoryMethodId":1,"UseMultipleWarehouses":false,"WarehouseId":0,"StockQuantity":10000,"DisplayStockAvailability":true,"DisplayStockQuantity":false,"MinStockQuantity":0,"LowStockActivityId":1,"NotifyAdminForQuantityBelow":1,"BackorderModeId":0,"AllowBackInStockSubscriptions":false,"OrderMinimumQuantity":1,"OrderMaximumQuantity":10000,"AllowedQuantities":null,"AllowAddingOnlyExistingAttributeCombinations":false,"DisableBuyButton":false,"DisableWishlistButton":false,"AvailableForPreOrder":false,"PreOrderAvailabilityStartDateTimeUtc":null,"CallForPrice":false,"Price":1259.0000,"OldPrice":0.0000,"ProductCost":0.0000,"SpecialPrice":null,"SpecialPriceStartDateTimeUtc":null,"SpecialPriceEndDateTimeUtc":null,"CustomerEntersPrice":false,"MinimumCustomerEnteredPrice":0.0000,"MaximumCustomerEnteredPrice":0.0000,"BasepriceEnabled":false,"BasepriceAmount":0.0000,"BasepriceUnitId":0,"BasepriceBaseAmount":0.0000,"BasepriceBaseUnitId":0,"MarkAsNew":false,"MarkAsNewStartDateTimeUtc":null,"MarkAsNewEndDateTimeUtc":null,"HasTierPrices":false,"HasDiscountsApplied":false,"Weight":7.0000,"Length":7.0000,"Width":7.0000,"Height":7.0000,"AvailableStartDateTimeUtc":null,"AvailableEndDateTimeUtc":null,"DisplayOrder":0,"Published":true,"Deleted":true,"CreatedOnUtc":"2016-04-19T11:41:12.177+01:00","UpdatedOnUtc":"2016-04-19T11:41:12.177+01:00","ProductType":"SimpleProduct","BackorderMode":"NoBackorders","DownloadActivationType":"0","GiftCardType":"Virtual","LowStockActivity":"DisableBuyButton","ManageInventoryMethod":"ManageStock","RecurringCyclePeriod":"Days","RentalPricePeriod":"Days","Id":2 } </code></pre>
0
2,308
C OpenMP parallel quickSort
<p>Once again I'm stuck when using openMP in C++. This time I'm trying to implement a parallel quicksort.</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;stack&gt; #include &lt;utility&gt; #include &lt;omp.h&gt; #include &lt;stdio.h&gt; #define SWITCH_LIMIT 1000 using namespace std; template &lt;typename T&gt; void insertionSort(std::vector&lt;T&gt; &amp;v, int q, int r) { int key, i; for(int j = q + 1; j &lt;= r; ++j) { key = v[j]; i = j - 1; while( i &gt;= q &amp;&amp; v[i] &gt; key ) { v[i+1] = v[i]; --i; } v[i+1] = key; } } stack&lt;pair&lt;int,int&gt; &gt; s; template &lt;typename T&gt; void qs(vector&lt;T&gt; &amp;v, int q, int r) { T pivot; int i = q - 1, j = r; //switch to insertion sort for small data if(r - q &lt; SWITCH_LIMIT) { insertionSort(v, q, r); return; } pivot = v[r]; while(true) { while(v[++i] &lt; pivot); while(v[--j] &gt; pivot); if(i &gt;= j) break; std::swap(v[i], v[j]); } std::swap(v[i], v[r]); #pragma omp critical { s.push(make_pair(q, i - 1)); s.push(make_pair(i + 1, r)); } } int main() { int n, x; int numThreads = 4, numBusyThreads = 0; bool *idle = new bool[numThreads]; for(int i = 0; i &lt; numThreads; ++i) idle[i] = true; pair&lt;int, int&gt; p; vector&lt;int&gt; v; cin &gt;&gt; n; for(int i = 0; i &lt; n; ++i) { cin &gt;&gt; x; v.push_back(x); } cout &lt;&lt; v.size() &lt;&lt; endl; s.push(make_pair(0, v.size())); #pragma omp parallel shared(s, v, idle, numThreads, numBusyThreads, p) { bool done = false; while(!done) { int id = omp_get_thread_num(); #pragma omp critical { if(s.empty() == false &amp;&amp; numBusyThreads &lt; numThreads) { ++numBusyThreads; //the current thread is not idle anymore //it will get the interval [q, r] from stack //and run qs on it idle[id] = false; p = s.top(); s.pop(); } if(numBusyThreads == 0) { done = true; } } if(idle[id] == false) { qs(v, p.first, p.second); idle[id] = true; #pragma omp critical --numBusyThreads; } } } return 0; } </code></pre> <p><strong>Algorithm:</strong></p> <p>To use openMP for a recursive function I used a stack to keep track of the next intervals on which the qs function should run. I manually add the 1st interval [0, size] and then let the threads get to work when a new interval is added in the stack.</p> <p><strong>The problem:</strong></p> <p>The program ends too early, not sorting the array after creating the 1st set of intervals ([q, i - 1], [i+1, r] if you look on the code. My guess is that the threads which get the work, considers the local variables of the quicksort function(qs in the code) shared by default, so they mess them up and add no interval in the stack.</p> <p><strong>How I compile:</strong></p> <pre><code>g++ -o qs qs.cc -Wall -fopenmp </code></pre> <p><strong>How I run:</strong></p> <p><code>./qs &lt; in_100000 &gt; out_100000</code></p> <p>where in_100000 is a file containing 100000 on the 1st line followed by 100k intergers on the next line separated by spaces.</p> <p>I am using gcc 4.5.2 on linux</p> <p>Thank you for your help,</p> <p>Dan </p>
0
1,995
Code Igniter PHP Error - Message: Use of undefined constant
<p>Im loading different contents in my main view with my menu, the code is working properly but is i have this error message.</p> <pre><code>A PHP Error was encountered Severity: Notice Message: Use of undefined constant users - assumed 'users' Filename: views/welcome.php Line Number: 53 A PHP Error was encountered Severity: Notice Message: Use of undefined constant stores - assumed 'stores' Filename: views/welcome.php Line Number: 56 A PHP Error was encountered Severity: Notice Message: Use of undefined constant notes - assumed 'notes' Filename: views/welcome.php Line Number: 59 </code></pre> <p>This is my view</p> <pre><code> &lt;div id="nav"&gt; &lt;div id="imagesBox"&gt; &lt;a href="index.php?section=users"&gt;&lt;img class="imagesLeft" src="images/usuario_on.png"&gt;&lt;/a&gt; &lt;a href="index.php?section=stores"&gt;&lt;img class="imagesLeft" src="images/tienda_on.png"&gt;&lt;/a&gt; &lt;a href="index.php?section=notes"&gt;&lt;img class="imagesLeft" src="images/aviso_on.png"&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php $section; $users=0; switch ($_GET['section']) { case users: $this-&gt;load-&gt;view('users'); break; case stores: $this-&gt;load-&gt;view('stores'); break; case notes: $this-&gt;load-&gt;view('notes'); break; } ?&gt; &lt;/div&gt; </code></pre> <p>And this is my controller (im using tank_auth and is working properly)</p> <pre><code>class Welcome extends CI_Controller { function __construct() { parent::__construct(); $this-&gt;load-&gt;helper('url'); $this-&gt;load-&gt;library('tank_auth'); } function index() { if (!$this-&gt;tank_auth-&gt;is_logged_in()) { redirect('/auth/login/'); } else { $data['user_id'] = $this-&gt;tank_auth-&gt;get_user_id(); $data['username'] = $this-&gt;tank_auth-&gt;get_username(); $this-&gt;load-&gt;view('welcome', $data); } } } </code></pre> <p>I dont find the best method to fix this and this is a little weird, because the code is working like i want.</p>
0
1,035
T-SQL How to select min, max and first row from table from duplicate values
<blockquote> <pre><code> DateTime -- Unit -- Client --- Qty 03/02/2013 08:00:01 -- 3 -- 1 --- 1 03/02/2013 08:00:02 -- 3 -- 2 --- 1 03/02/2013 08:00:03 -- 3 -- 3 --- 2 03/02/2013 08:00:04 -- 3 -- 3 --- 2 03/02/2013 08:00:05 -- 3 -- 3 --- 5 03/02/2013 08:00:06 -- 3 -- 3 --- 4 03/02/2013 08:00:07 -- 3 -- 4 --- 6 03/02/2013 08:00:08 -- 3 -- 4 --- 67 03/02/2013 08:00:09 -- 3 -- 4 --- 76 03/02/2013 08:00:10 -- 3 -- 4 --- 76 </code></pre> </blockquote> <p>And I want :</p> <blockquote> <pre><code> DateTime -- Unit -- Client --- Qty 03/02/2013 08:00:01 -- 3 -- 1 --- 1 03/02/2013 08:00:02 -- 3 -- 2 --- 1 03/02/2013 08:00:03 -- 3 -- 3 --- 2 03/02/2013 08:00:05 -- 3 -- 3 --- 5 03/02/2013 08:00:07 -- 3 -- 4 --- 6 03/02/2013 08:00:09 -- 3 -- 4 --- 76 </code></pre> </blockquote> <p>The criteria to filter is get the min and max "Qty" from table and get only the first value when exists duplicate "Qty" values in the same "Unit" and "client" column.</p> <p>I do the follow T-SQL, but the retrieval is the last "Qty" value when the "Unit" and "client" column are the same, I need the first.</p> <pre><code> --1 CREATE TABLE Transact (DateTime DateTime, Unit INT NULL, Client INT NULL, Qty INT NULL ) INSERT INTO Transact (Datetime,Unit,Client,Qty) Values ( '03/02/2013 08:00:01',3,1,1) Values ( '03/02/2013 08:00:02',3,2,1) Values ( '03/02/2013 08:00:03',3,3,2) Values ( '03/02/2013 08:00:04',3,3,2) Values ( '03/02/2013 08:00:05',3,3,5) Values ( '03/02/2013 08:00:06',3,3,4) Values ( '03/02/2013 08:00:07',3,4,6) Values ( '03/02/2013 08:00:08',3,4,67) Values ( '03/02/2013 08:00:09',3,4,76) Values ( '03/02/2013 08:00:10',3,4,76) DECLARE @Total TABLE (DateTime DateTime, Unit INT NULL, Client INT NULL, Qty INT NULL ) DECLARE @Uniques TABLE (DateTime DateTime, Unit INT NULL, Client INT NULL, Qty INT NULL ) DECLARE @Mini TABLE (DateTime DateTime, Unit INT NULL, Client INT NULL, Qty INT NULL ) DECLARE @Maxi TABLE (DateTime DateTime, Unit INT NULL, Client INT NULL, Qty INT NULL ) --2 INSERT INTO @Total SELECT * FROM Transact INSERT INTO @Mini SELECT MIN(Datetime) Datetime,Unit,Client,MIN(Qty) FROM @Total GROUP BY Unit,Client INSERT INTO @Maxi SELECT MAX(Datetime) Datetime,Unit,Client,MAX(Qty) FROM @Total GROUP BY Unit,Client --3 INSERT INTO @Uniques SELECT * FROM @Mini UNION SELECT * FROM @Maxi SELECT * FROM @Uniques </code></pre> <p>Thanks in advance.</p> <p>Pablo Geronimo.</p>
0
1,502
Aggregating Rows Pandas
<p>I am quite new to <code>pandas</code>. I need to aggregate <code>'Names'</code> if they have the same name and then make an average for <code>'Rating'</code> and <code>'NumsHelpful'</code> (without counting <code>NaN</code>). <code>'Review'</code> should get concatenated whilst <code>'Weight(Pounds)'</code>should remain untouched: </p> <pre><code>col names: ['Brand', 'Name', 'NumsHelpful', 'Rating', 'Weight(Pounds)', 'Review'] Name 'Brand' 'Name' 1534 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 1535 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 1536 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 1537 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 1538 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 1539 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 1540 Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 'NumsHelpful' 'Rating' 'Weight' 1534 NaN 2 4.5 1535 NaN 2 4.5 1536 NaN NaN 4.5 1537 NaN NaN 4.5 1538 2 NaN 4.5 1539 3 5 4.5 1540 5 NaN 4.5 'Review' 1534 Yummy - Delish 1535 The best Bloody Mary mix! - The best Bloody Ma... 1536 Best Taste by far - I've tried several if not ... 1537 Best bloody mary mix ever - This is also good ... 1538 Outstanding - Has a small kick to it but very ... 1539 OMG! So Good! - Spicy, terrific Bloody Mary mix! 1540 Good stuff - This is the best </code></pre> <p>So the output should be something like this:</p> <pre><code> 'Brand' 'Name' 'NumsHelpful' 'Rating' Zing Zang Zing Zang Bloody Mary Mix, 32 fl oz 3.33 3 'Weight' 'Review' 4.5 Review1 / Review2 / ... / ReviewN </code></pre> <p>How shall I procede? Thanks.</p>
0
1,264
The method getApplicationContext() is undefined - fragment issues
<p>I am getting the following errors: The method getApplicationContext() is undefined The method findViewById(int) is undefined for the type Fragment1</p> <p>These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too sure how to work this out.</p> <p>Any help would be greatly appreciated. Thanks in advance.</p> <p>Below is the code</p> <pre><code>public class Fragment1 extends Fragment { private String currentUserId; private ArrayAdapter&lt;String&gt; namesArrayAdapter; private ArrayList&lt;String&gt; names; private ListView usersListView; private Button logoutButton; String userGender = ParseUser.getCurrentUser().getString("Gender"); String activityName = ParseUser.getCurrentUser().getString("ActivityName"); Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance"); String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender"); Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age"); Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age"); Number userage = ParseUser.getCurrentUser().getNumber("Age"); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub if (container == null){ return null; } return (LinearLayout)inflater.inflate(R.layout.fragment1_layout, container,false); logoutButton = (Button) findViewById(R.id.logoutButton); logoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ParseUser.logOut(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); startActivity(intent); } }); setConversationsList(); } private void setConversationsList() { currentUserId = ParseUser.getCurrentUser().getObjectId(); names = new ArrayList&lt;String&gt;(); // String userActivitySelectionName = null; ParseQuery&lt;ParseUser&gt; query = ParseUser.getQuery(); // query.whereEqualTo("ActivityName",userActivitySelectionName); query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId()); // users with Gender = currentUser.Looking_Gender query.whereEqualTo("Gender", userLookingGender); // users with Looking_Gender = currentUser.Gender query.whereEqualTo("Looking_Gender", userGender); query.setLimit(1); query.whereEqualTo("ActivityName", activityName); query.whereGreaterThanOrEqualTo("Minimum_Age", minimumAge).whereGreaterThanOrEqualTo("Age", userage); query.whereLessThanOrEqualTo("Maximum_Age", maximumAge).whereLessThanOrEqualTo("Age", userage); // query.whereWithinKilometers("Maximum_Distance", point, maxDistance) query.findInBackground(new FindCallback&lt;ParseUser&gt;() { public void done(List&lt;ParseUser&gt; userList, ParseException e) { if (e == null) { for (int i=0; i&lt;userList.size(); i++) { names.add(userList.get(i).get("Name").toString()); names.add(userList.get(i).get("Headline").toString()); names.add(userList.get(i).get("Age").toString()); // names.add(userList.get(i).getParseObject("ProfilePicture").; } usersListView = (ListView)findViewById(R.id.usersListView); namesArrayAdapter = new ArrayAdapter&lt;String&gt;(getApplicationContext(), R.layout.user_list_item, names); usersListView.setAdapter(namesArrayAdapter); usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; a, View v, int i, long l) { openConversation(names, i); } }); } else { Toast.makeText(getApplicationContext(), "Error loading user list", Toast.LENGTH_LONG).show(); } } }); } public void openConversation(ArrayList&lt;String&gt; names, int pos) { ParseQuery&lt;ParseUser&gt; query = ParseUser.getQuery(); query.whereEqualTo("Name", names.get(pos)); query.findInBackground(new FindCallback&lt;ParseUser&gt;() { public void done(List&lt;ParseUser&gt; user, ParseException e) { if (e == null) { Intent intent = new Intent(getApplicationContext(), MessagingActivity.class); intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId()); startActivity(intent); } else { Toast.makeText(getApplicationContext(), "Error finding that user", Toast.LENGTH_SHORT).show(); } } }); } } </code></pre> <p>Update Unreachable code error for setConversationList</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub if (container == null){ return null; } return (LinearLayout)inflater.inflate(R.layout.fragment1_layout, container,false); setConversationsList(); } private void setConversationsList() { currentUserId = ParseUser.getCurrentUser().getObjectId(); names = new ArrayList&lt;String&gt;(); // String userActivitySelectionName = null; ParseQuery&lt;ParseUser&gt; query = ParseUser.getQuery(); </code></pre> <p>Update </p> <p>Upon launching the activity, I received the following message:</p> <pre><code>08-15 14:52:16.365: E/AndroidRuntime(3332): FATAL EXCEPTION: main 08-15 14:52:16.365: E/AndroidRuntime(3332): Process: com.dooba.beta, PID: 3332 08-15 14:52:16.365: E/AndroidRuntime(3332): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.usermatch}: java.lang.NullPointerException 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.access$800(ActivityThread.java:135) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.os.Handler.dispatchMessage(Handler.java:102) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.os.Looper.loop(Looper.java:136) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.main(ActivityThread.java:5017) 08-15 14:52:16.365: E/AndroidRuntime(3332): at java.lang.reflect.Method.invokeNative(Native Method) 08-15 14:52:16.365: E/AndroidRuntime(3332): at java.lang.reflect.Method.invoke(Method.java:515) 08-15 14:52:16.365: E/AndroidRuntime(3332): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 08-15 14:52:16.365: E/AndroidRuntime(3332): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 08-15 14:52:16.365: E/AndroidRuntime(3332): at dalvik.system.NativeStart.main(Native Method) 08-15 14:52:16.365: E/AndroidRuntime(3332): Caused by: java.lang.NullPointerException 08-15 14:52:16.365: E/AndroidRuntime(3332): at com.dooba.beta.usermatch.initialisePaging(usermatch.java:32) 08-15 14:52:16.365: E/AndroidRuntime(3332): at com.dooba.beta.usermatch.onCreate(usermatch.java:20) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.Activity.performCreate(Activity.java:5231) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 08-15 14:52:16.365: E/AndroidRuntime(3332): ... 11 more </code></pre> <p>Below is the activity page that calls for the fragment</p> <pre><code>import java.util.List; import java.util.Vector; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; public class usermatch extends FragmentActivity { private PageAdapter mPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.viewpager_layout); initialisePaging(); } private void initialisePaging() { // TODO Auto-generated method stub List&lt;Fragment&gt; fragments = new Vector&lt;Fragment&gt;(); fragments.add(Fragment.instantiate(this, Fragment1.class.getName())); fragments.add(Fragment.instantiate(this, Fragment2.class.getName())); fragments.add(Fragment.instantiate(this, Fragment3.class.getName())); mPagerAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments); ViewPager pager = (ViewPager) findViewById(R.id.viewpager); pager.setAdapter(mPagerAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.mood, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre> <p><strong>Update 2</strong> Below is the message I receive in logcat</p> <pre><code>08-15 17:42:28.863: E/AndroidRuntime(4974): FATAL EXCEPTION: main 08-15 17:42:28.863: E/AndroidRuntime(4974): Process: com.dooba.beta, PID: 4974 08-15 17:42:28.863: E/AndroidRuntime(4974): java.lang.NullPointerException 08-15 17:42:28.863: E/AndroidRuntime(4974): at com.dooba.beta.Fragment1$1.done(Fragment1.java:108) 08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.FindCallback.internalDone(FindCallback.java:45) 08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.FindCallback.internalDone(FindCallback.java:1) 08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.Parse$6$1.run(Parse.java:888) 08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Handler.handleCallback(Handler.java:733) 08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Handler.dispatchMessage(Handler.java:95) 08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Looper.loop(Looper.java:136) 08-15 17:42:28.863: E/AndroidRuntime(4974): at android.app.ActivityThread.main(ActivityThread.java:5017) 08-15 17:42:28.863: E/AndroidRuntime(4974): at java.lang.reflect.Method.invokeNative(Native Method) 08-15 17:42:28.863: E/AndroidRuntime(4974): at java.lang.reflect.Method.invoke(Method.java:515) 08-15 17:42:28.863: E/AndroidRuntime(4974): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 08-15 17:42:28.863: E/AndroidRuntime(4974): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 08-15 17:42:28.863: E/AndroidRuntime(4974): at dalvik.system.NativeStart.main(Native Method) </code></pre>
0
4,832
HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process ASP.NET Core 3
<p>From this morning without any changes to the code of the project, a very simple Web API, one controller and 3 methods, with Swagger, it doesn't start anymore and I get the error:</p> <blockquote> <p>HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process</p> </blockquote> <p>Event viewer report the most useless message:</p> <blockquote> <p>IIS Express AspNetCore Module V2: Failed to start application '/LM/W3SVC/2/ROOT/docs', ErrorCode '0x80004005'.</p> </blockquote> <p>Restarted the system several times.</p> <p>I'm using Visual Studio 2019, the application successfully compile and a few minutes ago it was working fine. No new software has been installed, no packages added. Tried also clean and rebuild.</p> <p>I've just modified the comment of a method. Obviously I've tried also to restore the previous comment but I get always the same message.</p> <p>What can I do?</p> <p>Is net core still too unstable to be used professionally?</p> <p><strong>UPDATE</strong></p> <p>The same code launched from the same version of Visual Studio but in another PC runs properly.</p> <p><strong>UPDATE 2</strong></p> <p>Below the code of the application:</p> <p>startup.cs</p> <pre><code>using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using System; using System.IO; using System.Reflection; namespace WFP_GeoAPIs { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c =&gt; { c.SwaggerDoc("v1", new OpenApiInfo() { Title = "Geographic APIs", Version = "v1.0.0" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "swagger-ui")), RequestPath = "/swagger-ui" }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(c =&gt; { c.SwaggerEndpoint("/swagger/v1/swagger.json", "GeoAPIs Ver 1.0.0"); c.RoutePrefix = "docs"; c.InjectStylesheet("/swagger-ui/custom.css"); }); } } } </code></pre> <p>Here is the launchsettings.json:</p> <pre><code>{ "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:51319", "sslPort": 44345 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "docs", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "WFP_GeoAPIs": { "commandName": "Project", "launchBrowser": true, "launchUrl": "docs", "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } </code></pre> <p>but coping the project on another PC with the same Visual Studio version works fine, so it looks like the is a configuration bug in the .NET Core or VIsual Studio property...</p>
0
1,814
Parallax and Pin collapse modes not working in Collapsing Toolbar Layout
<p>This is my code of my test project:- Main Activity</p> <pre><code> package com.invento.defcomm.collapsingtoolbarlayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private CollapsingToolbarLayout collapsingToolbarLayout; public static final int COLLAPSE_MODE_PARALLAX=2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar= (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); collapsingToolbarLayout= (CollapsingToolbarLayout) findViewById(R.id.collpasing_toolbar); collapsingToolbarLayout.setTitle("TEST COLLAPSING TOOLBAR"); collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.expandedTitleColor)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } </code></pre> <p>}</p> <p>activity main xml file:</p> <pre><code> &lt;android.support.design.widget.CoordinatorLayout 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"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/app_bar_layout" android:layout_width="match_parent" android:layout_height="192dp"&gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collpasing_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:contentScrim="@color/contentscrim" app:layout_scrollFlags="scroll|exitUntilCollapsed"&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="192dp" android:scaleType="centerCrop" android:src="@drawable/index" app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="0.7"/&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:layout_collapseMode="pin" /&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>color xml file:-</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;color name="contentscrim"&gt;#846735&lt;/color&gt; &lt;color name="expandedTitleColor"&gt;#ffffff&lt;/color&gt; &lt;/resources&gt; </code></pre> <p>style xml file:-</p> <pre><code> &lt;resources&gt; &lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;!-- Customize your theme here. --&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>The problem is that the activity loads up fine. There is no error in there. But the Parallax scroll effect is not working. Is there something I 'm missing? Please point it out. </p>
0
1,572
Rspec doesn't see my model Class. uninitialized constant error
<p>I'm writing tests on Rspec for my models in Ruby on Rails application. And I receive this error while starting 'rspec spec' </p> <pre><code>command: /spec/models/client_spec.rb:4:in `&lt;top (required)&gt;': uninitialized constant Client (NameError) </code></pre> <p>I use Rails 4.0.0 and Ruby 2.0.0</p> <p>Here is my client_spec.rb:</p> <pre><code>require 'spec_helper' describe Client do it 'is invalid without first_name', :focus =&gt; true do client = Client.new client.should_not be_valid end end </code></pre> <p>And Gemfile:</p> <pre><code>source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.0.0.rc1' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use SCSS for stylesheets gem 'sass-rails', '~&gt; 4.0.0.rc1' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '&gt;= 1.3.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~&gt; 4.0.0' # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: gem 'turbolinks' gem 'jbuilder', '~&gt; 1.0.1' group :development do gem 'rspec-rails' end group :doc do # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', require: false end group :test do gem 'rspec-rails' gem 'factory_girl_rails' gem 'database_cleaner' end </code></pre> <p>And at last client.rb (ROR Model and Class):</p> <pre><code>class Client &lt; ActiveRecord::Base has_many :cars has_many :orders has_one :client_status has_one :discount_plan, through: :client_status validates :email, format: { with: /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})\z/, :message =&gt; "Only emails allowed", :multiline =&gt; true } validates :email, presence: true, if: "phone.nil?" #validates :phone, presence: true, if: "email.nil?" validates :last_name, :first_name, presence: true validates :last_name, :first_name, length: { minimum: 2, maximum: 500, wrong_length: "Invalid length", too_long: "%{count} characters is the maximum allowed", too_short: "must have at least %{count} characters" } end </code></pre> <p>If it'd be useful my spec_helper.rb file:</p> <pre><code># This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' #config.use_transactional_fixtures = false config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end </code></pre>
0
1,273
Rendering HTML+Javascript server-side
<p>I need to render an HTML page server-side and "extract" the raw bytes of a canvas element so I can save it to a PNG. Problem is, the canvas element is created from javascript (I'm using jquery's Flot to generate a chart, basically). So I guess I need a way to "host" the DOM+Javascript functionality from a browser without actually using the browser. I settled on mshtml (but open to any and all suggestions) as it seems that it should be able to to exactly that. This is an ASP.NET MVC project. </p> <p>I've searched far and wide and haven't seen anything conclusive. </p> <p>So I have this simple HTML - example kept as simple as possible to demonstrate the problem - </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Wow&lt;/title&gt; &lt;script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="hello"&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; function simple() { $("#hello").append("&lt;p&gt;Hello&lt;/p&gt;"); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>which produces the expected output when run from a browser. </p> <p>I want to be able to load the original HTML into memory, execute the javascript function, then manipulate the final DOM tree. I cannot use any System.Windows.WebBrowser-like class, as my code needs to run in a service environment. </p> <p>So here's my code:</p> <pre><code>IHTMLDocument2 domRoot = (IHTMLDocument2)new HTMLDocument(); using (WebClient wc = new WebClient()) { using (var stream = new StreamReader(wc.OpenRead((string)url))) { string html = stream.ReadToEnd(); domRoot.write(html); domRoot.close(); } } while (domRoot.readyState != "complete") Thread.Sleep(SleepTime); string beforeScript = domRoot.body.outerHTML; IHTMLWindow2 parentWin = domRoot.parentWindow; parentWin.execScript("simple"); while (domRoot.readyState != "complete") Thread.Sleep(SleepTime); string afterScript = domRoot.body.outerHTML; System.Runtime.InteropServices.Marshal.FinalReleaseComObject(domRoot); domRoot = null; </code></pre> <p>The problem is, "beforeScript" and "afterScript" are exactly the same. The IHTMLDocument2 instance goes through the normal "uninitialized", "loading", "complete" cycle, no errors are thrown, nothing.</p> <p>Anybody have any ideas on what I'm doing wrong? Completely lost here. </p>
0
1,049
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4729395/c-error-free-invalid-next-size-fast">C++ Error: free(): invalid next size (fast):</a></p> </blockquote> <p><em>That's a C++ question (albeit a 'C++ being abused' question). Alternative duplicate: <a href="https://stackoverflow.com/questions/2317021/facing-an-error-glibc-detected-free-invalid-next-size-fast">Facing an error: glibc detected free invalid next size (fast)</a></em></p> <hr> <p>I am using a Linux tool to generate some n/w traffic but getting this error when i try to send data greater than some length while the tool has provision for it.</p> <p>My whole project has stuck in between. As I have not created the tool so not sure where exactly is the error occurring... and this error(even <code>gdb</code>) is not giving any hint regarding where is the problem.How to detect the point of error?</p> <p>I am giving some snapshots of the problem if they help. Please guide me how should I proceed? It's looking like a mesh to me.</p> <pre><code>udit@udit-Dabba ~ $ sendip -v -p ipv6 -f file.txt -6s ::1 -p esp -es 0x20 -eq 0x40 -ei abcd -eI zxc -p tcp -ts 21 -td 21 ::2 | more *** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 *** ======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6(+0x6b961)[0x17b961] /lib/i386-linux-gnu/libc.so.6(+0x6d28b)[0x17d28b] /lib/i386-linux-gnu/libc.so.6(cfree+0x6d)[0x18041d] /lib/i386-linux-gnu/libc.so.6(fclose+0x14a)[0x16b9ca] /lib/i386-linux-gnu/libc.so.6(+0xe053f)[0x1f053f] /lib/i386-linux-gnu/libc.so.6(__res_ninit+0x25)[0x1f0815] /lib/i386-linux-gnu/libc.so.6(__res_maybe_init+0x130)[0x1f1810] /lib/i386-linux-gnu/libc.so.6(__nss_hostname_digits_dots+0x34)[0x1f37d4] /lib/i386-linux-gnu/libc.so.6(gethostbyname2+0x96)[0x1f82f6] /usr/local/lib/sendip/ipv6.so(set_addr+0x2d)[0x3eec69] sendip(main+0x8eb)[0x804a635] /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x126e37] sendip[0x8048f81] ======= Memory map: ======== 00110000-0026a000 r-xp 00000000 08:07 3408705 /lib/i386-linux-gnu/libc-2.13.so 0026a000-0026b000 ---p 0015a000 08:07 3408705 /lib/i386-linux-gnu/libc-2.13.so 0026b000-0026d000 r--p 0015a000 08:07 3408705 /lib/i386-linux-gnu/libc-2.13.so 0026d000-0026e000 rw-p 0015c000 08:07 3408705 /lib/i386-linux-gnu/libc-2.13.so 0026e000-00271000 rw-p 00000000 00:00 0 002d6000-002da000 r-xp 00000000 08:07 923078 /usr/local/lib/sendip/tcp.so 002da000-002db000 r--p 00003000 08:07 923078 /usr/local/lib/sendip/tcp.so 002db000-002dc000 rw-p 00004000 08:07 923078 /usr/local/lib/sendip/tcp.so 002dc000-002e0000 rw-p 00000000 00:00 0 003ee000-003f0000 r-xp 00000000 08:07 923076 /usr/local/lib/sendip/ipv6.so 003f0000-003f1000 r--p 00001000 08:07 923076 /usr/local/lib/sendip/ipv6.so 003f1000-003f2000 rw-p 00002000 08:07 923076 /usr/local/lib/sendip/ipv6.so 005fd000-00621000 r-xp 00000000 08:07 3408742 /lib/i386-linux-gnu/libm-2.13.so 00621000-00622000 r--p 00023000 08:07 3408742 /lib/i386-linux-gnu/libm-2.13.so 00622000-00623000 rw-p 00024000 08:07 3408742 /lib/i386-linux-gnu/libm-2.13.so 006f7000-006fa000 r-xp 00000000 08:07 919265 /usr/local/lib/sendip/esp.so 006fa000-006fb000 r--p 00002000 08:07 919265 /usr/local/lib/sendip/esp.so 006fb000-006fc000 rw-p 00003000 08:07 919265 /usr/local/lib/sendip/esp.so 006fc000-00700000 rw-p 00000000 00:00 0 0081a000-00836000 r-xp 00000000 08:07 3408692 /lib/i386-linux-gnu/ld-2.13.so 00836000-00837000 r--p 0001b000 08:07 3408692 /lib/i386-linux-gnu/ld-2.13.so 00837000-00838000 rw-p 0001c000 08:07 3408692 /lib/i386-linux-gnu/ld-2.13.so 0091d000-0091f000 r-xp 00000000 08:07 3408715 /lib/i386-linux-gnu/libdl-2.13.so 0091f000-00920000 r--p 00001000 08:07 3408715 /lib/i386-linux-gnu/libdl-2.13.so 00920000-00921000 rw-p 00002000 08:07 3408715 /lib/i386-linux-gnu/libdl-2.13.so 009e7000-00a01000 r-xp 00000000 08:07 3408733 /lib/i386-linux-gnu/libgcc_s.so.1 00a01000-00a02000 r--p 00019000 08:07 3408733 /lib/i386-linux-gnu/libgcc_s.so.1 00a02000-00a03000 rw-p 0001a000 08:07 3408733 /lib/i386-linux-gnu/libgcc_s.so.1 00fb3000-00fb4000 r-xp 00000000 00:00 0 [vdso] 08048000-0804e000 r-xp 00000000 08:07 923064 /usr/local/bin/sendip 0804e000-0804f000 r--p 00005000 08:07 923064 /usr/local/bin/sendip 0804f000-08050000 rw-p 00006000 08:07 923064 /usr/local/bin/sendip 08050000-08054000 rw-p 00000000 00:00 0 09da1000-09dc2000 rw-p 00000000 00:00 0 [heap] b7600000-b7621000 rw-p 00000000 00:00 0 b7621000-b7700000 ---p 00000000 00:00 0 b77ce000-b77d0000 rw-p 00000000 00:00 0 b77e1000-b77e2000 rw-p 00000000 00:00 0 b77e2000-b77e3000 r--s 00000000 08:07 3148711 /home/udit/file.txt b77e3000-b77e5000 rw-p 00000000 00:00 0 bfb5a000-bfb7b000 rw-p 00000000 00:00 0 [stack] esp Added 43 options Initializing module ipv6 Initializing module esp Initializing module tcp </code></pre> <p>My glibc version ..</p> <pre><code>udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2 $ ldd --version ldd (Ubuntu EGLIBC 2.13-0ubuntu13) 2.13 ... </code></pre> <p>It's an open source tool sendip and I am trying to generate ipsec traffic. If any code portion will be required I will add it here but don't have time to report the bug and wait for it to be fixed because acc. to the tool specifications i choose it for my purpose and now I am completely stuck in between. Please guide me for this.</p> <p>I know it's almost impossible to tell what is the error and where it is without even looking at the code. I am just asking for your help and suggestion what should I do in this situation because its not even completely my mistake.</p> <p><strong>If anyone could tell me any tool which could tell me where exactly is the problem ????</strong></p> <p>I am not even sure whether the question is suitable for here; if not please tell me where to migrate it?</p> <p>As suggested I tried with <code>valgrind</code>. I never even heard about it before so no idea how to proceed with here is the output. Please guide me how to go about it further?</p> <pre><code> udit@udit-Dabba ~ $ valgrind --leak-check=yes sendip -v -p ipv6 -f file.txt -6s ::1 -p esp -es 0x20 -eq 0x40 -ei abcd -eI zxc -p tcp -ts 21 -td 21 ::2 ==12444== Memcheck, a memory error detector ==12444== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==12444== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info ==12444== Command: sendip -v -p ipv6 -f file.txt -6s ::1 -p esp -es 0x20 -eq 0x40 -ei abcd -eI zxc -p tcp -ts 21 -td 21 ::2 ==12444== esp Added 43 options Initializing module ipv6 Initializing module esp Initializing module tcp ==12444== Invalid write of size 1 ==12444== at 0x4027F40: memcpy (mc_replace_strmem.c:635) ==12444== by 0x4032269: do_opt (esp.c:113) ==12444== by 0x804A51D: main (sendip.c:575) ==12444== Address 0x41cec5c is 5 bytes after a block of size 23 alloc'd ==12444== at 0x402699A: realloc (vg_replace_malloc.c:525) ==12444== by 0x4032231: do_opt (esp.c:111) ==12444== by 0x804A51D: main (sendip.c:575) ==12444== Finalizing module tcp Finalizing module esp Finalizing module ipv6 Final packet data: 60 00 00 00 `... 00 5B 32 20 .[2 /*rest packet content*/ 65 66 0A 0A ef.. 00 00 02 06 .... 1E 97 1E ... Couldn't open RAW socket: Operation not permitted Freeing module ipv6 Freeing module esp Freeing module tcp ==12444== ==12444== HEAP SUMMARY: ==12444== in use at exit: 16 bytes in 1 blocks ==12444== total heap usage: 118 allocs, 117 frees, 8,236 bytes allocated ==12444== ==12444== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==12444== at 0x40268A4: malloc (vg_replace_malloc.c:236) ==12444== by 0x4031F47: ??? ==12444== by 0x804A34F: main (sendip.c:517) ==12444== ==12444== LEAK SUMMARY: ==12444== definitely lost: 16 bytes in 1 blocks ==12444== indirectly lost: 0 bytes in 0 blocks ==12444== possibly lost: 0 bytes in 0 blocks ==12444== still reachable: 0 bytes in 0 blocks ==12444== suppressed: 0 bytes in 0 blocks ==12444== ==12444== For counts of detected and suppressed errors, rerun with: -v ==12444== ERROR SUMMARY: 4 errors from 2 contexts (suppressed: 30 from 11) </code></pre>
0
3,484
Failed to Load Plugin Vue in eslintrc.js When Building
<p>Dockerfile runs <code>RUN npm run build</code> which runs <code>vue-cli-service build</code>. After some time, I get an error from <code>.eslintrc.js</code>:</p> <p>Failed to load plugin 'vue' declared in '.eslintrc.js': createRequire is not a function. Build does not get completed because of this issue.</p> <p>This issue does not occur if I run <code>npm run build</code> manually. Why do I get this issue and How can I resolve it?</p> <p><code>.eslintrc.js</code>:</p> <pre><code>module.exports = { root: true, env: { node: true }, extends: ['plugin:vue/essential', '@vue/airbnb', '@vue/prettier'], rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'consistent-return': 0, 'import/extensions': 0, 'import/no-extraneous-dependencies': 0, 'no-param-reassign': 0, 'no-alert': 0, 'no-unused-expressions': 0, 'no-shadow': 0, 'no-return-assign': 0 }, plugins: ['prettier'], parserOptions: { parser: 'babel-eslint' } }; </code></pre> <p><code>package.json</code>:</p> <pre><code>{ "name": "web", "version": "0.1.0", "private": true, "scripts": { "build": "vue-cli-service build", "lint": "vue-cli-service lint", "start": "vue-cli-service serve" }, "dependencies": { "axios": "^0.19.2", "core-js": "^3.6.5", "date-fns": "^2.14.0", "humps": "^2.0.1", "izitoast": "^1.4.0", "lamejs": "^1.2.0", "pug-plain-loader": "^1.0.0", "register-service-worker": "^1.7.1", "sass": "^1.26.5", "sass-loader": "^8.0.2", "vue": "^2.6.11", "vue-resource": "^1.5.1", "vue-router": "^3.2.0", "vuex": "^3.4.0", }, "devDependencies": { "@vue/cli-plugin-babel": "^4.3.1", "@vue/cli-plugin-eslint": "^4.3.1", "@vue/cli-plugin-pwa": "^4.3.1", "@vue/cli-service": "^4.3.1", "@vue/eslint-config-airbnb": "^5.0.2", "@vue/eslint-config-prettier": "^6.0.0", "babel-eslint": "^10.1.0", "compression-webpack-plugin": "^4.0.0", "eslint": "^7.0.0", "eslint-plugin-prettier": "^3.1.3", "eslint-plugin-vue": "^6.2.2", "expose-loader": "^0.7.5", "material-design-icons-iconfont": "^5.0.1", "node-sass": "^4.14.1", "vue-cli-plugin-vuetify": "^2.0.5", "vue-template-compiler": "^2.6.11", "vuetify-loader": "^1.4.3", "webpack-bundle-analyzer": "^3.8.0" } } </code></pre>
0
1,232
java.lang.ClassNotFoundException: org.apache.commons.lang.UnhandledException
<p>while running the tomcat, I am getting error like this: (In code, up to controller, it is working fine, but when it comes to JSP page, it is giving error) please, can any one help?</p> <pre><code>Oct 30, 2013 4:48:16 PM org.apache.catalina.core.ApplicationDispatcher invoke SEVERE: Servlet.service() for servlet jsp threw exception java.lang.ClassNotFoundException: org.apache.commons.lang.UnhandledException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526) at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404) at java.lang.Class.getConstructor0(Class.java:2714) at java.lang.Class.newInstance0(Class.java:343) at java.lang.Class.newInstance(Class.java:325) at com.sun.beans.finder.InstanceFinder.instantiate(InstanceFinder.java:96) at com.sun.beans.finder.InstanceFinder.find(InstanceFinder.java:66) at java.beans.Introspector.findExplicitBeanInfo(Introspector.java:455) at java.beans.Introspector.&lt;init&gt;(Introspector.java:405) at java.beans.Introspector.getBeanInfo(Introspector.java:174) at org.apache.jasper.compiler.Generator$TagHandlerInfo.&lt;init&gt;(Generator.java:3911) at org.apache.jasper.compiler.Generator$GenerateVisitor.getTagHandlerInfo(Generator.java:2174) at org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1632) at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530) at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361) at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411) at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417) at org.apache.jasper.compiler.Node$Root.accept(Node.java:495) at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361) at org.apache.jasper.compiler.Generator.generate(Generator.java:3461) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:231) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:551) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:488) at com.preva.controller.OverspeedDBProcess.service(OverspeedDBProcess.java:86) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760) at java.lang.Thread.run(Thread.java:722) </code></pre> <p>Controller like this </p> <pre><code>package com.preva.controller; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.preva.dao.UserDAO; import com.preva.vo.OverspeedDetails; /** * Servlet implementation class OverspeedDBProcess */ public class OverspeedDBProcess extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public OverspeedDBProcess() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try{ response.setContentType("text/html"); PrintWriter out=response.getWriter(); HttpSession session=request.getSession(true); String accountID=(String)session.getAttribute("sessionId"); String deviceID=request.getParameter("vehicleId"); String fromDate=request.getParameter("AnotherDate"); String toDate=request.getParameter("ADate"); String stringspeed=request.getParameter("speed").substring(1,3); double speed=Double.parseDouble(stringspeed); session.setAttribute("vid",deviceID); session.setAttribute("fromdate",fromDate); session.setAttribute("startdate",toDate); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date startD = (Date) sdf.parse(fromDate); Date endD = (Date) sdf.parse(toDate); Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(startD); cal2.setTime(endD); long timestamp1,timestamp2; timestamp1=cal1.getTimeInMillis()/1000; timestamp2=cal2.getTimeInMillis()/1000; System.out.println("::::"+timestamp1); System.out.println("::::"+timestamp2); String Timestamp1 = Long.toString(timestamp1); String Timestamp2 = Long.toString(timestamp2); UserDAO rdao=new UserDAO(); List&lt;OverspeedDetails&gt; overspeeddetail=rdao.getosDetails(accountID, deviceID, Timestamp1, Timestamp2,speed); if(!(overspeeddetail.isEmpty())){ session.setAttribute("overspeeddetails", overspeeddetail); RequestDispatcher rd=request.getRequestDispatcher("OverspeedDBReport.jsp"); rd.include(request,response); return; } RequestDispatcher rd=request.getRequestDispatcher("DataNotFound.jsp"); rd.include(request,response); }catch (Exception e) { // TODO: handle exception } } } </code></pre> <p>Jsp page like this </p> <pre><code>&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt; &lt;%@ page import = "com.preva.vo.StoppageDetails"%&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt; &lt;%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %&gt; &lt;%@ taglib uri="http://displaytag.sf.net" prefix="display" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;link href="css/cal.css" rel="stylesheet" type="text/css" /&gt; &lt;link href="css/sty.css" rel="stylesheet" type="text/css" /&gt; &lt;link href="css/tabborder.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;jsp:include page="Header.jsp" /&gt; &lt;table align=center border=0 cellspacing=0 cellpadding=0&gt; &lt;tr &gt;&lt;td colSpan=5 align=center&gt;&lt;b&gt;Overspeed Details&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr &gt;&lt;td colspan=5 align=center&gt;&lt;b&gt;&lt;%=request.getParameter("vehicleId") %&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;From &amp;nbsp;&lt;%=session.getAttribute("fromdate") %&gt;&amp;nbsp;to&amp;nbsp;&lt;%=session.getAttribute("startdate") %&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;&lt;br&gt;&lt;/br&gt; &lt;table class='rptTbl_sortable' width='80%' align=center cellspacing='2' cellpadding='0' border='0'&gt; &lt;thead&gt; &lt;tr class="rptHdrRow"&gt; &lt;th id="index" class="rptHdrCol_sort" nowrap&gt;DeviceID&lt;/th&gt; &lt;th id="date" class="rptHdrCol_sort" nowrap&gt;Date&lt;/th&gt; &lt;th id="time" class="rptHdrCol_sort" nowrap&gt;Speed&lt;/th&gt; &lt;th id="statusdesc" class="rptHdrCol_sort" nowrap&gt;Status&lt;/th&gt; &lt;th id="address" class="rptHdrCol_sort" nowrap&gt;Address&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;display:table id="deviceDetailsID" name="sessionScope.overspeeddetails" pagesize="10" style="width:99%;"&gt; &lt;display:setProperty name="basic.empty.showtable" value="true" /&gt; &lt;display:setProperty name="paging.banner.group_size" value="10" /&gt; &lt;display:setProperty name="paging.banner.item_name" value="user" /&gt; &lt;display:setProperty name="paging.banner.item_names" value="users" /&gt; &lt;display:column property="deviceID" title="Device ID" sortable="true" headerClass="sortable" style="width: 1%"/&gt; &lt;display:column property="TIMESTAMP" title="TIMESTAMP" sortable="true" headerClass="sortable" format="{0,date,dd-MM-yyyy}"/&gt; &lt;display:column property="speed" title="Speed" sortable="true"/&gt; &lt;display:column property="statuscode" title="Status Code"/&gt; &lt;display:column property="address" title="Address" sortable="true" headerClass="sortable" /&gt; &lt;/display:table&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; </code></pre>
0
4,742
Exporting HTML table into excel using javascript
<p>I have table with 4 columns where every column includes text field and button and at the end of every row consists of edit and delete button. I want to export the table into excel format but when I do the text field and button at the column header and edit and delete button are also getting exported into excel file which I dont want. Can any one tell me where I am making the mistake in javascript, please.</p> <p>Here is my jquery code which I got it from net (<a href="http://jsfiddle.net/insin/cmewv/" rel="nofollow">http://jsfiddle.net/insin/cmewv/</a>)</p> <pre><code>&lt;script type="text/javascript"&gt; var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = '&lt;html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"&gt;&lt;head&gt;&lt;!--[if gte mso 9]&gt;&lt;xml&gt;&lt;x:ExcelWorkbook&gt;&lt;x:ExcelWorksheets&gt;&lt;x:ExcelWorksheet&gt;&lt;x:Name&gt;{worksheet}&lt;/x:Name&gt;&lt;x:WorksheetOptions&gt;&lt;x:DisplayGridlines/&gt;&lt;/x:WorksheetOptions&gt;&lt;/x:ExcelWorksheet&gt;&lt;/x:ExcelWorksheets&gt;&lt;/x:ExcelWorkbook&gt;&lt;/xml&gt;&lt;![endif]--&gt;&lt;/head&gt;&lt;body&gt;&lt;table&gt;{table}&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })() &lt;/script&gt; </code></pre> <p>my HTML code as follows </p> <pre><code>&lt;TABLE id="table_id" class="display" align="Center" border="1px" width="80%"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; &lt;b&gt;User_ID &lt;/th&gt;&lt;/b&gt; &lt;form action="SearchId" method="post"&gt; &lt;input type="hidden" name="hiddenname" value="hidden_uid" &gt; &lt;input type="text" name="uid" id="uid"&gt; &lt;input type="submit" value="Search"&gt; &lt;/form&gt; &lt;th&gt;&lt;b&gt;User_Name &lt;/th&gt;&lt;/b&gt; &lt;form action="SearchId" method="post"&gt; &lt;input type="text" name="uname" id="uname"&gt; &lt;input type="hidden" name="hiddenname" value="hidden_uname" &gt; &lt;input type="submit" value="Search"&gt; &lt;/form&gt; &lt;th&gt;&lt;b&gt;Password&lt;/th&gt;&lt;/b&gt; &lt;form action="SearchId" method="post"&gt; &lt;input type="text" name="pass" id="pass"&gt; &lt;input type="hidden" name="hiddenname" value="hidden_pass" &gt; &lt;input type="submit" value="Search"&gt; &lt;/form&gt; &lt;th&gt;&lt;b&gt;Designation&lt;/th&gt;&lt;/b&gt; &lt;form action="SearchId" method="post"&gt; &lt;input type="text" name="desig" id="desig"&gt; &lt;input type="hidden" name="hiddenname" value="hidden_desig" &gt; &lt;input type="submit" value="Search"&gt; &lt;/form&gt; &lt;/thead&gt; &lt;tbody &gt; &lt;%Iterator itr;%&gt; &lt;%List data=(List) request.getAttribute("UserData"); for(itr=data.iterator();itr.hasNext();) {%&gt; &lt;tr&gt; &lt;% String s= (String) itr.next(); %&gt; &lt;td&gt;&lt;%=s %&gt;&lt;/td&gt; &lt;td&gt;&lt;%=itr.next() %&gt;&lt;/td&gt; &lt;td&gt;&lt;%=itr.next() %&gt;&lt;/td&gt; &lt;td&gt;&lt;%=itr.next() %&gt;&lt;/td&gt; &lt;form id="edit" action="EditRecord" method="post" &gt; &lt;td&gt;&lt;input type="hidden" name="hidden_edit" id="edit_id" value="&lt;%=s %&gt;"/&gt; &lt;input type="submit" id="myButton" value="Edit" name="edit" onclick="toggleVisibility('');"&gt; &lt;/td&gt; &lt;/form&gt; &lt;td&gt;&lt;form id="delete" action="DeleteRecord" method="post" &gt; &lt;td&gt;&lt;input type="hidden" name="hidden_delete" id="delete_id" value="&lt;%=s %&gt;"/&gt; &lt;input type="submit" value="delete" name="delete"&gt; &lt;/td&gt; &lt;/form&gt;&lt;/td&gt; &lt;%} %&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/TABLE&gt; </code></pre>
0
2,220
rake aborted! cannot load such file -- yard
<p>I have been trying to add a vagrant plugin (<a href="https://github.com/schisamo/vagrant-omnibus" rel="noreferrer">https://github.com/schisamo/vagrant-omnibus</a>) from source. I downloaded it, did "bundle install", which went smooth. But when I did "rake install", it showed me the following error:</p> <pre><code>rake aborted! cannot load such file -- yard </code></pre> <p>Here is the full error log with trace:</p> <pre><code>rake aborted! cannot load such file -- yard /root/chef-solo-example/vagrant-omnibus-master/Rakefile:5:in `require' /root/chef-solo-example/vagrant-omnibus-master/Rakefile:5:in `&lt;top (required)&gt;' /usr/share/gems/gems/rake-10.0.4/lib/rake/rake_module.rb:25:in `load' /usr/share/gems/gems/rake-10.0.4/lib/rake/rake_module.rb:25:in `load_rakefile' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:589:in `raw_load_rakefile' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:89:in `block in load_rakefile' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:160:in `standard_exception_handling' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:88:in `load_rakefile' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:72:in `block in run' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:160:in `standard_exception_handling' /usr/share/gems/gems/rake-10.0.4/lib/rake/application.rb:70:in `run' /usr/share/gems/gems/rake-10.0.4/bin/rake:33:in `&lt;top (required)&gt;' /bin/rake:23:in `load' /bin/rake:23:in `&lt;main&gt;' </code></pre> <p>Here is the gem list:</p> <pre><code>*** LOCAL GEMS *** archive-tar-minitar (0.5.2) ast (1.1.0) bigdecimal (1.2.0) bundler (1.3.1) chef (11.8.2) chef-zero (1.7.2) coderay (1.1.0) diff-lcs (1.2.5) erubis (2.7.0) hashie (2.0.5) highline (1.6.20) io-console (0.4.2) ipaddress (0.8.0) json (1.7.7) knife-solo (0.4.1) librarian (0.1.0) librarian-chef (0.0.2) method_source (0.8.2) mime-types (1.16) mixlib-authentication (1.3.0) mixlib-cli (1.4.0) mixlib-config (2.1.0) mixlib-log (1.6.0) mixlib-shellout (1.3.0) moneta (0.7.20, 0.7.0, 0.6.0) net-http-persistent (2.8) net-ssh (2.7.0) net-ssh-gateway (1.2.0) net-ssh-multi (1.2.0, 1.1) ohai (6.20.0) parser (2.0.0) powerpack (0.0.9, 0.0.6) pry (0.9.12.4) psych (2.0.0) puma (1.6.0) rack (1.5.2) rainbow (1.1.4) rake (10.0.4) rake-compiler (0.8.3) rdoc (4.0.1) rest-client (1.6.7) rspec (2.14.1) rspec-core (2.14.0) rspec-expectations (2.14.0) rspec-mocks (2.14.0) rubocop (0.15.0) slop (3.4.7) systemu (2.6.0, 2.5.2) thor (0.17.0) yajl-ruby (1.1.0) yard (0.8.7.3) </code></pre> <p>Any idea what could be causing this error?</p>
0
1,291