title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
When I change screen orientation using sensor ImageView becomes blank in android?
<p>Here i am using following code</p> <p>Here the problem is to using following code i am picked image from gallery and set in ImageView but when i rotate screen the ImageView become blank. So give me the solution for how to save state and displaying the image. </p> <pre><code> FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Create intent to Open Image applications like Gallery, Google Photos Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Start the Intent startActivityForResult(galleryIntent, RESULT_LOAD_IMG); //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) //.setAction("Action", null).show(); //Intent i = new Intent(MainActivity.this,firstActivity.class); //startActivity(i); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); try { // When an Image is picked if (requestCode == RESULT_LOAD_IMG &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) { // Get the Image from data Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; // Get the cursor Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); // Move to first row cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); imgDecodableString = cursor.getString(columnIndex); cursor.close(); ImageView imgView = (ImageView) findViewById(R.id.imgView); // Set the Image in ImageView after decoding the String imgView.setImageBitmap(BitmapFactory .decodeFile(imgDecodableString)); } else { Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG) .show(); } } </code></pre>
3
1,041
Angular JS create multiple Dropdowns dynamically and Need validation
<p>I want to do validation for the dynamically create dropdown fields in angular js. Here I pasred my JSON data and dynamically create dropdown fields and able to get even data but I want validation on default option "select a type". .html file</p> <pre><code> &lt;div ng-repeat="CategoryList1 in Data"&gt; {{CategoryList1.fullImage}} &lt;div ng-repeat="Attributes in CategoryList1.Attributes"&gt; &lt;label class="item item-input"&gt; &lt;span&gt; {{Attributes.name}}&lt;/span&gt; &lt;/label&gt; &lt;select ng-model="atcStatusTasks" name="category-group" id="name" required ng-options="values.values for values in Attributes.Values" ng-change="atcStatusTasks===undefined ||GetValue(atcStatusTasks,Attributes.name)" &gt; &lt;option selected="selected" value=""&gt;select a type&lt;/option&gt; &lt;/select&gt; {{atcStatusTasks}}{{Attributes.name}} &lt;/div&gt; &lt;button class="button button-dark" ng-click="addToCart()"&gt; Add To Cart&lt;/button&gt; &lt;span style="color:red"&gt;{{msg}}&lt;/span&gt;&lt;br /&gt; &lt;/div&gt; </code></pre> <p><a href="https://i.stack.imgur.com/986lC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/986lC.png" alt="enter image description here"></a></p> <p>JSON data:</p> <pre><code>{ "recordSetTotal": "1", "resourceId": "", "resourceName": "productview", "recordSetComplete": "true", "recordSetStartNumber": "0", "CatalogEntryView": [ { "shortDescription": "Straight leg denim jeans", "buyable": "true", "longDescription": "A regular pair of jeans for your boy in dark blue, they are straight legged and have a distressed finish. Whisker washed for a faded effect, the comfortable fit makes him look tall and lean. A white shirt goes very well with these jeans.", "parentCategoryID": "10024", "metaKeyword": " Hermitage Collection", "resourceId": "", "Price": [ { "priceDescription": "I", "priceUsage": "Offer", "priceValue": "45.0" } ], "productType": "ProductBean", "name": "Hermitage Straight Leg Denim Jeans", "fullImage": "", "thumbnail": "", "uniqueID": "12390", "manufacturer": "Hermitage Collection", "numberOfSKUs": "4", "SKUs": [ { "Attributes": [ { "usage": "Defining", "Values": [ { "values": "Blue", "identifier": "Blue", "uniqueID": "7000000000000001341" } ], "searchable": "false", "identifier": "BoysPantsColor", "comparable": "true", "name": "Color", "displayable": "true", "uniqueID": "7000000000000000060" }, { "usage": "Defining", "Values": [ { "values": "S", "identifier": "S", "uniqueID": "7000000000000001344" } ], "searchable": "false", "identifier": "BoysPantsSize", "comparable": "true", "name": "Size", "displayable": "true", "uniqueID": "7000000000000000061" } ], "SKUUniqueID": "12391", "Price": [ { "SKUPriceDescription": "I", "SKUPriceValue": "45.0", "SKUPriceUsage": "Offer" } ] }, { "Attributes": [ { "usage": "Defining", "Values": [ { "values": "Blue", "identifier": "Blue", "uniqueID": "7000000000000001341" } ], "searchable": "false", "identifier": "BoysPantsColor", "comparable": "true", "name": "Color", "displayable": "true", "uniqueID": "7000000000000000060" }, { "usage": "Defining", "Values": [ { "values": "M", "identifier": "M", "uniqueID": "7000000000000001345" } ], "searchable": "false", "identifier": "BoysPantsSize", "comparable": "true", "name": "Size", "displayable": "true", "uniqueID": "7000000000000000061" } ], "SKUUniqueID": "12392", "Price": [ { "SKUPriceDescription": "I", "SKUPriceValue": "45.0", "SKUPriceUsage": "Offer" } ] }, { "Attributes": [ { "usage": "Defining", "Values": [ { "values": "Blue", "identifier": "Blue", "uniqueID": "7000000000000001341" } ], "searchable": "false", "identifier": "BoysPantsColor", "comparable": "true", "name": "Color", "displayable": "true", "uniqueID": "7000000000000000060" }, { "usage": "Defining", "Values": [ { "values": "L", "identifier": "L", "uniqueID": "7000000000000001346" } ], "searchable": "false", "identifier": "BoysPantsSize", "comparable": "true", "name": "Size", "displayable": "true", "uniqueID": "7000000000000000061" } ], "SKUUniqueID": "12393", "Price": [ { "SKUPriceDescription": "I", "SKUPriceValue": "45.0", "SKUPriceUsage": "Offer" } ] }, { "Attributes": [ { "usage": "Defining", "Values": [ { "values": "Blue", "identifier": "Blue", "uniqueID": "7000000000000001341" } ], "searchable": "false", "identifier": "BoysPantsColor", "comparable": "true", "name": "Color", "displayable": "true", "uniqueID": "7000000000000000060" }, { "usage": "Defining", "Values": [ { "values": "XL", "identifier": "XL", "uniqueID": "7000000000000001347" } ], "searchable": "false", "identifier": "BoysPantsSize", "comparable": "true", "name": "Size", "displayable": "true", "uniqueID": "7000000000000000061" } ], "SKUUniqueID": "12394", "Price": [ { "SKUPriceDescription": "I", "SKUPriceValue": "45.0", "SKUPriceUsage": "Offer" } ] }], "Attributes": [ { "usage": "Defining", "Values": [ { "values": "S", "extendedValue": [ { "value": "C62", "key": "UnitOfMeasure" } ], "identifier": "S", "uniqueID": "7000000000000001344" }, { "values": "M", "extendedValue": [ { "value": "C62", "key": "UnitOfMeasure" } ], "identifier": "M", "uniqueID": "7000000000000001345" }, { "values": "L", "extendedValue": [ { "value": "C62", "key": "UnitOfMeasure" } ], "identifier": "L", "uniqueID": "7000000000000001346" }, { "values": "XL", "extendedValue": [ { "value": "C62", "key": "UnitOfMeasure" } ], "identifier": "XL", "uniqueID": "7000000000000001347" } ], "searchable": "false", "dataType": "STRING", "ExtendedValue": [ { "extValue": "C62" } ], "identifier": "BoysPantsSize", "comparable": "true", "name": "Size", "description": "Size", "displayable": "true", "uniqueID": "7000000000000000061" }, { "usage": "Defining", "Values": [ { "values": "Blue", "extendedValue": [{ "value": "C62", "key": "UnitOfMeasure" }], "identifier": "Blue", "uniqueID": "7000000000000001341" } ], "searchable": "false", "dataType": "STRING", "ExtendedValue": [ { "extValue": "C62" } ], "identifier": "BoysPantsColor", "comparable": "true", "name": "Color", "description": "Color", "displayable": "true", "uniqueID": "7000000000000000060" }, { "usage": "Descriptive", "Values": [ { "values": "Denim jeans", "identifier": "BCL015_1501", "uniqueID": "7000000000000001368" } ], "searchable": "false", "dataType": "STRING", "ExtendedValue": [ { "extValue": "C62" } ], "identifier": "Style", "comparable": "true", "name": "Style", "description": "Style", "displayable": "true", "uniqueID": "7000000000000000010" }, { "usage": "Descriptive", "Values": [ { "values": "Denim", "identifier": "BCL015_1501", "uniqueID": "7000000000000001358" } ], "searchable": "false", "dataType": "STRING", "ExtendedValue": [ { "extValue": "C62" } ], "identifier": "Material", "comparable": "true", "name": "Material", "description": "Material", "displayable": "true", "uniqueID": "7000000000000000009" }, { "usage": "Descriptive", "Values": [ { "values": "Casual", "identifier": "BCL015_1501", "uniqueID": "7000000000000001378" } ], "searchable": "false", "dataType": "STRING", "ExtendedValue": [ { "extValue": "C62" } ], "identifier": "Occasion", "comparable": "true", "name": "Occasion", "description": "Occasion", "displayable": "true", "uniqueID": "7000000000000000011" }, { "usage": "Descriptive", "Values": [ { "values": "8-16", "identifier": "BCL015_1501", "uniqueID": "7000000000000001348" } ], "searchable": "false", "dataType": "STRING", "ExtendedValue": [ { "extValue": "C62" } ], "identifier": "Age", "comparable": "true", "name": "Age", "description": "Age", "displayable": "true", "uniqueID": "7000000000000000053" } ], "subscriptionType": "NONE", "metaDescription": "Straight leg denim jeans", "title": "Hermitage Straight Leg Denim Jeans | Aurora", "disallowRecOrder": "true", "hasSingleSKU": "false", "partNumber": "BCL015_1501", "storeID": "10001", "fullImageAltDescription": "Image for Hermitage Straight Leg Denim Jeans from Aurora" } ], "recordSetCount": "1", "MetaData": [ { "metaKey": "price", "metaData": "1" } ] } </code></pre>
3
11,651
.apk file installed and worked on 2.2 android device well but .apk not installing in android 4.0.4 iball tab
<p><strong>MY MANIFEST</strong></p> <p>App run well in android 2.2 device well but getting error when try to installing in android </p> <p>4.0.4 device,i tested by changing the properties of the app also.</p> <p><strong>BUILD TARGET:</strong></p> <p> <p>package="com.example.androidactionbar"</p> <p>android:versionCode="1"</p> <p>android:versionName="1.1" ></p> <p><strong>USING SDK:</strong></p> <pre><code>&lt;uses-sdk android:minSdkVersion="3" android:maxSdkVersion="15" android:targetSdkVersion="15" /&gt; </code></pre> <p><strong>SUPPORT SCREEN RESOLUTION:</strong></p> <p> <pre><code> android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" /&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.WRITE_EXTERNAL_STORAGE" &gt; &lt;/uses-permission&gt; &lt;uses-permission android:name="android.permission.INTERNET" &gt; &lt;/uses-permission&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-feature android:name="android.hardware.touchscreen" android:required="false" /&gt; &lt;application android:icon="@drawable/applauncher" android:label="CarKonect" android:theme="@style/Theme.D1" &gt; &lt;uses-library android:name="com.google.android.maps" /&gt; &lt;activity android:name=".ActionBarAppActivity" android:label="@string/title_activity_action_bar_app" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".HomeActivity" android:label="@string/title_activity_action_bar_app" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".SearchActivity" android:label="@string/title_activity_action_bar_app" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Writetodealer" android:label="@string/title_activity_action_bar_app" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".FeedBackForm" android:label="@string/title_activity_action_bar_app" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ScheduleService" android:label="@string/title_activity_action_bar_app" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".R" android:label="@string/title_activity_r" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CustomerLogin" android:label="@string/title_activity_customer_login" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CarKonect" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CustomAdapter" android:label="@string/title_activity_custom_adapter" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".JSONParser" android:label="@string/title_activity_jsonparser" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Comment" android:label="@string/title_activity_comment" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ExpandAnimation" android:label="@string/title_activity_expand_animation" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CollapseAnimation" android:label="@string/title_activity_collapse_animation" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Animation" android:label="@string/title_activity_animation" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".MainActivity" android:label="@string/title_activity_animation" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ServiceCallAsyncGet" android:label="@string/title_activity_test" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Common" android:label="@string/title_activity_common" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ExpandListView" android:label="@string/title_activity_expand_list_view" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".JsonPost" android:label="@string/title_activity_json_post" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Json" android:label="@string/title_activity_json_post" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Normal" android:label="@string/title_activity_normal" &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=".ServiceCallAsyncCommon" android:label="@string/title_activity_service_call_async_common" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".OneNormal" android:label="@string/title_activity_one_normal" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Asyncall" android:label="@string/title_activity_asyncall" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".NormalTwo" android:label="@string/title_activity_normal_two" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".OneNormalValue" android:label="@string/title_activity_normal_two" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".AsyncallOne" android:label="@string/title_activity_normal_two" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".AsyncallTwo" android:label="@string/title_activity_asyncall_two" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ResetPassword" android:label="@string/title_activity_reset_password" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".JsonParserTwo" android:label="@string/title_activity_json_parser_two" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CustomListViewAdapter1" android:label="@string/title_activity_custom_list_view_adapter1" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Schedule" android:label="@string/title_activity_schedule" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".JsonParserOne" android:label="@string/title_activity_json_parser_one" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".TestActivity" android:label="@string/title_activity_test" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".SingleClick" android:label="@string/title_activity_test" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".SingleClickComment" android:label="@string/title_activity_test" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; </code></pre> <p></p>
3
7,025
Translate HTML form request to php array
<p>I have a html form with 3 selector:</p> <pre><code>a. Room -&gt; 1, 2, 3, 4, 5, 6 b. Adults -&gt; 1, 2, 3, 4, 5, 6 c. Childs -&gt; 0, 1, 2, 3, 4, 5 </code></pre> <p>THe php arrays that i need to get looks like: Example 1 room with 2 adults</p> <pre><code>$rooms[] = array(array("paxType" =&gt; "Adult"), array("paxType" =&gt; "Adult")); </code></pre> <p>Example 2 rooms ( one room is with two adults and the second room si with 2 adults an one child</p> <pre><code>$rooms[] = array(array("paxType" =&gt; "Adult"), array("paxType" =&gt; "Adult")); $rooms[] = array(array("paxType" =&gt; "Adult"), array("paxType" =&gt; "Adult"), array("paxType" =&gt;"Child", "age" =&gt; 8)); </code></pre> <p>The variables that i receive from the form are as below:</p> <pre><code>$City= $_POST['City']; - text $CheckIN= $_POST['CheckIN']; - text (date) $CheckOUT= $_POST['CheckOUT']; - text (date) $Rooms= $_POST['Rooms']; - selector (1,2,3,4,5,6) $Adults= $_POST['Adults']; - selector (1,2,3,4,5,6) $Childs= $_POST['Childs']; - selector (0,1,2,3,4,5) </code></pre> <p>Form is workink fine for text and date input fields. How can i translate the html form request to get into the a bove look like php arrays. Thank you for your time.</p> <p>Entire code is:</p> <pre><code>// create SOAP client object $client = new SoapClient("http://www.bookingassist.ro/test/book.wsdl", array('trace' =&gt; 1)); try { function addPaxType($type = null, $amount = 0) { $pax = array(); for ($i = 0; $i &lt; amount; $i++) { array_push($pax, array('paxType' =&gt; $type)); } return $pax; } $RoomsLength = 1;//count($_POST['Rooms']); $Rooms = array(); //iterate over all rooms for ($i = 0; $i &lt; $RoomsLength ; $i++) { $Rooms[$i] = array(); if ( count($Adults) &gt; 0) { //use a function to add adults to room array_push($Rooms[$i] , addPaxType('Adults', count($Adults))); } if (count($Childs) &gt; 0) { array_push($Rooms[$i], addPaxType('Childs', count($Childs))); } } $filters = array(); $filters[] = array("filterType" =&gt; "hotelStar", "filterValue" =&gt; "3", "4", "5"); $filters[] = array("filterType" =&gt; "resultLimit", "filterValue" =&gt; "7"); // make getAvailableHotel request (start search) $checkAvailability = $client-&gt;getAvailableHotel("gfdgdfgVNhTzA4MVZ3Y2hjTkt3QXNHSXZRYUZOb095Qg==", "RHMK", "2015-03-30", "2015-04-12", "EUR", "RO", "false", $rooms, $filters); } catch (SoapFault $exception) { echo $exception-&gt;getMessage(); exit; } </code></pre>
3
1,135
Django cumulative value displayed in template
<p>I’m new to Django and Python and have been plugging through Python Crash Course. I have finished that and now have been making my own Django project, adding some extra bits in.</p> <p>Currently, I have a table of entries from my model which I am displaying with a template, each entry in the table has a time and some other data. What I would like is the value for the cumulative time in a column, next to each entries time ie</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Lesson</th> <th>Lesson time</th> <th>cumulative time</th> </tr> </thead> <tbody> <tr> <td>Lesson1</td> <td>0.5</td> <td>0.5</td> </tr> <tr> <td>Lesson2</td> <td>1</td> <td>1.5</td> </tr> <tr> <td>Lesson3</td> <td>1.3</td> <td>2.8</td> </tr> </tbody> </table> </div> <p>I’m just really stuck on how to get this done, I have looked at lot’s of stack overflow and tried various ways that I just can’t get to work correctly. Looking at other examples they use annotate() and cumsum, but I’ve not been able to get that to work. I’ve done count and sum of other values but this has got me stuck. I think I need to loop over it in my view, but not sure how to associate each value to a cumulative time.</p> <p>Any help would be greatly received. Also, sorry this isn't very well written or succinct, programming doesn't come naturally to me.</p> <p>My <strong>topics.py</strong></p> <pre class="lang-py prettyprint-override"><code>def topics(request): &quot;&quot;&quot;Show all the topics&quot;&quot;&quot; # Get the public topics public_topics = Lessontopic.objects.filter(public=True).order_by('date_added') # Get the private topics if request.user.is_authenticated: private_topics = Lessontopic.objects.filter(owner=request.user).order_by('date_added') topics = private_topics &quot;&quot;&quot;By Adding private into topics, seeing all public topics not just users this way any topic added by authenticated user comes up in private, even if it is also visible in public&quot;&quot;&quot; time = Lessontopic.objects.aggregate(Sum('lesson_time')) total_time = time.get('lesson_time__sum') total_time = float(total_time) lessons = Lessontopic.objects.all().count() print(f&quot;There has been {lessons} lessons &quot;) solo = (Lessontopic.objects.filter(solo_lesson=True) .aggregate(Sum('lesson_time'))) solo_time = solo.get('lesson_time__sum') print(f&quot;solo lesson flying time {solo_time} hours&quot;) solo_num = Lessontopic.objects.filter(solo_lesson=True).all().count() dual = (Lessontopic.objects.filter(solo_lesson=False) .aggregate(Sum('lesson_time'))) dual_time = dual.get('lesson_time__sum') remaining_time = 50 - total_time #Make a pie chart. labels = ['Solo', 'Dual'] values = [solo_time, dual_time] chat = ['this is long'] # Visualise the results data=[Pie(labels=labels,text=chat,values=values,pull=[0.1, 0], textposition='outside') ] x_axis_config = {'title': 'Hours'} y_axis_config = {'title': 'Lesson type'} my_layout = Layout(title='Flying time Solo vs Dual Instruction',title_font_color='black' , title_font_size=30, title_x=0.5, legend_bordercolor='green', legend_borderwidth=5 ) fig = ({'data': data, 'layout': my_layout}) div = offline.plot(fig, auto_open=False, output_type='div') cumulative_time = Lessontopic.objects.annotate( cumulative_times=Window( expression = Sum('lesson_time'), order_by=F('date_added').asc(), frame=RowRange(start=None, end=0) ) ) context = {'topics': topics, 'cumulative_time':cumulative_time,'lessons':lessons, 'solo_time':solo_time, 'solo_num':solo_num, 'dual_time':dual_time,'solo_num':solo_num, 'remaining_time':remaining_time, 'dual':dual,'graph':div,} else: topics = public_topics context = {'topics': topics} return render(request, 'flying_logs/topics.html', context) </code></pre> <p>my <strong>model.py</strong></p> <pre class="lang-py prettyprint-override"><code>from django.db import models from django.contrib.auth.models import User from django.forms.widgets import DateInput from django import forms import json import requests # Create your models here. class Lessontopic(models.Model): &quot;&quot;&quot;The topic of each lesson or day flying&quot;&quot;&quot; text= models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False, verbose_name=&quot;Make post public?&quot;, help_text=&quot;click on this form if you want it to be viewed by anyone&quot;) lesson_number = models.PositiveIntegerField(blank=True, null=True) lesson_time = models.DecimalField('enter flight time', max_digits=2, decimal_places=1) solo_lesson = models.BooleanField(default=False, verbose_name=&quot;Were you solo for the lesson&quot;, help_text=&quot;Click if were flying solo for the lesson&quot;) runway_direction = models.PositiveIntegerField( verbose_name=&quot;Select runway direction: 07 or 25&quot;) number_landings = models.PositiveIntegerField(blank=True, default=1, help_text=&quot;Enter how many landings&quot;) date = models.DateTimeField() time_of_lesson = models.PositiveIntegerField( verbose_name=&quot;time that the lesson started&quot;) weather_data = models.CharField(max_length=200) adding = models.TextField(default=None, null=True, blank=True) def __str__(self): &quot;&quot;&quot;Return a string representation of the modeel&quot;&quot;&quot; return self.text </code></pre> <p>My template <strong>topics.html</strong></p> <pre class="lang-py prettyprint-override"><code> {% extends &quot;flying_logs/base.html&quot; %} &lt;h1&gt;Topics&lt;/h1&gt; {% block page_header %} {% endblock page_header %} {% block content %} &lt;div class=&quot;container&quot;&gt; &lt;table class=&quot;table text-center table-hover table-bordered&quot; &gt; &lt;tr&gt;&lt;tr class=&quot;table-primary&quot;&gt; &lt;th style=&quot;width: 10%&quot;&gt;Lesson No.&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Date&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Lesson&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Dual/Solo &lt;th scope=&quot;col&quot;&gt;Flying time&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Cumulative&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; {% for topic in topics %} {% if topic.solo_lesson %} &lt;tr class=&quot;table-success&quot;&gt; {% endif %} &lt;td class=&quot;text-center&quot;&gt; {{topic.lesson_number}}&lt;/td&gt; &lt;td&gt;{{ topic.date|date:'d/m/Y'}}&lt;/td&gt; &lt;td&gt;&lt;a href=&quot;{% url 'flying_logs:topic' topic.id %}&quot;&gt;{{ topic }}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{ topic.solo_lesson|yesno:&quot;Solo, Dual&quot; }}&lt;/td&gt; &lt;td class=&quot;text-center&quot;&gt;{{topic.lesson_time}}&lt;/td&gt; &lt;td&gt;Time so far{{ cumulative_time}}&lt;/td&gt; &lt;/tr&gt; {% endfor %}&lt;/table&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;table class=&quot;table text-center table-hover table-bordered&quot; &gt; &lt;thread&gt; &lt;tr&gt;&lt;tr class=&quot;table-primary&quot;&gt; &lt;th style=&quot;width: 5%&quot;&gt;Solo&lt;/th&gt; &lt;th style=&quot;width: 20%&quot;&gt;Dual&lt;/th&gt; &lt;th style=&quot;width: 20%&quot;&gt;total time&lt;/th&gt; &lt;th style=&quot;width: 20%&quot;&gt;Time remaing&lt;/th&gt; &lt;th style=&quot;width: 20%&quot;&gt; Solo Lessons&lt;/th&gt; &lt;th style=&quot;width: 35%&quot;&gt;Number of lessons&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;td&gt;{{solo_time|floatformat:1}}&lt;/td&gt; &lt;td&gt;{{dual_time|floatformat:1}}&lt;/td&gt; &lt;td&gt;{{total_time}}&lt;/td&gt; {% if remaining_time &gt;= 0 %} &lt;td class=&quot;table-danger&quot;&gt;{{ remaining_time|floatformat:1 }}&lt;/td&gt; {% elif remaining_time &lt;= 0 %} &lt;td class=&quot;table-success&quot;&gt;You've done the minimum hours!!&lt;/td&gt; {% endif %} &lt;td class=&quot;text-center&quot;&gt; {{ solo_num}} &lt;/td&gt; &lt;td&gt;{{lessons}}&lt;/td&gt; &lt;/tr&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;h3&gt;&lt;a href=&quot;{% url 'flying_logs:new_topic' %}&quot;&gt;&lt;button name=&quot;new entry&quot; class=&quot;btn btn-primary&quot;&gt;Add a new topic&lt;/button&gt;&lt;/a&gt;&lt;/h3&gt; {% if graph %} &lt;div style=&quot;width:600;height:500&quot;&gt; {{ graph|safe }} &lt;/div&gt; {% endif %} {% endblock content %} </code></pre>
3
4,485
Using Factory with DryIoc and getting object by string
<p>I am just testing invertion control using DryIoc library. Please check above to get the picture.</p> <p>I have that factory class:</p> <pre><code> 'FactoryConnections using IoC Dry Public Class FactoryConnections Private Shared ReadOnly Container As Container Shared Sub New() Container = New Container() With Container .Register(Of ISftp, Sftp) .Register(Of ISaop, Soap) '.Register(Of IFtp, Ftp) .Register(Of IFtp, Ftp)(serviceKey:= "some string value") End With End Sub Public Shared Function ResolveService(Of T As IProtocol)(value As Iprotocol) As T Return Container.Resolve(Of T) End Function End Class </code></pre> <p>Just shortly according to invertion:</p> <pre><code>A -&gt; Y (A uses Y) A -&gt; Interface B -&gt; Y (in this case A doesn't know about Y) </code></pre> <p>we can read my solution the same:</p> <pre><code>A -&gt; IFtp -&gt; Ftp </code></pre> <p>Therefore instead of getting directly object like: Ftp, Sftp or Soap code should ask factory to get one of them based on the interface therefore calling point doesn't know exactly what concrete object is using but it knows who implements that - that's at elast my understanding. Therefore i could ask calling them via interfaces. This is what i am trying to do however from string value (project related requirment). </p> <pre><code>Dim myProtocol As String = "IFtp" </code></pre> <p>And as mentioned having that i want to get proper object from my factory in this case i should get New instance of Ftp right?</p> <p><em>Note that parent interface for IFtp, ISoap, ISftp is IProtocol</em> </p> <p>I was trying like this:</p> <pre><code>Dim myProtocol As String = "IFtp" Dim itemprotocol As type = Type.GetType(myProtocol) Dim realprotocolobject = FactoryConnections.ResolveService(TypeOf(itemprotocol)) </code></pre> <p>and also tried like this:</p> <pre><code>Dim myProtocol As String = "IFtp" Dim realprotocolobject = FactoryConnections.ResolveService(Of IProtocol)(myProtocol) </code></pre> <p>What's wrong, What am i doing wrong?</p> <p>One more thing: what is the diffrence between those lines? (just saw this serviceKey somwhere..)</p> <pre><code>.Register(Of IFtp, Ftp) .Register(Of IFtp, Ftp)(serviceKey:= "some string value") </code></pre> <p><strong>Further discussionre reference:</strong></p> <p>Factory class: <a href="https://1drv.ms/i/s!AkQvbwpYPYoIh0IqruVthcndFyOM" rel="nofollow noreferrer">https://1drv.ms/i/s!AkQvbwpYPYoIh0IqruVthcndFyOM</a></p> <p>UnitTestClass: <a href="https://1drv.ms/i/s!AkQvbwpYPYoIh0G7iEfy427aJXXw" rel="nofollow noreferrer">https://1drv.ms/i/s!AkQvbwpYPYoIh0G7iEfy427aJXXw</a></p>
3
1,075
Cesar decryption. How to deal with non-alphanumerical chars | JS
<p>Build a function which takes an encrypted string as argument. it's a Cesar encryption. Like: encrypted character + 5 (or whatever number).</p> <p><strong>Problem: The encrypted string contains non-alphanumeric chars like " " or "!".</strong></p> <p>I build a very verbose function which is attached below for completion. <strong>The main part to solve the above mentioned problem is:</strong></p> <pre><code> let z = /[^A-^Z]/g; if (strIn.search(z) !== 0) { let n = strIn.search(z); wordArr.splice(n, 0, strIn[n]); </code></pre> <p><code>strIn</code> is the uppercase version of the input string (the encrypted string) <code>wordArr</code> is the decrypted version <strong>without</strong> non alphanumeric chars.</p> <p>I tried to loop like this:</p> <pre><code> for (var i = 0; i &lt; strIn.length; i++) { if (strIn.search(z) !== 0) { let n = strIn.search(z); wordArr.splice(n, 0, strIn[n]); } } </code></pre> <p>I also tried a while loop. Similar successless. I also tried to map. But than console throws: </p> <pre><code> strIn.map is not a function </code></pre> <p><strong>Could anyone explain this behavior and give me just a hint how to solve this problem. 1.) Using a loop 2.) Using something better if possible</strong></p> <p>Here my verbose code for reference or whatever:</p> <pre><code>function rot13(str) { let upper = str.toUpperCase().split(""); let index = []; let decode = []; const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (var i = 0; i &lt; upper.length; i++) { if (alpha.indexOf(upper[i]) === -1) { index.push(upper[i]); } else if (alpha.indexOf(upper[i]) !== -1) { index.push(alpha.indexOf(upper[i])); } } console.log("index: " + index); let elem = index.map(function(a, b) { if (a === 13) { return a - 13; } else if (a + 13 &lt;= 26) { return a + 13; } else if (a + 13 &gt; 26) { return a - 13; } }); console.log("elem :" + elem); for (var j = 0; j &lt; elem.length; j++) { decode.push(alpha[elem[j]]); } let word = decode.join(""); let strIn = upper.join(""); console.log("strIn: " + strIn); let z = /[^A-^Z]/g; // let z = /[\!]/g; let wordArr = Array.from(word); if (strIn.search(z) !== 0) { let n = strIn.search(z); wordArr.splice(n, 0, strIn[n]); } console.log("wordArr: " + wordArr); console.log(wordArr.join("")); console.log(strIn.search(z)); } rot13("SERR CVMMN!"); </code></pre>
3
1,024
how to perform addition using a textbox
<p>I have a Text box. On button click event the value of Text box should be displayed in a label as result. On clicking the button again and giving some input in the Text box the input should get added to the result. I mean repeating the button clicks and providing input should get added o the result. How to perform this?</p> <p>I am still getting error </p> <pre><code>"System.FormatException: Input string was not in a correct format." Error is regarding: lblconsumed.Text = (int.Parse(lblconsumed.Text) + userValue).ToString(); </code></pre> <p>Code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebApplication1.ServRef; using System.Configuration; using System.Data.SqlClient; using System.Data; namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { ServRef.ProteinServiceClient sc = new ServRef.ProteinServiceClient(); UserDetail userinfo = new UserDetail(); protected void Page_Load(object sender, EventArgs e) { // ddlUser.DataSource = sc.AddUser(userinfo); BindUserDetails(); } protected void BindUserDetails() { IList&lt;UserDetail&gt; objUserDetails = new List&lt;UserDetail&gt;(); //objUserDetails = objService.GetUserDetails(""); objUserDetails = sc.GetAllUser(""); ddlUser.DataSource = objUserDetails; ddlUser.DataBind(); } protected void btnAddUser_Click(object sender, EventArgs e) { userinfo.user_name = tbname.Text.Trim(); userinfo.user_goal = Convert.ToInt32(tbgoal.Text.Trim()); string result = sc.AddUser(userinfo); lblgoal.Text = Convert.ToString(userinfo.user_goal); } protected void Button2_Click(object sender, EventArgs e) { int userValue; if (int.TryParse(tbamount.Text, out userValue)) { lblconsumed.Text = (int.Parse(lblconsumed.Text) + userValue).ToString(); } } } }` </code></pre> <p>My aspx page:</p> <pre><code> &lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %&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;link href="Style.css" rel="stylesheet" /&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div id="main"&gt; &lt;h2&gt;Protein Tracker&lt;/h2&gt; &lt;div id="selectuser"&gt; &lt;label for="select-users"&gt;Select a user&amp;nbsp: &lt;/label&gt; &lt;asp:DropDownList ID="ddlUser" runat="server" Width="60px" AutoPostBack="True" DataTextField="user_name" DataValueField="user_name" &gt;&lt;/asp:DropDownList&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div id="adduser"&gt; &lt;h2&gt;Add new user&lt;/h2&gt; &lt;label for="name"&gt;User Name&amp;nbsp:&lt;/label&gt; &lt;asp:TextBox ID="tbname" runat="server" style="margin-left: 10px"&gt;&lt;/asp:TextBox&gt; &lt;br /&gt;&lt;br /&gt; &lt;label for="goal"&gt;User Goal&amp;nbsp:&lt;/label&gt; &lt;asp:TextBox ID="tbgoal" runat="server" style="margin-left: 20px"&gt;&lt;/asp:TextBox&gt; &lt;br /&gt;&lt;br /&gt; &lt;asp:Button ID="btnAddUser" runat="server" Text="Add" style="margin-left: 210px" OnClick="btnAddUser_Click" /&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div id="addprotein"&gt; &lt;h2&gt;Add protein&lt;/h2&gt; &lt;label for="amount"&gt;Amount&amp;nbsp:&lt;/label&gt; &lt;asp:TextBox ID="tbamount" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;br /&gt; &lt;br /&gt; &lt;asp:Button ID="Button2" runat="server" Text="Add" style="margin-left: 180px" OnClick="Button2_Click"/&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div&gt; &lt;p&gt;Total Consumed&amp;nbsp:&amp;nbsp &lt;asp:Label ID="lblconsumed" runat="server" Text=""&gt;&lt;/asp:Label&gt;&lt;/p&gt; &lt;p&gt;Goal Set&amp;nbsp:&amp;nbsp &lt;asp:Label ID="lblgoal" runat="server" Text=""&gt;&lt;/asp:Label&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
2,361
highrise api not working with spring
<p>I am trying to use highrise api with my java spring application.</p> <p>I copied highrise .jar from <a href="https://github.com/dnobel/highrise-java-api" rel="nofollow">https://github.com/dnobel/highrise-java-api</a>. But I am getting exception when I run my appliaction with this and it stops my tomcat server</p> <pre><code> [ERROR] 2013-09-30 12:03:34 Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#1' while setting bean property 'sourceList' with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#1': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [2]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property ' passwordEncoder' threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:354) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:587) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) 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:722) </code></pre> <p>when I remove highrise jar file then my application works fine.</p> <p>Does anyone has idea why I am getting this error or is there any other way to use highrise api I have got the highrise token number to connect. I want to retrieve all Emails, Notes and deals with employee names.</p> <p>Please let me know if you need anymore information</p>
3
1,706
React setState not merging all changes
<h2>EDIT - I can't vote for my own answer at the moment but this turned out to be a reference/immutability issue - see <a href="https://stackoverflow.com/a/60189228/11602055">https://stackoverflow.com/a/60189228/11602055</a></h2> <p>this one has me completely stumped!</p> <p>I'm getting some data from my server and applying it to my state, but some of the properties I'm applying to the state don't migrate to the state after setState has completed...</p> <p>I've tried everything I can think of regarding this, I'm reading the final state as part of the callback from setState to ensure I'm getting the state after setState has completed so it's nothing to do with setState being Async in nature.</p> <p>Have attempted the following -</p> <ul> <li>use a blank object, save new props to that object and then return that.</li> <li>apply each property one at a time in separate setState calls inside an outer loop on the keys</li> <li>return Object.assign({},this.state,data);</li> <li>return {...data};</li> <li>return {...this.state,...data};</li> <li>await setState(...);</li> <li>setState(data)</li> </ul> <p>I've got a couple of nested state properties but this is affecting root properties of the state object...</p> <p>See code/output/end state below, note for example that eventColour has not propagated through the setState action to the final state... (same applies for iconCls...)</p> <p>Help please?...</p> <p>Code:</p> <pre><code>getJobDetail = async function (){ // get data from server let response = await window.fetch("/event/events?id="+this.props.job,{cache: "no-cache", credentials: "same-origin"}); // parse returned data let data = await response.json(); // couple of minor data manipulation exercises if (data.tempToFeedback!==null){ data.toFeedback=data.tempToFeedback; } if (data.tempSwitchNotes!==null){ data.switchingNotes=data.tempSwitchNotes; } if (data.editedName!==null){ data.name=data.editedName; } if (data.fileList!==null){ data.fileList=JSON.parse(data.fileList); } // merge all recieved data onto state this.setState(currentState=&gt;{ for (let key of Object.keys(data)){ console.log("setting " + key + " from "+currentState[key]+" to " + data[key]); currentState[key]=data[key]; } return currentState; } , ()=&gt;{ // output new state on callback (doesn't include everything which was merged in...) console.log(JSON.parse(JSON.stringify(this.state))) } ) } </code></pre> <p>Console output during setState</p> <pre><code>setting id from undefined to 214793 setting tnccJobsID from undefined to 214793 setting startDate from undefined to 2020-02-12T08:00:00.000Z setting endDate from undefined to 2020-02-12T09:00:00.000Z setting resourceId from undefined to 99921 setting FKusers from undefined to 99999 setting previousJob from undefined to null setting isInfoBooking from undefined to 0 setting isCSP from undefined to null setting isDAR from undefined to 0 setting hasStarted from undefined to 0 setting hasEnded from undefined to 0 setting isCancelled from undefined to 0 setting FKtogaGroups from undefined to 12327 setting currentStep from undefined to 0 setting adjustedFKjobTypes from undefined to null setting FKjobTypes from undefined to 23 setting lastUpdated from undefined to null setting name from undefined to undefined setting jobTypeID from undefined to 23 setting eventType from undefined to Operational Release setting eventColor from undefined to orange setting eventStyle from undefined to colored setting iconCls from undefined to fas fa-plane-departure setting weight from undefined to 1 setting northDesk from undefined to 1 setting southDesk from undefined to 0 setting switchOutState from undefined to 1 setting feedbackState from undefined to 1 setting feedbackRequired from undefined to 0 setting demandAtRisk from undefined to null setting demandAtRiskApproved from undefined to null setting runwaySteps from undefined to [object Object],[object Object],[object Object],[object Object],[object Object] setting startStep from undefined to 4 setting endStep from undefined to 5 setting fileList from undefined to setting outageList from undefined to [object Object] setting toFeedback from undefined to undefined setting switchingNotes from undefined to undefined </code></pre> <p>Final state as read out in callback</p> <pre><code>updateData: {} fileDrawer: null fileUploading: null showJobDetailModal: false id: 214793 tnccJobsID: 214793 startDate: "2020-02-12T08:00:00.000Z" endDate: "2020-02-12T09:00:00.000Z" resourceId: 99921 FKusers: 99999 previousJob: null isInfoBooking: 0 isCSP: null isDAR: 0 hasStarted: 0 hasEnded: 0 isCancelled: 0 FKtogaGroups: 12327 currentStep: 0 adjustedFKjobTypes: null FKjobTypes: 23 lastUpdated: null jobTypeID: 23 eventType: "Operational Release" eventStyle: "colored" weight: 1 northDesk: 1 southDesk: 0 switchOutState: 1 feedbackState: 1 feedbackRequired: 0 demandAtRisk: null demandAtRiskApproved: null runwaySteps: (5) [{…}, {…}, {…}, {…}, {…}] startStep: 4 endStep: 5 fileList: [] outageList: [{…}] __proto__: Object </code></pre> <p>Image formats as well!</p> <p><a href="https://i.stack.imgur.com/Lf8wH.png" rel="nofollow noreferrer">Code</a></p> <p><a href="https://i.stack.imgur.com/LmXzM.png" rel="nofollow noreferrer">setState Output</a></p> <p><a href="https://i.stack.imgur.com/9fvAX.png" rel="nofollow noreferrer">state as read in callback</a></p> <p>Demo version of code with data in it:</p> <pre><code> import React, { Component } from 'react'; export const JobView = class JobView extends React.PureComponent{ render(){ return null; } } export const JobDetails = class JobDetails extends React.Component{ constructor(props){ super(props); this.state={ // jobData:null, updateData:{}, } this.getJobDetail = this.getJobDetail.bind(this); this.setState = this.setState.bind(this); } componentDidMount(){ this.getJobDetail(); } getJobDetail = async function (){ // get data from server // let response = await window.fetch("/event/events?id="+this.props.job,{cache: "no-cache", credentials: "same-origin"}); // parse returned data // let data = await response.json(); let data = JSON.parse('{"id":5267,"tnccJobsID":5267,"startDate":"2020-02-12T08:00:00.000Z","endDate":"2020-02-12T09:00:00.000Z","resourceId":99921,"FKusers":99999,"previousJob":null,"isInfoBooking":0,"isCSP":null,"isDAR":0,"hasStarted":null,"hasEnded":null,"isCancelled":null,"FKtogaGroups":2830,"currentStep":1,"adjustedFKjobTypes":null,"FKjobTypes":1,"lastUpdated":"2020-01-21T22:30:43.000Z","name":"OCKER HILL 132KV BUS SECTION 120 .","jobTypeID":1,"eventType":"Operational Release","eventColor":"orange","eventStyle":"colored","iconCls":"fas fa-plane-departure","weight":1,"northDesk":1,"southDesk":0,"switchOutState":1,"feedbackState":1,"feedbackRequired":0,"demandAtRisk":null,"demandAtRiskApproved":null,"runwaySteps":[{"step":1,"active":{"icon":"loading","text":"Planning"},"isLast":false,"completed":{"icon":"bars","text":"Planned"}},{"step":2,"active":{"icon":"loading","text":"Negotiating TSC"},"isLast":false,"completed":{"icon":"file-done","text":"TSC Recieved"}},{"step":3,"active":{"icon":"loading","text":"Awaiting Allocation"},"isLast":false,"completed":{"icon":"user","text":"Allocated"}},{"step":4,"active":{"icon":"loading","text":"Waiting to Start"},"isLast":false,"completed":{"icon":"user","text":"Started"}},{"step":5,"active":{"icon":"loading","text":"Switching In Progress"},"isLast":false,"completed":{"icon":"api","text":"Switched"}},{"step":6,"active":{"icon":"loading","text":"Releasing To Safety"},"isLast":true,"completed":{"icon":"check","text":"Released To Safety"}}],"startStep":4,"endStep":6,"fullHistory":[{"time":"2019-11-23T22:58:44.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"hasEnded Changed"},{"time":"2019-11-23T22:58:44.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"hasStarted Changed"},{"time":"2019-11-23T22:58:44.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"isCancelled Changed"},{"time":"2019-11-25T23:03:12.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"hasEnded Changed"},{"time":"2019-11-25T23:03:12.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"hasStarted Changed"},{"time":"2019-11-25T23:03:12.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"isCancelled Changed"},{"time":"2019-11-28T22:59:03.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"hasEnded Changed"},{"time":"2019-11-28T22:59:03.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"hasStarted Changed"},{"time":"2019-11-28T22:59:03.000Z","entryTo":"No","entryFrom":0,"changedBy":"System","message":"isCancelled Changed"},{"time":"2020-01-13T22:39:10.000Z","entryTo":0,"entryFrom":null,"changedBy":"System","message":"isDAR Changed"}],"fileList":"[]","outageList":[]}'); // console.log(JSON.stringify(data)); // couple of minor data manipulation exercises if (data.tempToFeedback!==null){ data.toFeedback=data.tempToFeedback; } if (data.tempSwitchNotes!==null){ data.switchingNotes=data.tempSwitchNotes; } if (data.editedName!==null){ data.name=data.editedName; } if (data.fileList!==null){ data.fileList=JSON.parse(data.fileList); } // merge all recieved data onto state await this.setState((currentState,props)=&gt;{ let newState = {} for (let key of Object.keys(data)){ console.log("setting " + key + " from "+currentState[key]+" to " + data[key]); newState[key]=data[key]; } console.log(newState); return newState; } , ()=&gt;{ // output new state on callback (doesn't include everything which was merged in...) console.log(this.state); } ) } render(){ return JSON.stringify(this.state); } } </code></pre>
3
3,707
Dissolve/combine an Array based on attributes
<p>I have an array that i made by combining two other arrays. The new array has all the data from the original arrays joined based on an attribute (id). I would like to make a new array that combines all the attribute (id)values into one string without duplicating the data. The data has many different (Attribute and AttributeValue) pairs but the rest of the data is the same. here is a two examples of the data that come out:</p> <pre><code> 0: id: "00ABCD-0003" AccessionID: "UWAR_007_Test" Attribute: "Object Type" AttributeValue: "Glass" BoxNumber: "2000" CatalogDate: null Cataloger: "rkirkwo2@uwyo.edu" FSNumber: null FreeformValue: null ProjectNumber: "#154 WAPA" SiteID: "00ABCD" Units: null 1: id: "00ABCD-0003" AccessionID: "UWAR_007_Test" Attribute: "Glass Material Type" AttributeValue: "Aluminosilicate glass" BoxNumber: "2000" CatalogDate: null Cataloger: "rkirkwo2@uwyo.edu" FSNumber: null FreeformValue: null ProjectNumber: "#154 WAPA" SiteID: "00ABCD" Units: null </code></pre> <p>below if the full array of data. Thanks for any help! </p> <p>The data will be used to print out tags for a museum to put into bags that the artifacts will be stored in. So i need all the data i can get without duplicating anything.</p> <pre><code> listArray =[{"id":"00ABCD-0003","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":"2000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Object Type","AttributeValue":"Glass","FreeformValue":null,"Units":null},{"id":"00ABCD-0003","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":"2000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Glass Material Type","AttributeValue":"Aluminosilicate glass","FreeformValue":null,"Units":null},{"id":"00ABCD-0003","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":"2000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Color","AttributeValue":"Brown","FreeformValue":null,"Units":null},{"id":"00ABCD-0003","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":"2000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Glass Object Type","AttributeValue":"Bead","FreeformValue":null,"Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Datum ID (if known)","AttributeValue":null,"FreeformValue":"NAD83","Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Object Type","AttributeValue":"Concrete","FreeformValue":null,"Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Concrete Object Type","AttributeValue":"General Building Material","FreeformValue":null,"Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Concrete Material Type","AttributeValue":"Cellular concrete","FreeformValue":null,"Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Provenience","AttributeValue":"Surface Collection","FreeformValue":null,"Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Datum Location","AttributeValue":"UTMs","FreeformValue":null,"Units":null},{"id":"00ABCD-0001","SiteID":"00ABCD","AccessionID":"UWAR_007_Test","ProjectNumber":"#154 WAPA","FSNumber":"f2","BoxNumber":"1000","ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"UTM Zone","AttributeValue":"12N","FreeformValue":null,"Units":null},{"id":"00ABCD-0002","SiteID":"00ABCD","AccessionID":"UWAR_010_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":null,"ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Object Type","AttributeValue":"Metal","FreeformValue":null,"Units":null},{"id":"00ABCD-0002","SiteID":"00ABCD","AccessionID":"UWAR_010_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":null,"ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Metal Material Type","AttributeValue":"Brass","FreeformValue":null,"Units":null},{"id":"00ABCD-0002","SiteID":"00ABCD","AccessionID":"UWAR_010_Test","ProjectNumber":"#154 WAPA","FSNumber":null,"BoxNumber":null,"ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Metal Object Type","AttributeValue":"Axe","FreeformValue":null,"Units":null},{"id":"00ABCD-0004","SiteID":"00ABCD","AccessionID":"UWAR-125-2019-14","ProjectNumber":"#190","FSNumber":null,"BoxNumber":null,"ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Object Type","AttributeValue":"Rubber","FreeformValue":null,"Units":null},{"id":"00ABCD-0004","SiteID":"00ABCD","AccessionID":"UWAR-125-2019-14","ProjectNumber":"#190","FSNumber":null,"BoxNumber":null,"ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Rubber Object Type","AttributeValue":"Tire","FreeformValue":null,"Units":null},{"id":"00ABCD-0004","SiteID":"00ABCD","AccessionID":"UWAR-125-2019-14","ProjectNumber":"#190","FSNumber":null,"BoxNumber":null,"ArtifactCount":null,"Cataloger":"rkirkwo2@uwyo.edu","CatalogDate":null,"ArtifactNotes":null,"Attribute":"Rubber Material Type","AttributeValue":"Natural Rubber","FreeformValue":null,"Units":null}] </code></pre> <p>For example, I would like to see:</p> <pre><code> id: "00ABCD-0003" AccessionID: "UWAR_007_Test" Attribute: "Object Type" AttributeValue: "Glass" Attribute: "Glass Material Type" AttributeValue: "Aluminosilicate glass" BoxNumber: "2000" CatalogDate: null Cataloger: "rkirkwo2@uwyo.edu" FSNumber: null FreeformValue: null ProjectNumber: "#154 WAPA" SiteID: "00ABCD" Units: null </code></pre>
3
2,420
Python - Newspaper Library - Why is it missing sizable portions of articles?
<p>I'm using the newspaper library, V. 2.7 found <a href="http://newspaper.readthedocs.io/en/latest/" rel="nofollow">here</a>. </p> <p>When I download, parse, and print the text, it gives me a much smaller portion of the article than exists in reality. Why is this? Is there any way to fix this? </p> <p>Here is my code:</p> <pre><code>from newspaper import Article url = "http://www.nytimes.com/2010/10/07/us/politics/07manchin.html" article_object = Article(url, language = 'en') article_object.download() article_object.parse() article_object.text </code></pre> <p>If you look at what it prints out, and <strong><a href="http://www.nytimes.com/2010/10/07/us/politics/07manchin.html" rel="nofollow">compares with the actual article online</a></strong>, one finds that the article.text skips over the first 7-8 paragraphs of the actual article. Any way to make sure the "full" article is captured?</p> <p>Here's the output of article_object.text:</p> <blockquote> <p>u'The national Republican Party has smelled blood and is spending millions on television ads here as part of its drive to retake the Senate. One new ad shows men in baseball caps predicting that Mr. Manchin will transform into \u201cWashington Joe,\u201d declaring, \u201cWe\u2019ve got to stop Obama.\u201d\n\nPhoto\n\nMr. Manchin thought he had punched all the right buttons in this state with a Democratic majority but conservative values. He won his second term as governor in 2008 with 70 percent of the vote and has garnered praise for fiscal responsibility; even Mr. Raese calls him a good governor. He has been endorsed by the Chamber of Commerce, the National Rifle Association and both the coal industry and the mine workers.\n\nMr. Manchin is highlighting his conservative credentials and record of independence and he has accused his opponent of waging a campaign of \u201cfear and smear.\u201d But the anti-Obama message appears to be resonating with some residents \u2014 perhaps the same voters who gave the state to Senator John McCain and President Bush in the last three presidential elections.\n\n\u201cManchin has been a great governor, but I\u2019m going to vote for Raese,\u201d said Jeff Whittington, 41, a tire distributor in Charleston. \u201cI think Manchin will get to the Senate and be a rubber stamp for Obama,\u201d he said, repeating Mr. Raese\u2019s message almost word for word.\n\nIn a state where coal is seen as the fount of prosperity, Mr. Raese has seized on what he calls ambiguous statements by Mr. Manchin on proposals for a cap-and-trade system to reduce greenhouse gases. Mr. Manchin now speaks clearly on the issue: he is firmly against cap-and-trade and a carbon tax, he emphasized in the interview.\n\nOn Wednesday, Mr. Manchin had an opportunity to underscore his support for coal and to distance himself from the president. With the head of the coal producers\u2019 association at his side in the state Capitol, he announced that the state was suing two federal agencies, seeking to reverse the stricter controls on mountain-top coal mining adopted in 2009 by the Obama administration.\n\nAdvertisement Continue reading the main story\n\nDiscussing the suit against the Environmental Protection Agency and the Army Corps of Engineers, Mr. Manchin said that the more stringent procedures were unlawful and had harmed the state by slowing new mining projects to a trickle, and he accused the Obama administration of trying \u201cto destroy our coal industry and way of life.\u201d\n\nThe E.P.A. responded that its actions were legally and scientifically sound.\n\nMr. Manchin, independent experts and even the West Virginia Coal Association have taken exception to a Raese ad accusing Mr. Manchin of passing a state law that \u201celiminates 25 percent of coal usage in our power plants.\u201d\n\nIn fact, the law calls for progress in new energy technologies that include cleaner coal, and it had the support of the industry.\n\nMr. Raese has also lambasted the governor for past statements welcoming the Obama health plan; Mr. Manchin says that some core elements of the plan, like protecting children\u2019s coverage, are good but that others should be repealed. Mr. Raese calls the health plan \u201cpure, unadulterated socialism\u201d that should be discarded entirely, a message that appeals to many small-business owners.\n\nPhoto\n\nMr. Raese is a brawny and self-confident man who has run unsuccessfully for the Senate and for governor before and now feels currents flowing his way. \u201cHow do you put together a business plan when you have Obamacare facing you, when you\u2019ve got cap-and-trade facing you?\u201d he asked in an interview at the Republican office in Morgantown, his home base.\n\nMr. Raese runs limestone mines and a steel-fabrication company and is part owner of a radio network and a newspaper. He has at least three homes around the country, and his wife lives in their home in Palm Beach, Fla., while he has kept his residence in West Virginia.\n\nWhile Mr. Raese\u2019s anti-Washington message has wide appeal, his unequivocal support for Nafta and free trade and his opposition to unions may not help him in a state with a blue-collar heritage. Mr. Manchin\u2019s campaign has run ads featuring Mr. Raese boasting about his inherited wealth and highlighting his opposition to minimum wages and other worker protections.\n\nIn interviews across the state, some residents said that while Mr. Raese can seem arrogant, they admired his record of creating jobs and were ready to send a new face to Washington rather than elect a man they see as a career politician.\n\nAdvertisement Continue reading the main story\n\nThe only polls published so far were automated \u2014 done without personal interviews \u2014 and are not widely accepted as reliable. But private polling by both camps indicates an unexpectedly close race.\n\nFord Frances, 53, a lawyer in Charleston, said he likes Mr. Manchin as governor \u2014 Mr. Manchin will retain his job if he loses the Senate race \u2014 but that he is leaning toward voting for Mr. Raese because he worries about a skyrocketing federal deficit and thinks government has too big a role in the economy.\n\nOthers, including Cheryl Bonner, 64, of Fairmont, said they thought it was unfair to paint Mr. Manchin with the excesses of Washington. \u201cHe\u2019s been for West Virginia, and I\u2019m leaning toward voting for him,\u201d said Ms. Bonner, who had to start working again, as a store clerk, because her and her husband\u2019s Social Security and pension checks did not cover the bills. She hopes that retirees will be protected, whoever wins, she said.\n\nSome residents said Mr. Manchin was just unlucky to be running for national office this year. \u201cProbably at any other time he\u2019d have gotten my vote,\u201d said a 51-year-old credit analyst in Charleston, an economic conservative who voted for Mr. Manchin in 2008 but is troubled by the administration\u2019s economic policies.\n\n\u201cPutting him in that Senate seat would enhance the Democrats\u2019 position,\u201d said the man, who declined to give his name because his company has dealings with the governor\u2019s office. \u201cWe\u2019d rather keep him here as governor.\u201d'</p> </blockquote>
3
2,010
Using Future with ExecutorService
<p>I need to execute two tasks in parallel and wait for them to complete. Also I need the result from the second task, for that I am using <code>Future</code>. </p> <p>My question is that DO I need <code>executor.awaitTermination</code> to join the tasks or <code>Future.get()</code> will take care of it. Also is there a better way to achieve this with Java 8?</p> <pre><code>public class Test { public static void main(String[] args) { test(); System.out.println("Exiting Main"); } public static void test() { System.out.println("In Test"); ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -&gt; { for(int i = 0 ; i&lt; 5 ; i++) { System.out.print("["+i+"]"); try { Thread.sleep(1000); } catch (Exception e) {e.printStackTrace();} } }); Future&lt;String&gt; result = executor.submit(() -&gt; { StringBuilder builder = new StringBuilder(); for(int i = 0 ; i&lt; 10 ; i++) { System.out.print("("+i+")"); try { Thread.sleep(1000); } catch (Exception e) {e.printStackTrace();} builder.append(i); } return builder.toString(); }); System.out.println("shutdown"); executor.shutdown(); // DO I need this code : START System.out.println("awaitTermination"); try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { System.out.println("Error"); } // DO I need this code : END System.out.println("Getting result"); try { System.out.println(result.get()); } catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} System.out.println("Exiting Test"); } } </code></pre> <p>OUTPUT with <strong>awaitTermination</strong>:</p> <pre><code>In Test [0]shutdown (0)awaitTermination [1](1)[2](2)[3](3)[4](4)(5)(6)(7)(8)(9)Getting result 0123456789 Exiting Test Exiting Main </code></pre> <p>OUTPUT without <strong>awaitTermination</strong>:</p> <pre><code>In Test [0]shutdown Getting result (0)[1](1)[2](2)[3](3)[4](4)(5)(6)(7)(8)(9)0123456789 Exiting Test Exiting Main </code></pre>
3
1,133
PHP for loop stops after the first iteration
<p>For a project I am trying to do something in PHP. It requires a <code>for</code> loop and houses one as well. The <code>for</code> loop inside the initial loop functions as expected. It loops through the variables and stops once <code>$i</code> is equal to <code>count($tasks)</code></p> <p>However, when I copy paste the exact same loop on top of it, now working with <code>$tasklists</code> the loop stops after just one iteration. Mind you that when I tested <code>count($tasklists)</code> does return for example 3 and in the loop when I echo <code>$i</code> it does echo 0 the first time.</p> <p>Here is the code with a bunch of comments.</p> <pre><code>// First let's break up all the tasklists the project has $tasklists = explode('&amp;', $data['proj_tasklists']); // Now lets get all the tasks for each tasklist for($i = 0; $i &lt; count($tasklists); $i++) { // Get list_tasks from the tasklist $sql_get = "SELECT * FROM tasklists WHERE list_id='".$tasklists[$i]."'"; $result_get = mysqli_query($con, $sql_get); if($result_get) { // Now load in the variable while($results = mysqli_fetch_array($result_get)) { $data['list_tasks'] = $results['list_tasks']; }; // Now let's break that up $tasks = explode('&amp;',$data['list_tasks']); // Now reset list_tasks $data['list_tasks'] = ''; // Do something for every task for($i = 0; $i &lt; count($tasks); $i++) { // And get the info for the set task $sql_get = "SELECT * FROM tasks WHERE task_id='".$tasks[$i]."'"; $result_get = mysqli_query($con, $sql_get); if($result_get) { // Now load it's task_user in a variable while($results = mysqli_fetch_array($result_get)) { $data['task_user'] = $results['task_user']; }; // Check if that is the same as that of the user whom was deleted if($data['task_user'] == $data['user_id']) { // If the Id is the same update it to '' $sql_update = "UPDATE tasks SET task_user='' WHERE task_id='".$tasks[$i]."'"; if (mysqli_query($con, $sql_update)) { // If that worked then add this to the list of addjusted IDs // First check if the variable is empty or not if($data['adjusted'] == '') { // Add the ID plainly $data['adjusted'] = $tasks[$i]; } else { // Otherwise preceed the ID with an &amp; $data['adjusted'] = $data['adjusted'].'&amp;'.$tasks[$i]; }; } else { // Return an error echo json_encode(array( 'status'=&gt;'unsuccesful', 'where'=&gt;3 )); // Exit the php before it returns an succes state exit(); }; }; // Now reset task_user $data['task_user'] = ''; } else { // Return an error echo json_encode(array( 'status'=&gt;'unsuccesful', 'where'=&gt;2 )); // Exit the php before it returns an succes state exit(); }; }; } else { // Return an error echo json_encode(array( 'status'=&gt;'unsuccesful', 'where'=&gt;1 )); // Exit the php before it returns an succes state exit(); }; }; </code></pre>
3
1,935
error 400 bad request with XEP-0055?
<p>I got possible fields from my server:</p> <pre><code>&lt;iq xmlns="jabber:client" from="vjud.company.com" to="testuser@company.com/iPhone" id="search1" type="result"&gt;&lt;query xmlns="jabber:iq:search"&gt; &lt;instructions&gt;You need an x:data capable client to search&lt;/instructions&gt; &lt;x xmlns="jabber:x:data" type="form"&gt; &lt;title&gt;Search users in vjud.company.com&lt;/title&gt; &lt;instructions&gt;Fill in the form to search for any matching Jabber User (Add * to the end of field to match substring) &lt;/instructions&gt; &lt;field type="text-single" label="User" var="user"/&gt; &lt;field type="text-single" label="Full Name" var="fn"/&gt; &lt;field type="text-single" label="Name" var="first"/&gt; &lt;field type="text-single" label="Middle Name" var="middle"/&gt; &lt;field type="text-single" label="Family Name" var="last"/&gt; &lt;field type="text-single" label="Nickname" var="nick"/&gt; &lt;field type="text-single" label="Birthday" var="bday"/&gt; &lt;field type="text-single" label="Country" var="ctry"/&gt; &lt;field type="text-single" label="City" var="locality"/&gt; &lt;field type="text-single" label="Email" var="email"/&gt; &lt;field type="text-single" label="Organization Name" var="orgname"/&gt; &lt;field type="text-single" label="Organization Unit" var="orgunit"/&gt; &lt;/x&gt; &lt;/query&gt; &lt;/iq&gt; </code></pre> <p>Suppose I want to search a user with JID <code>admin@company.com</code></p> <p>Composed request wil look like this:</p> <pre><code>XMPPIQ *iq2 = [[XMPPIQ alloc] init]; [iq2 addAttributeWithName:@"type" stringValue:@"set"]; [iq2 addAttributeWithName:@"from" stringValue:@"testuser@company.com"]; [iq2 addAttributeWithName:@"to" stringValue:@"vjud.company.com"]; [iq2 addAttributeWithName:@"id" stringValue:@"search1"]; XMPPElement *query2 = [XMPPElement elementWithName:@"query"]; [query2 setXmlns:@"jabber:iq:search"]; XMPPElement *user = [XMPPElement elementWithName:@"user"]; [user setStringValue:@"admin"]; [iq2 addChild:query2]; [query addChild:user]; </code></pre> <p>The error stanza:</p> <pre><code>&lt;iq xmlns="jabber:client" from="vjud.company.com" to="testuser@company.com/iPhone" type="error" id="search1"&gt; &lt;query xmlns="jabber:iq:search"/&gt; &lt;error code="400" type="modify"&gt; &lt;bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/&gt; &lt;/error&gt; &lt;/iq&gt; </code></pre> <p>So, basically there are 2 questions:</p> <ol> <li>Why there is no <code>&lt;/query&gt;</code> element in response?</li> <li>Is it the actual reason of the error?</li> </ol> <p><strong>-The server's response should look like this-</strong></p> <p>Big thanks to @legoscia user, in case request was composed right, you will get something like this(notice <code>&lt;item&gt;</code> element):</p> <pre><code> &lt;iq xmlns="jabber:client" from="vjud.company.com" to="testuser@company.com/iPhone" id="search1" type="result»&gt; &lt;query xmlns="jabber:iq:search"&gt;&lt;x xmlns="jabber:x:data" type="result»&gt; &lt;title&gt;Search Results for vjud.company.com&lt;/title&gt; &lt;reported&gt; &lt;field type="text-single" label="Jabber ID" var="jid»/&gt; &lt;field type="text-single" label="Full Name" var="fn»/&gt; &lt;field type="text-single" label="Name" var="first»/&gt; &lt;field type="text-single" label="Middle Name" var="middle»/&gt; &lt;field type="text-single" label="Family Name" var="last"/&gt;&lt;field type="text-single" label="Nickname" var="nick»/&gt; &lt;field type="text-single" label="Birthday" var="bday»/&gt; &lt;field type="text-single" label="Country" var="ctry»/&gt; &lt;field type="text-single" label="City" var="locality»/&gt; &lt;field type="text-single" label="Email" var="email»/&gt; &lt;field type="text-single" label="Organization Name" var="orgname"/&gt;&lt;field type="text-single" label="Organization Unit" var="orgunit»/&gt; &lt;/reported&gt; &lt;item&gt; &lt;field var="jid»&gt; &lt;value&gt;admin@company.com&lt;/value&gt; &lt;/field&gt; &lt;field var="fn"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="last"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="first"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="middle"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="nick"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="bday"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="ctry"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="locality"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="email"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="orgname"&gt;&lt;value/&gt;&lt;/field&gt; &lt;field var="orgunit"&gt;&lt;value/&gt;&lt;/field&gt;&lt;/item&gt; &lt;/x&gt; &lt;/query&gt; &lt;/iq&gt; </code></pre> <p>If there is no matches,you will just receive <code>&lt;reported&gt;</code> element with lots of fields. You may want to have look at <a href="https://stackoverflow.com/questions/26800596/xep-0055-with-ios-and-ejabberd">this</a> as well.</p>
3
2,017
Getting data from a input textfield then use it in MySQL statement on the same page
<p>sorry for the bulk of code :)</p> <p>I need to input a client name in the input textfield name clientname then i need to output the client information from my database when i click a button name loadcliinfo. But the problem is <strong> i don't know how will i get the data inputted in clientname? </strong> so I used <strong>$_POST['clientname']</strong>. The code is not working.</p> <p>the code i pasted below is located on the same file.</p> <pre><code> &lt;tr&gt; &lt;td width="6"&gt;&lt;/td&gt; &lt;td width="155"&gt;Client Name&lt;font color="#990000"&gt;*&lt;/font&gt;&lt;/td&gt; &lt;td width="218"&gt;&lt;input type="text" name="clientname" id="clientname" required= "required" class="forinput" value="&lt;?php echo $clientname ?&gt;"/&gt;&lt;/td&gt; &lt;td width="148"&gt;&lt;input type="button" name="loadcliinfo" value="Load Client Info" onClick="loadclientinfo()"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6"&gt;&lt;/td&gt; &lt;td width="155"&gt;Client Address&lt;font color="#990000"&gt;*&lt;/font&gt;&lt;/td&gt; &lt;td width="218"&gt;&lt;p id="clientadd" class="readonly"&gt;&lt;/p&gt;&lt;/td&gt; &lt;td width="148"&gt;Contact Name&lt;font color="#990000"&gt;*&lt;/font&gt;&lt;/td&gt; &lt;td width="230"&gt;&lt;p id="clientcontactname" class="readonly"&gt;&lt;/p&gt;&lt;/td&gt; &lt;td width="8"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="shade"&gt; &lt;td width="6"&gt;&lt;/td&gt; &lt;td width="155"&gt;Email Address&lt;font color="#990000"&gt;*&lt;/font&gt;&lt;/td&gt; &lt;td width="218"&gt;&lt;p id="clientemail" class="readonly"&gt;&lt;/p&gt;&lt;/td&gt; &lt;td width="148"&gt;Contact No&lt;font color="#990000"&gt;*&lt;/font&gt;&lt;/td&gt; &lt;td width="230"&gt;&lt;p id="clientaddcontact" class="readonly"&gt;&lt;/p&gt;&lt;/td&gt; &lt;td width="8"&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p><strong>my php code</strong> </p> <pre><code> &lt;?php $name=isset($_POST['clientname'])? $_POST['clientname'] : ''; </code></pre> <p>I get the data using this statement <strong>isset($_POST['clientname'])? $_POST['clientname'] : '' </strong> and store it in the variable $name but when i output the variable its empty. </p> <pre><code> $csql="Select address, email, contactperson, contactno from client where name='$name'"; $result=$db-&gt;prepare($csql); $result-&gt;execute(); while($resu= $result-&gt;fetch(PDO::FETCH_ASSOC)) { echo '&lt;input type="hidden" id="add" value="'.$resu['address'].'"/&gt;'; echo '&lt;input type="hidden" id="email" value="'.$resu['email'].'"/&gt;'; echo '&lt;input type="hidden" id="contactperson" value="'.$resu['contactperson'].'"/&gt;'; echo '&lt;input type="hidden" id="contactno" value="'.$resu['contactno'].'"/&gt;'; } ?&gt; </code></pre> <p><strong>My loadclientinfo function</strong></p> <pre><code> &lt;script&gt; function loadclientinfo() { var add=document.getElementById("add"); var email=document.getElementById("email"); var contactperson=document.getElementById("contactperson"); var contactno=document.getElementById("contactno"); document.getElementById("clientadd").innerHTML = add.value; document.getElementById("clientemail").innerHTML = email.value; document.getElementById("clientcontactname").innerHTML = contactperson.value; document.getElementById("clientcontact").innerHTML = contactno.value; } &lt;/script&gt; </code></pre> <p>I think <strong>getting data from clientname is the problem.</strong> Is there any way i could get the data from clientname on the same page? thanks :D </p>
3
1,916
NoneType' object has no attribute 'shape
<p>I am trying to do my detection but dont know why this error is comming up dont know whats the issue with this when i start the detection the cam stops and it gives the shape error of nonetype. It was running before but dont know what happen and its stop working and giving me this error.Can anyone can help me.</p> <pre><code>from flask import Flask,render_template,Response import cv2 import numpy as np app = Flask(__name__) net = cv2.dnn.readNet('project-files/yolov4-custom.cfg', 'project-files/yolov4.weights') face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') scale_factor =1.3 with open(&quot;project-files/coco.names&quot;, &quot;r&quot;) as f: classes = f.read().splitlines() font = cv2.FONT_HERSHEY_PLAIN colors = np.random.uniform(0, 255, size=(len(classes), 3)) @app.route('/') def index(): return render_template('index.html') @app.route('/page1/') def page1(): return render_template('page1.html') def obdetect(): net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) cap = cv2.VideoCapture(0) while True: _, img = cap.read() height, width, _ = img.shape blob = cv2.dnn.blobFromImage(img, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False) net.setInput(blob) output_layers_names = net.getUnconnectedOutLayersNames() layeroutputs = net.forward(output_layers_names) boxes = [] confidences = [] class_ids = [] for output in layeroutputs: for detection in output: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence &gt; 0.5: center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append((float(confidence))) class_ids.append(class_id) # it will remove the duplicate detections in our detection indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.2, 0.4) if len(indexes) &gt; 0: for i in indexes.flatten(): x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = str(round(confidences[i], 2)) color = colors[i] cv2.rectangle(img, (x, y), (x + w, y + h), color, 2) cv2.putText(img, label + &quot; &quot; + confidence, (x, y + 20), font, 2, (255, 0, 0), 2) _, jpeg = cv2.imencode('.jpg', img) yield (b'--frame\r\n' b'Content-Type:image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n') cap.release() @app.route('/video_feed') def video_feed(): return Response(obdetect(), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(threaded=True) </code></pre> <p>error</p> <pre><code>(base) C:\Users\sanja\OneDrive\Documents\flask&gt;flask run * Serving Flask app &quot;main&quot; * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [07/Jun/2021 18:43:41] &quot;←[37mGET / HTTP/1.1←[0m&quot; 200 - 127.0.0.1 - - [07/Jun/2021 18:43:41] &quot;←[37mGET /static/logo-1-144x144.png HTTP/1.1←[0m&quot; 200 - 127.0.0.1 - - [07/Jun/2021 18:43:43] &quot;←[37mGET /page1/ HTTP/1.1←[0m&quot; 200 - 127.0.0.1 - - [07/Jun/2021 18:43:55] &quot;←[37mGET /video_feed HTTP/1.1←[0m&quot; 200 - [ WARN:1] global C:\project files\opencv-4.5.2\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback Error on request: Traceback (most recent call last): File &quot;C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\serving.py&quot;, line 323, in run_wsgi execute(self.server.app) File &quot;C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\serving.py&quot;, line 314, in execute for data in application_iter: File &quot;C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\wsgi.py&quot;, line 506, in __next__ return self._next() File &quot;C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\wrappers\base_response.py&quot;, line 45, in _iter_encoded for item in iterable: File &quot;C:\Users\sanja\OneDrive\Documents\flask\main.py&quot;, line 31, in obdetect height, width, _ = img.shape AttributeError: 'NoneType' object has no attribute 'shape' </code></pre>
3
2,235
I want to add new option to table row on hover
<p>I want to add a new option to the table cell on hover in ReactJS:</p> <p>Here is the screenshot:</p> <p><a href="https://i.stack.imgur.com/n44cB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n44cB.png" alt="enter image description here" /></a></p> <p>Here what I have done so far:</p> <p><a href="https://i.stack.imgur.com/LdMXh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LdMXh.png" alt="enter image description here" /></a></p> <p>I don't know how to hover on it and change the table cell of material UI and add that remove option to it.</p> <p>Here is my ReactJS:</p> <pre><code> &lt;TableRow key={row.name}&gt; &lt;TableCell style={{ verticalAlign: 'middle', display: 'flex', alignItems: 'flex-end' }} align=&quot;left&quot;&gt; &lt;SupervisedUserCircleRoundedIcon style={{ marginRight: '5px' }} /&gt; {row.importedGroups} &lt;/TableCell&gt; &lt;TableCell align=&quot;left&quot;&gt;{row.importedAs}&lt;/TableCell&gt; {/* &lt;TableCell align=&quot;left&quot;&gt; &lt;Select value={selected} onChange={handleChange} name=&quot;select_importas&quot; style={{ minWidth: 120, font: 'normal normal 600 16px/22px Open Sans' }} displayEmpty &gt; &lt;MenuItem value=&quot;&quot;&gt;Normal Group&lt;/MenuItem&gt; &lt;MenuItem value=&quot;super_Group&quot;&gt;Super Group&lt;/MenuItem&gt; &lt;/Select&gt; &lt;/TableCell&gt; */} &lt;/TableRow&gt; </code></pre> <p>Here is my CSS:</p> <pre><code>.MuiTableCell-root { border-bottom: none !important; padding: 20px; } </code></pre> <p>I just want to change the color of Table cell color on hover and add a visible option of <code>Remove</code> to it as shown in the screenshot above in material UI.</p>
3
1,401
Cannot operate on year value of regular expression
<p>This is my first question here so please forgive and educate on any formatting errors. I am new to Python and going through automate the boring stuff. Decided to expand the date detection project by using the clipboard and formatting some things also. The problem I have is in any operation taken on the year part of the REGEX. I have commented out my last attempt to validate the year and gave up and changed the REGEX to only find dates from 1000 to 2999 and skipped code validation of the dates. I now need to validate leap years but I'm back to having to work with the year variable, but once again no operation has any effect. Basically the problem is I can extract the year value and display it but I cannot modify it or do checks against it.</p> <pre><code>#! python3 #! detect dates in a block of text import pyperclip import re #!import numpy as np text = str(pyperclip.paste()) def datedetection(text): dateRegex = re.compile( r&quot;&quot;&quot;( (\d|\d\d) #! match day (/{1}) #! match / (\d|\d\d) #! match month (/{1}) #! match / ([1|2][0-9][0-9][0-9]) #! match year )&quot;&quot;&quot;, re.VERBOSE, ) matches = [] for groups in dateRegex.findall(text): day = str(groups[1]) slash1 = str(groups[2]) month = str(groups[3]) slash2 = str(groups[4]) year = str(groups[5]) month_range_30 = [&quot;04&quot;, &quot;06&quot;, &quot;09&quot;, &quot;11&quot;] month_range_31 = [&quot;01&quot;, &quot;03&quot;, &quot;05&quot;, &quot;07&quot;, &quot;08&quot;, &quot;10&quot;, &quot;12&quot;] month_range_Feb = [&quot;02&quot;] #!year_range = np.arange(1000, 3000, 1).tolist() if len(day) == 1: day = &quot;0&quot; + day else: day = day if len(month) == 1: month = &quot;0&quot; + month else: month = month if month in month_range_31: if int(day) &gt; 31: day = &quot;Too many days in a month with only 31 days.&quot; slash1 = month = slash2 = year = &quot;&quot; elif month in month_range_30: if int(day) &gt; 30: day = &quot;Too many days in a month with only 30 days.&quot; slash1 = month = slash2 = year = &quot;&quot; elif month in month_range_Feb: if int(day) &gt; 29: day = &quot;Too many days in February.&quot; slash1 = month = slash2 = year = &quot;&quot; elif int(month) &gt; 12: day = &quot;Found an invalid month.&quot; slash1 = month = slash2 = year = &quot;&quot; elif month in month_range_Feb: if ( int(day) == 29 and (int(year) % 4 == 0) and (int(year) % 400 == 0) and (int(year) % 100 == 0) ): day = day elif month in month_range_Feb: if ( int(day) == 29 and (int(year) % 4 == 0) and (int(year) % 100 != 0) ): day = &quot;Found an invalid leap year.&quot; slash1 = month = slash2 = year = &quot;&quot; #!elif year not in year_range: #!day = &quot;Year is out of range.&quot; #!slash1 = month = slash2 = year = &quot;&quot; dates = &quot;&quot;.join([day, slash1, month, slash2, year]) matches.append(dates) if len(matches) &gt; 0: pyperclip.copy(&quot;\n&quot;.join(matches)) print(&quot;Copied to clipboard:&quot;) print(&quot;\n&quot;.join(matches)) else: print(&quot;No dates found.&quot;) datedetection(text) </code></pre>
3
1,638
Printing an array of structs in C
<p>I'm trying to print an array of structs that contain two strings. However my print function does not print more than two indices of the array. I am not sure why because it seems to me that the logic is correct.</p> <p>This is the main function</p> <pre><code> const int MAX_LENGTH = 1024; typedef struct song { char songName[MAX_LENGTH]; char artist[MAX_LENGTH]; } Song; void getStringFromUserInput(char s[], int maxStrLength); void printMusicLibrary(Song library[], int librarySize); void printMusicLibraryTitle(void); void printMusicLibrary (Song library[], int librarySize); void printMusicLibraryEmpty(void); int main(void) { // Announce the start of the program printf("%s", "Personal Music Library.\n\n"); printf("%s", "Commands are I (insert), S (sort by artist),\n" "P (print), Q (quit).\n"); char response; char input[MAX_LENGTH + 1]; int index = 0; do { printf("\nCommand?: "); getStringFromUserInput(input, MAX_LENGTH); // Response is the first character entered by user. // Convert to uppercase to simplify later comparisons. response = toupper(input[0]); const int MAX_LIBRARY_SIZE = 100; Song Library[MAX_LIBRARY_SIZE]; if (response == 'I') { printf("Song name: "); getStringFromUserInput(Library[index].songName, MAX_LENGTH); printf("Artist: "); getStringFromUserInput(Library[index].artist, MAX_LENGTH); index++; } else if (response == 'P') { // Print the music library. int firstIndex = 0; if (Library[firstIndex].songName[firstIndex] == '\0') { printMusicLibraryEmpty(); } else { printMusicLibraryTitle(); printMusicLibrary(Library, MAX_LIBRARY_SIZE); } </code></pre> <p>This is my printing the library function</p> <pre><code> // This function will print the music library void printMusicLibrary (Song library[], int librarySize) { printf("\n"); bool empty = true; for (int i = 0; (i &lt; librarySize) &amp;&amp; (!empty); i ++) { empty = false; if (library[i].songName[i] != '\0') { printf("%s\n", library[i].songName); printf("%s\n", library[i].artist); printf("\n"); } else { empty = true; } } } </code></pre>
3
1,146
Intermittent Stale Element Reference Exception
<p>I am writing a python selenium script to scrape data from a website. The script reads the employee identification number, name and date of birth from a CSV file and copies it to a Dictionary &amp; then enters data from each line into a form and then clicks a submit button. The next page that appears asks for the years of employment history which defaults to one year which is fine for my use case so the only thing the script does on this page is click the search button. The script works consistently for approximately 20 to 35 employees. But at some point the script will fail with the following stale element reference exception:</p> <blockquote> <p>Message: The element reference of <strong></strong> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed</p> </blockquote> <p>The relevant HTML for the Search button is:</p> <pre><code>&lt;div data-container=&quot;&quot; class=&quot;btn-label OSInline&quot;&gt;Search&lt;/div&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;div data-container=&quot;&quot; style=&quot;text-align: center;&quot; id=&quot;b8-ResetFilters2&quot;&gt;&lt;a data-link=&quot;&quot; href=&quot;#&quot; style=&quot;width: auto;&quot;&gt;&lt;span data-expression=&quot;&quot; style=&quot;width: auto;&quot;&gt;Reset Search&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div </code></pre> <p>The relevant Python Selenium code is (GO DOWN TO &quot;*****&quot; TO SEE WHERE I THE SEARCH BUTTON IS):</p> <pre><code># Open MOCemployees.csv as readable file &amp; then convert to a Python Dictionary with open('MOCemployees.csv', 'r') as MOCemployees.: MOCemployees.Dict = csv.DictReader(MOCemployees.) for line in MCpatientsDict: MOCEmployeeNumber = (line['MCID']) LastName = (line['LastName']) FirstName = (line['FirstName']) DOB = (line['DOB']) # Explicit Wait for MOCEmployeeNumberInput then click on it and enter MOCEmployeeNumber MOCEmployeeNumberInput = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.ID, 'b7-MOCEmployeeNumberInput'))) # Locate LastNameInput and click on it and enter LastName LastNameInput = driver.find_element(By.ID, 'b7-LastNameInput') LastNameInput.click() LastNameInput.send_keys(LastName) # Locate FirstNameInput and click on it and enter FirstNameI FirstNameInput = driver.find_element(By.ID, 'b7-FirstNameInput') FirstNameInput.click() FirstNameInput.send_keys(FirstName) # Locate DOBInput and click on it and enter DOB DOBInput = driver.find_element(By.ID, 'b7-DOBInput') DOBInput.click() #DOBInput.send_keys('YYYY-MM-DD') DOBInput.send_keys(DOB) # Explicit Wait for Submit Button &amp; click on it SubmitButton = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.margin-top-m'))) SubmitButton.click() # *****Explicit Wait for Search Button &amp; click on it to accept default 1 year of data *****THIS BUTTON IS NOT CLICKED INTERMITTENTLY AND THE STALE ELEMENT REFERENCE EXCEPTION OCCURS AT THIS POINT***** SearchButton = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-label'))) SearchButton.click() #Wait time.sleep(3) # print MOCID, NAME &amp; then the value of the value attribute RemainDeductible = (WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, &quot;b8-b36-Input_RemainAmtYr1&quot;))).get_attribute(&quot;value&quot;)) #Save MOCID, Name &amp; Remaining Due to a CSV file POutput = ','.join((MOCEmployeeNumber, LastName, FirstName, DOB, RemainDeductible)) + '\n' #Locate Change Employee Link &amp; click on it SelectButton = driver.find_element(By.CSS_SELECTOR, '#b7-b3-Column4 &gt; div:nth-child(1) &gt; a:nth-child(1) &gt; span:nth-child(1)') SelectButton.click() </code></pre> <p>How can I prevent this stale element reference exception?</p>
3
1,502
Is there a way to only add verified email addresses to Firebase authentication console (React JS)?
<p>I'm trying to create a Firebase authentication system in my React web app. I know how to register an account and I know how to send a verification email out. Upon registration it sends the verification email which is fine, but the account gets added to the Firebase console database before the user has even verified it. I want it to be such that only verified accounts are added to the database.</p> <p>Here is my code:</p> <pre><code>import React, { useState, useEffect, useRef } from 'react' import './join.css' import { Link, useNavigate } from 'react-router-dom' import { auth } from '../firebase' import { createUserWithEmailAndPassword, onAuthStateChanged, sendEmailVerification } from &quot;firebase/auth&quot; export default function Join() { const [registerEmail, setRegisterEmail] = useState(''); const [registerPassword, setRegisterPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [user, setUser] = useState({}); const verificationMessage = useRef(); useEffect(() =&gt; { onAuthStateChanged(auth, (currentUser) =&gt; { setUser(currentUser); }); }, []) const navigate = useNavigate(); const register = async () =&gt; { try { const user = await createUserWithEmailAndPassword(auth, registerEmail, registerPassword); console.log(user); } catch (error) { console.log(error.message); } } const handleSubmit = event =&gt; { if (registerPassword === confirmPassword) { sendEmailVerification(auth.currentUser); verificationMessage.current.style.display = 'block'; register(); event.preventDefault(); } else { alert('Passwords do not match, please try again!'); event.preventDefault(); } } return ( &lt;&gt; &lt;div className=&quot;signup-div&quot;&gt; &lt;h2&gt;Sign Up&lt;/h2&gt; &lt;form onSubmit={handleSubmit}&gt; &lt;fieldset&gt; &lt;label className='labels'&gt;Email:&lt;/label&gt;&lt;br /&gt; &lt;input placeholder='Please enter your email' type=&quot;email&quot; value={registerEmail} onChange={e =&gt; setRegisterEmail(e.target.value)} required /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;label className='labels'&gt;Set Password:&lt;/label&gt;&lt;br /&gt; &lt;input placeholder='Create password' type=&quot;password&quot; value={registerPassword} onChange={e =&gt; setRegisterPassword(e.target.value)} required /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;label className='labels'&gt;Re-type password to confirm:&lt;/label&gt;&lt;br /&gt; &lt;input placeholder=&quot;Confirm password&quot; type=&quot;password&quot; value={confirmPassword} onChange={e =&gt; setConfirmPassword(e.target.value)} required /&gt; &lt;/fieldset&gt; &lt;button type=&quot;submit&quot;&gt;Sign Up&lt;/button&gt; &lt;/form&gt; &lt;div&gt; Already have an account? &lt;Link to=&quot;/login&quot;&gt;Log In&lt;/Link&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className='verification-message' ref={verificationMessage}&gt;Welcome aboard! Please check your inbox and click the link in our verification email to verify your account. This could take upto a few minutes to arrive.&lt;/div&gt; &lt;/&gt; ) } </code></pre>
3
1,600
inline expansion compiles into a function call [c++]
<h2>Introduction:</h2> <p>I have been creating a simple wrapper classes. I randomly found out that <em>(or it appears to be)</em> an inline function still compiled into a function call. I created an example class to test things out and this is what I found:</p> <p><strong>Consider the following class:</strong> </p> <pre><code>//compile with MSVC class InlineTestClass { public: int InternalInt; int GetInt() {return InternalInt;} inline int GetInt_Inl() {return InternalInt;} //__forceinline -Forces the compiler to implement the function as inline __forceinline int GetInt_ForceInl() {return InternalInt;} }; </code></pre> <p><strong>This class has 3 functions for reference.</strong> </p> <ul> <li>The <strong>GetInt</strong> function is a standard function. </li> <li>The <strong>GetInt_Inl</strong> function is an inline function.</li> <li>The <strong>GetInt_ForceInl</strong> function is an ensured inline function in case of the compiler deciding not to implement <strong>GetInt_Inl</strong> as inline function</li> </ul> <p>Implemented like so:</p> <pre><code>InlineTestClass itc; itc.InternalInt = 3; int myInt; myInt = itc.InternalInt; //No function myInt = itc.GetInt(); //Normal function myInt = itc.GetInt_Inl(); //Inline function myInt = itc.GetInt_ForceInl(); //Forced inline function </code></pre> <p>The resulting assembler code of the setting of myInt (taken from dissassembler):</p> <pre><code> 451 myInt = itc.InternalInt; 0x7ff6fe0d4cae &lt;+0x003e&gt; mov eax,dword ptr [rsp+20h] 0x7ff6fe0d4cb2 &lt;+0x0042&gt; mov dword ptr [rsp+38h],eax 452 myInt = itc.GetInt(); 0x7ff6fe0d4cb6 &lt;+0x0046&gt; lea rcx,[rsp+20h] 0x7ff6fe0d4cbb &lt;+0x004b&gt; call nD_Render!ILT+2125(?GetIntInlineTestClassQEAAHXZ) (00007ff6`fe0d1852) 0x7ff6fe0d4cc0 &lt;+0x0050&gt; mov dword ptr [rsp+38h],eax 453 myInt = itc.GetInt_Inl(); 0x7ff6fe0d4cc4 &lt;+0x0054&gt; lea rcx,[rsp+20h] 0x7ff6fe0d4cc9 &lt;+0x0059&gt; call nD_Render!ILT+1885(?GetInt_InlInlineTestClassQEAAHXZ) (00007ff6`fe0d1762) 0x7ff6fe0d4cce &lt;+0x005e&gt; mov dword ptr [rsp+38h],eax 454 myInt = itc.GetInt_ForceInl(); 0x7ff6fe0d4cd2 &lt;+0x0062&gt; lea rcx,[rsp+20h] 0x7ff6fe0d4cd7 &lt;+0x0067&gt; call nD_Render!ILT+715(?GetInt_ForceInlInlineTestClassQEAAHXZ) (00007ff6`fe0d12d0) 0x7ff6fe0d4cdc &lt;+0x006c&gt; mov dword ptr [rsp+38h],eax </code></pre> <p>As shown above the setting (of myInt) from the <strong>member</strong> of InlineTestClass directly is <em>(as expected)</em> 2 mov instructions long. Setting from the <strong>GetInt</strong> function results in a function call <em>(as expected)</em>, however both of the <strong>GetInt_Inl</strong> and <strong>GetInt_ForceInl</strong> (inline functions) also result in a function call. </p> <p>It appears as if the inline function has been compiled as a normal function ignoring the inlining completely <em>(correct me if I am wrong)</em>.</p> <p>This is strange cause according to <a href="https://msdn.microsoft.com/en-us/library/bw1hbe6y.aspx" rel="nofollow noreferrer">MSVC documentation</a>:</p> <blockquote> <p>The inline and __inline specifiers instruct the compiler to insert a copy of the function body into each place the function is called.</p> </blockquote> <p>Which <em>(I think)</em> would result in:</p> <pre><code>inline int GetInt_Inl() {return InternalInt; //Is the function body} myInt = itc.GetInt_Inl(); //Call site //Should result in myInt = itc.InternalInt; //Identical to setting from the member directly </code></pre> <p>Which means that the assembler code should be also identical to the one of setting from the class member directly but it isn't.</p> <h2>Questions:</h2> <ol> <li>Am I missing something or implementing the functions incorrectly?</li> <li>Am I interpreting the function of the inline keyword? What is it?</li> <li>Why do these inline functions result in a function call?</li> </ol>
3
1,727
vue-tables-2 — $emit from custom filter not making it to callback?
<p>I'm struggling to get a custom filter in vue-tables-2 to emit an event from a nested, single-page component in Vue. The problem may be that I'm not capturing / handling it correctly upstream.</p> <p>I have a custom filter <code>&lt;filter-brand /&gt;</code> inside a custom template for <code>dataTable</code> which emits <code>Event.$emit(&quot;vue-tables.filter::filterByBrand&quot;, this.brand)</code>.</p> <p>I want to capture this 'filterByBrand' event in a top-level, router component called <code>&lt;Grid /&gt;</code> which is where I have my <code>&lt;v-client-table /&gt;</code> plus the attendant options including my <code>customFilters</code>.</p> <p>Any thoughts on where I've gotten off course?</p> <p><strong>Grid.vue</strong></p> <pre><code>... customFilters: [ { name: &quot;filterByBrand&quot;, callback: function(row, query) { console.log(&quot;filter=&quot;, query); // nothing? return row.name[0] === query; }, }, ], ... </code></pre> <p><strong>main.js</strong></p> <pre><code>import Vue from &quot;vue&quot;; import App from &quot;./App.vue&quot;; import router from &quot;./router&quot;; import store from &quot;./store&quot;; import { ClientTable, Event } from &quot;vue-tables-2&quot;; import &quot;./scss/index.scss&quot;; Vue.use(ClientTable, {}, false, &quot;bootstrap4&quot;, { filtersRow: FiltersRow, genericFilter: FilterKeyword, sortControl: SortControl, tableHeading: TableHeading, dataTable: DataTable, // in which resides my custom filter &lt;filter-brand /&gt; }); Vue.use(Event); Vue.config.productionTip = false; new Vue({ router, store, render: h =&gt; h(App), }).$mount(&quot;#app&quot;); </code></pre> <p><strong>FilterBrand.vue</strong></p> <pre><code>&lt;template&gt; &lt;div class=&quot;form-group position-relative&quot;&gt; &lt;label for=&quot;brandFilter&quot;&gt; Brand: &lt;/label&gt; &lt;select name=&quot;brandFilter&quot; id=&quot;brandFilter&quot; class=&quot;form-control select&quot; @change=&quot;handleChange($event)&quot; v-model=&quot;brand&quot; &gt; &lt;option disabled selected value=&quot;&quot;&gt;Choose&lt;/option&gt; &lt;option value=&quot;All&quot;&gt;All&lt;/option&gt; &lt;option value=&quot;Brand 1&quot;&gt;Brand 1&lt;/option&gt; &lt;option value=&quot;Brand 2&quot;&gt;Brand 2&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import { Event } from &quot;vue-tables-2&quot;; // if I don't import here, Event below is &quot;window&quot; event. export default { name: &quot;FilterBrand&quot;, props: [&quot;props&quot;], data() { return { brand: &quot;&quot;, }; }, methods: { handleChange(event) { this.brand = event.target.value; Event.$emit(&quot;vue-tables.filter::filterByBrand&quot;, this.brand); // where is this going?? :) }, }, }; &lt;/script&gt; </code></pre>
3
1,244
PFQueryTablViewController queryForTable method with network reachability
<p>I am trying to populate a PFQueryTableViewController with Question objects from my Parse backend. How do I implement blocks within this method? </p> <pre><code>- (PFQuery *)queryForTable // I'm having issues with using the method "findObjectInBackgroundWithBlock" in this method. { PFQuery *query = [PFQuery queryWithClassName:self.parseClassName]; [query fromLocalDatastore]; [query orderByDescending:@"createdAt"]; [query findObjectsInBackgroundWithBlock:^(NSArray *parseQuestions, NSError *error) { // Fetch from local datastore if (parseQuestions != nil) { NSMutableArray *mutableParseQuestions = [parseQuestions mutableCopy]; self.questions = mutableParseQuestions; // if Set local array to fetched Parse questions } else { if ([InternetReachabilityManager isReachable]) { [query findObjectsInBackgroundWithBlock:^(NSArray *parseQuestions, NSError *error) { // Fetch from Cloud NSMutableArray *mutableParseQuestions = [parseQuestions mutableCopy]; self.questions = mutableParseQuestions; // if Set local array to fetched Parse questions [Question pinAllInBackground:parseQuestions]; // Save query results to local datastore }]; } } }]; return query; } </code></pre> <p>When blocks are in this method I get this error. <a href="https://i.stack.imgur.com/9SJnC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9SJnC.png" alt="enter image description here"></a></p> <p>Is this because queryForTable is already a background process? Should I just use </p> <blockquote> <p>[query findObjects]</p> </blockquote> <p>Also, I'm trying to implement reachability into my fetch. </p> <ol> <li>Try fetching from local datastore </li> <li>Load data into table if they are there else switch to the network </li> <li>Call block if network is available</li> <li>Save the results of the network fetch into the local datastore</li> </ol> <p>I know that this method is supposed to automatically assign objects it fetches to rows but I don't know how to work with it if we're passing around a PFObject subclass object. This is my explanation for the arrays.</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { self.question = [self.questions objectAtIndex:indexPath.row]; // Save one question from row static NSString *identifier = @"QuestionsCell"; QuestionsCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if (cell == nil) { cell = [[QuestionsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; } [cell setQuestion:self.question]; // return cell; } </code></pre> <p>This is how I use the fetched array to populate the tableView.</p> <p>So my questions:</p> <ol> <li>Why can't I call a block inside of queryForTable?</li> <li>Is there any way I can make this simpler by using queryForTable's automatic assigning of objects to rows?</li> <li>If the internet is unreachable and the local datastore is empty what should I do?</li> </ol>
3
1,117
jquery slider with cookie
<p>I'm trying to add a cookie to a jquery slider which works fine, until i refresh the page and go backwards in the slider (when the value in the cookie is added (valuevalue) rather than added (value+value).</p> <p>The error occurs on slideMargin += width (which works if the cookie's not involved) , if i change this to slideMargin -= width it works fine but goes the wrong way.</p> <p>The code :</p> <pre><code> jQuery(document).ready(function($) { $(function () { var $slider = $('#slider'); var $slideContainer = $('.slides', $slider); var $slides = $('.slide', $slider); var slideMargin = readCookie('slide'); var width = 770; var slidesLength = ($slides.length-2)*770; document.onload = checkCookie(); $('#next-gal') .on('click', nextGal); $('#prev-gal') .on('click', prevGal); function nextGal() { slideMargin -= width; createCookie('slide', slideMargin,1); $slideContainer.animate({'margin-left':(slideMargin)},1000,function() { if (slideMargin === (-Math.abs(($slides.length-1)*770))) { slideMargin = -Math.abs(width); $slideContainer.css('margin-left', -width); } }); } function prevGal() { slideMargin += width; createCookie('slide', slideMargin,1); $slideContainer.animate({'margin-left':(slideMargin)},1000,function() { if (slideMargin === 0) { slideMargin = -Math.abs(slidesLength); $slideContainer.css('margin-left', -Math.abs(slidesLength)); } }); } function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i &lt; ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } function checkCookie() { if (slideMargin != null) { $slideContainer.css('margin-left', -Math.abs(slideMargin)); createCookie('slide', slideMargin,1); } else { createCookie( 'slide', -1540 ,1); slideMargin = -770; $slideContainer.css('margin-left', -Math.abs(slideMargin)); } } }); }); </code></pre> <p>Any help would be happily recieved.</p> <p>Russ</p>
3
1,098
HtmlUnit infinite loop when redirect link after the form submit is same as the one containing form
<p>I am trying to login to a web page <a href="https://online.firstdata.de/esp/concardis/" rel="nofollow noreferrer">https://online.firstdata.de/esp/concardis/</a> using HTMLunit library in Java. The thing is that this page contains a form inside a couple of iframes. The source of the iframe containing the form is <a href="https://online.firstdata.de/login/postlogin/UserDispatcher" rel="nofollow noreferrer">https://online.firstdata.de/login/postlogin/UserDispatcher</a> . When a form is submitted then one of the redirect links before the next page is rendered is also the same link as mentioned above. So, this creates an infinite loop when I use it from Java. However, when the login happens from the browser because the main source of the originating page was the link ending with /concardis the redirect link is not the same as this link and hence there is no infinite loop. How can I simulate this same behaviour from Java? Here is my code :</p> <pre><code>WebClient webClient = new WebClient(BrowserVersion.CHROME); webClient.getOptions().setJavaScriptEnabled(true); webClient.getOptions().setRedirectEnabled(true); webClient.getOptions().setThrowExceptionOnScriptError(false); webClient.getOptions().setCssEnabled(false); webClient.setAjaxController(new NicelyResynchronizingAjaxController()); try{ HtmlPage page1 = null; HtmlPage page2 = null; HtmlPage page3 = null; HtmlPage page = webClient.getPage("https://online.firstdata.de/esp/concardis"); List&lt;FrameWindow&gt; frames = page.getFrames(); for (FrameWindow frame : frames) { if (frame.getFrameElement().getNameAttribute().equals("application")) { page1 = webClient.getPage(frame.getEnclosedPage().getUrl()); } } List&lt;FrameWindow&gt; frames1 = page1.getFrames(); for (FrameWindow frame : frames1) { if (frame.getFrameElement().getNameAttribute().equals("content")) { page2 = webClient.getPage(frame.getEnclosedPage().getUrl()); } } List&lt;FrameWindow&gt; frames2 = page2.getFrames(); for (FrameWindow frame : frames2) { if (frame.getFrameElement().getId().equals("loginFrame")) { page3 = webClient.getPage(frame.getFrameElement().getSrcAttribute()); } } HtmlForm form = page3.getFormByName("loginForm"); HtmlTextInput userName = form.getInputByName("j_username"); HtmlPasswordInput password = form.getInputByName("j_password"); userName.setValueAttribute("username"); password.setValueAttribute("password"); HtmlSubmitInput submit = form.getInputByName("Submit"); submit.click(); </code></pre>
3
1,025
If clauses in for loop acts weird
<p>I have a function, which collects inputted answer and checked if collected answer is the same as it is the solution. Questions are asked randomly. Questions and solutions are in separate .txt file.</p> <p>I have a file with some words and the program always fulfil its condition if the last word from the list is correctly answered, even though if other answers from other questions are correct. </p> <p>Any suggestions?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var besedeNemske = ["glava", "voda", "drevo"]; var besedePrevod = ["der Kopf", "das Wasser", "der Baum"]; window.onload = function() { var fileInput = document.getElementById('fileInput'); var fileDisplayArea = document.getElementById('fileDisplayArea'); fileInput.addEventListener('change', function(e) { var file = fileInput.files[0]; var textType = /text.*/; if (file.type.match(textType)) { var reader = new FileReader(); reader.onload = function(e) { var lines = this.result.split('\n'); for (var line = 0; line &lt; lines.length; line++) { if (line % 2 != 0) { besedeNemske.push(lines[line]); } else { besedePrevod.push(lines[line]); } } } reader.readAsText(file); } else { fileDisplayArea.innerText = "File not supported!" } }); } var random = 0; function nastaviRandom() { random = Math.floor(Math.random() * 5); } function noviGlagol() { nastaviRandom(); document.getElementById("vprasanje").innerHTML = besedePrevod[random]; } function preveriOdgovor() { var odgovorjeno = document.getElementById("mojOdgovor").value; if (besedeNemske.indexOf(odgovorjeno) == random) { document.getElementById("odgovor").innerHTML = "Pravilni odgovor"; } else { document.getElementById("odgovor").innerHTML = "Napačen odgovor. Pravilni odgovor je " + (besedeNemske[random]) + ""; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page-wrapper"&gt; &lt;h1&gt;Nemščina glagoli&lt;/h1&gt; &lt;div&gt; Select a text file: &lt;input type="file" id="fileInput"&gt; &lt;/div&gt; &lt;pre id="fileDisplayArea"&gt;&lt;pre&gt; &lt;button onclick="noviGlagol()"&gt;Novi glagol&lt;/button&gt; &lt;div id="vprasanje"&gt;&lt;/div&gt; &lt;div id="odgovor"&gt;&lt;/div&gt; &lt;input type="text" id="mojOdgovor"&gt; &lt;button onclick="preveriOdgovor()"&gt;Pošlji&lt;/button&gt; &lt;/div&gt; &lt;script&gt; &lt;/script&gt; &lt;/body&gt; &lt;html&gt;</code></pre> </div> </div> </p>
3
1,202
hashchange event possible bug
<p>I think I've found a really unusual bug in Javascript but I'm not sure.</p> <p>So I have three child divs absolutely positioned inside a parent div (that is position relative).</p> <p>The three child divs are 1200px wide and are <strong>side by side</strong> inside the parent.</p> <p>So the first div is left:0px the second is left:1200px and the third is left:2400px.</p> <p>Now my goal is to click and the divs shift. (The parent div is acting as a 1200px viewport)</p> <pre><code>$(&quot;#blogNav&quot;).click(function() { $(&quot;#blog&quot;).css( &quot;left&quot;, &quot;0px&quot;); $(&quot;#software&quot;).css( &quot;left&quot;, &quot;1200px&quot;); $(&quot;#about&quot;).css( &quot;left&quot;, &quot;2400px&quot;); }); $(&quot;#softwareNav&quot;).click(function() { $(&quot;#blog&quot;).css( &quot;left&quot;, &quot;-1200px&quot;); $(&quot;#software&quot;).css( &quot;left&quot;, &quot;0px&quot;); $(&quot;#about&quot;).css( &quot;left&quot;, &quot;1200px&quot;); }); $(&quot;#aboutNav&quot;).click(function() { $(&quot;#blog&quot;).css( &quot;left&quot;, &quot;-2400px&quot;); $(&quot;#software&quot;).css( &quot;left&quot;, &quot;-1200px&quot;); $(&quot;#about&quot;).css( &quot;left&quot;, &quot;0px&quot;); }); </code></pre> <p>THIS WORKS PERFECTLY.</p> <p>Now here's the issue.</p> <p>When I do the exact same thing with a hashchange event:</p> <pre><code>window.onhashchange = function() { if(window.location.hash==&quot;#blog&quot;) { $(&quot;#blog&quot;).css( &quot;left&quot;, &quot;0px&quot;); $(&quot;#software&quot;).css( &quot;left&quot;, &quot;1200px&quot;); $(&quot;#about&quot;).css( &quot;left&quot;, &quot;2400px&quot;); } if(window.location.hash==&quot;#software&quot;) { $(&quot;#blog&quot;).css( &quot;left&quot;, &quot;-1200px&quot;); $(&quot;#software&quot;).css( &quot;left&quot;, &quot;0px&quot;); $(&quot;#about&quot;).css( &quot;left&quot;, &quot;1200px&quot;); } if(window.location.hash==&quot;#about&quot;) { $(&quot;#blog&quot;).css( &quot;left&quot;, &quot;-2400px&quot;); $(&quot;#software&quot;).css( &quot;left&quot;, &quot;-1200px&quot;); $(&quot;#about&quot;).css( &quot;left&quot;, &quot;0px&quot;); } }; </code></pre> <p>THE POSITIONING IS ALL MESSED UP.</p> <p>The 0px location of the parent div is shifted so that the 0px is no longer the left border of the parent div. Its at some negative margin.</p> <p>The only thing that has change is the hashevent.</p> <p>I hope I'm explaining this well enough.</p> <p>I'll try to upload some examples to my site soon.</p> <p>It's really strange how the exact same logic works with a click event but not with a hashchange event.</p>
3
1,320
How to construct links to static images?
<p>I realized that when I send mails(letters) on localhost site via local postfix server, they were sent successfully, but each time I need to include the letter link to my logo stored in: </p> <blockquote> <p>public/castle.jpg</p> </blockquote> <p>app/mailers/<strong>review_mailer</strong>.rb:</p> <pre><code>class ReviewMailer &lt; ApplicationMailer default from: 'no-reply@kalinin.ru' def welcome_email(review) @review = review mail(to: 'bla@bla.ru', subject: 'New review create') end end </code></pre> <p>views/review_mailer/<strong>welcome_email</strong>.html.erb:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; ........................... &lt;p&gt;logo: &lt;%= image_tag 'public/castle.jpg' %&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>application.rb:</p> <pre><code>config.action_mailer.default_url_options = { host: 'localhost' } </code></pre> <p>development.rb:</p> <pre><code> config.action_mailer.raise_delivery_errors = false config.action_mailer.delivery_method = :sendmail config.action_mailer.default_url_options = { :host =&gt; 'localhost:3000' } </code></pre> <p>reviews_controller:</p> <pre><code> def create @review = current_user.reviews.build(review_params) if @review.save ReviewMailer.welcome_email(@review).deliver_now redirect_to root_path end </code></pre> <p>after creating a new review, here is the <strong>console output</strong>:</p> <pre><code>ReviewMailer#welcome_email: processed outbound mail in 205.9ms Sent mail to bla@bla.ru (73.5ms) Date: Tue, 22 Sep 2015 12:47:11 +0300 From: no-reply@kalinin.ru To: prozaik81-2@yandex.ru Message-ID: &lt;5601239fdd0d3_18b43f823a7394382836b@kalinin.mail&gt; Subject: New review create Mime-Version: 1.0 Content-Type: multipart/alternative; boundary="--==_mimepart_5601239fdbc22_18b43f823a73943828272"; charset=UTF-8 Content-Transfer-Encoding: 7bit ----==_mimepart_5601239fdbc22_18b43f823a73943828272 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit &lt;html&gt; &lt;body&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; .................... &lt;p&gt;logo: &lt;img src="/images/public/castle.jpg" alt="Castle" /&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; &lt;/body&gt; &lt;/html&gt; ----==_mimepart_5601239fdbc22_18b43f823a73943828272-- Redirected to http://localhost:3000/ Completed 302 Found in 601ms (ActiveRecord: 301.4ms) </code></pre> <p>Mail(letter) is not being sent, what can possibly be wrong?</p>
3
1,039
Audio playback using ffmpeg and audiotrack android
<p>I am trying to play mp3 audio in android using ffmpeg and audiotrack. But i'm getting only garbled audio output. Can anyone suggest where could be the problem ?. Here entire player runs in JNI code. All other ffmpeg and audio track initializations are also done before starting this thread.</p> <pre><code>void *decode_audio_thread(void *arg){ AVPacket packet; AVFrame *decoded_frame; int index,i=0,ret; bool isEOS = false; struct timeval tp; int startMs; JNIEnv* env = NULL; jlong timeout = 100000; int got_frame,len,data_size,size; uint8_t **src_data = NULL, **dst_data = NULL; int src_rate = 48000, dst_rate = 44100; int src_nb_channels = 0, dst_nb_channels = 0; int src_linesize, dst_linesize; int src_nb_samples = 1024, dst_nb_samples, max_dst_nb_samples; enum AVSampleFormat src_sample_fmt, dst_sample_fmt; int64_t src_ch_layout, dst_ch_layout; int dst_bufsize; (*myVm)-&gt;AttachCurrentThread(myVm, &amp;env, NULL); LOGV("Allocating avframe"); decoded_frame = av_frame_alloc(); if(decoded_frame) LOGV("Allocation done"); av_init_packet(&amp;packet); while(stop){ ret = av_read_frame(mDataSource, &amp;packet); if (ret &lt; 0) { LOGV("av_read_frame : returned %d ERROR_END_OF_STREAM=%d\n",ret); isEOS = true; break; } LOGV("av_read_frame (%d) size=%d index=%d mAudioIndex=%d\n",i++,packet.size,packet.stream_index,mAudioIndex); if(packet.stream_index == mAudioIndex) { //LOGV("Decoding Frame size=%d",packet.size); len = avcodec_decode_audio4(mAudioTrack,decoded_frame, &amp;got_frame,&amp;packet); if(len &lt; 0) { LOGV("Error frame skiping"); continue; } LOGV("avcodec_decode_audio4 ret=%d got_fram=%d packet.size=%d format decoded %d= configured %d",len,got_frame,packet.size,decoded_frame-&gt;format,AV_SAMPLE_FMT_S16); if(got_frame){ data_size = av_samples_get_buffer_size(NULL,mAudioTrack-&gt;channels , decoded_frame-&gt;nb_samples,mAudioTrack-&gt;sample_fmt, 1); LOGV("av_samples_get_buffer_size data_size=%d decode_len=%d avpacket.len=%d ",data_size,len,packet.size); jbyteArray samples_byte_array; if(decoded_frame-&gt;format != AV_SAMPLE_FMT_S16) { src_nb_samples = decoded_frame-&gt;nb_samples; src_linesize = (int) decoded_frame-&gt;linesize; src_data = decoded_frame-&gt;data; if (decoded_frame-&gt;channel_layout == 0) { decoded_frame-&gt;channel_layout = av_get_default_channel_layout(decoded_frame-&gt;channels); } /* create resampler context */ swr_ctx = swr_alloc(); if (!swr_ctx) { LOGV("sw_ctx allocation failed"); break; } src_rate = decoded_frame-&gt;sample_rate; dst_rate = decoded_frame-&gt;sample_rate; src_ch_layout = decoded_frame-&gt;channel_layout; dst_ch_layout = decoded_frame-&gt;channel_layout; av_opt_set_int(swr_ctx, "in_channel_layout", src_ch_layout, 0); av_opt_set_int(swr_ctx, "out_channel_layout", dst_ch_layout, 0); av_opt_set_int(swr_ctx, "in_sample_rate", src_rate, 0); av_opt_set_int(swr_ctx, "out_sample_rate", dst_rate, 0); src_sample_fmt = decoded_frame-&gt;format; dst_sample_fmt = AV_SAMPLE_FMT_S16; av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", decoded_frame-&gt;format, 0); av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0); LOGV("Swr_init : src_rate=%d dst_rate=%d src_ch_layout=%d dst_ch_layout=%d src_sample_fmt=%d %d dst_sample_fmt=%d %d", src_rate,dst_rate,src_ch_layout,dst_ch_layout,src_sample_fmt,decoded_frame-&gt;format,dst_sample_fmt,AV_SAMPLE_FMT_S16); /* initialize the resampling context */ if ((ret = swr_init(swr_ctx)) &lt; 0) { LOGV("Failed to initialize the resampling context\n"); break; } /* allocate source and destination samples buffers */ src_nb_channels = av_get_channel_layout_nb_channels(src_ch_layout); ret = av_samples_alloc_array_and_samples(&amp;src_data, &amp;src_linesize, src_nb_channels, src_nb_samples, src_sample_fmt, 0); if (ret &lt; 0) { LOGV("Could not allocate source samples\n"); break; } /* compute the number of converted samples: buffering is avoided * ensuring that the output buffer will contain at least all the * converted input samples */ max_dst_nb_samples = dst_nb_samples = av_rescale_rnd(src_nb_samples, dst_rate, src_rate, AV_ROUND_UP); /* buffer is going to be directly written to a rawaudio file, no alignment */ dst_nb_channels = av_get_channel_layout_nb_channels(dst_ch_layout); ret = av_samples_alloc_array_and_samples(&amp;dst_data, &amp;dst_linesize, dst_nb_channels, dst_nb_samples, dst_sample_fmt, 0); if (ret &lt; 0) { LOGV("Could not allocate destination samples\n"); //goto end; } /* compute destination number of samples */ dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, src_rate) + src_nb_samples, dst_rate, src_rate, AV_ROUND_UP); /* convert to destination format */ ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)decoded_frame-&gt;data, src_nb_samples); if (ret &lt; 0) { LOGV("Error while converting\n"); break; } dst_bufsize = av_samples_get_buffer_size(&amp;dst_linesize, dst_nb_channels, ret, dst_sample_fmt, 1); if (dst_bufsize &lt; 0) { LOGV("Could not get sample buffer size\n"); //goto end; } //jbyteArray samples_byte_array = (*env)-&gt;NewByteArray(env, dst_bufsize); if (samples_byte_array == NULL) { LOGV("Cannot Allocate byte array"); break; } jbyte *jni_samples = (*env)-&gt;GetByteArrayElements(env, samples_byte_array, NULL); LOGV("Coping Data %d ",dst_bufsize); memcpy(jni_samples,dst_data[0], dst_bufsize); LOGV("Releasing jni_samples"); (*env)-&gt;ReleaseByteArrayElements(env, samples_byte_array, jni_samples, 0); swr_free(&amp;swr_ctx); } else { //jbyteArray samples_byte_array = (*env)-&gt;NewByteArray(env, data_size); if (samples_byte_array == NULL) { LOGV("Cannot Allocate byte array"); break; } jbyte *jni_samples = (*env)-&gt;GetByteArrayElements(env, samples_byte_array, NULL); LOGV("Coping Data %d ",data_size); memcpy(jni_samples,decoded_frame-&gt;data[0], len); LOGV("Releasing jni_samples"); (*env)-&gt;ReleaseByteArrayElements(env, samples_byte_array, jni_samples, 0); } //(*env)-&gt;SetByteArrayRegion(env, p_sys-&gt;jb_array[0], 0, data_size, audio_frame-&gt;data[0]); LOGV("Audio: AudioTrack.write size=%d\n",len); int ret = (*env)-&gt;CallIntMethod(env, p_sys-&gt;audio_track, p_sys-&gt;aud_write,samples_byte_array,0, len); if ((*env)-&gt;ExceptionOccurred(env)) { LOGV( "Exception in AudioTrack.write failed ret=%d",ret); (*env)-&gt;ExceptionClear(env); p_sys-&gt;error_state = true; goto error; } LOGV("Audio: ret=%d Done AudioTrack...Aud deleting localref\n",ret); (*env)-&gt;DeleteLocalRef(env, samples_byte_array); } } av_free_packet(&amp;packet); } error: LOGV("Closing"); avformat_close_input(&amp;mDataSource); avcodec_close(mAudioTrack); av_free(mDataSource); av_free(decoded_frame); LOGV("DetachCurrentThread\n"); (*myVm)-&gt;DetachCurrentThread(myVm); return; } </code></pre>
3
3,732
php artisan error after repo clone SQLSTATE[42S02]: Base table or view not found:
<p>I made a Laravel project with Jetstream and uploaded it to Github. After my colleague and I tried to execute <code>composer install</code>, we received the following error:</p> <pre><code>&gt; Illuminate\Foundation\ComposerScripts::postAutoloadDump &gt; @php artisan package:discover --ansi Illuminate\Database\QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.users' doesn't exist (SQL: select * from `users` limit 1) at vendor/laravel/framework/src/Illuminate/Database/Connection.php:742 738▕ // If an exception occurs when attempting to run a query, we'll format the error 739▕ // message to include the bindings with SQL, which will make this exception a 740▕ // lot more helpful to the developer instead of just the database's errors. 741▕ catch (Exception $e) { ➜ 742▕ throw new QueryException( 743▕ $query, $this-&gt;prepareBindings($bindings), $e 744▕ ); 745▕ } 746▕ } 1 [internal]:0 Illuminate\Foundation\Application::Illuminate\Foundation\{closure}(Object(App\Providers\RouteServiceProvider)) +15 vendor frames 17 routes/web.php:20 Illuminate\Database\Eloquent\Model::__callStatic(&quot;first&quot;, []) Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1 </code></pre> <p>We tried again without the scripts in <code>composer.json</code>, went well, but after each and every artisan-command we try, we get the following exception:</p> <pre><code> In Connection.php line 742: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.users' doesn't exist (SQL: select * from `users` limit 1) In Connection.php line 396: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.users' doesn't exist </code></pre> <p>This also happens when we try to execute <code>php artisan migrate</code>, the command which should solve this error.</p> <p>So, what can we try now?</p>
3
1,052
Cleaning a SQL schema before using SQL Developer Database copy tool
<p>I have a database for an application and several environment (development, test and production). I would like to use the option <strong>Database copy</strong> from <strong>SQL Developer</strong> in order to retrieve data from the production and copy them in development. Thus data on both environments will be the same.</p> <p>With a previous version of the program all was working perfectly. Nevertheless with a new version (SQL Developer 18.2) imposed by our company, I obtain several error with different objects like sequences, existing table, primary key, ...) during the copy.</p> <p>Thus I would like to use a script for cleaning the objects of the Database before to use the tool in order to see if the problem will be solved. But I don't know how to do that.</p> <p>I found and updated this script:</p> <pre><code>BEGIN FOR cur_rec IN (SELECT object_name, object_type FROM user_objects WHERE object_type IN ('TABLE', 'VIEW', 'PACKAGE', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'SYNONYM' )) LOOP BEGIN IF cur_rec.object_type = 'TABLE' THEN EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '" CASCADE CONSTRAINTS'; ELSE EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '"'; END IF; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line ( 'FAILED: DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '"' ); END; END LOOP; END; </code></pre> <p>Nevertheless this script Cleanup the Schema by DROPPING all objects. I would like to keep the structure and the objects but just empty the conten.</p> <p>Could you please help me how to do for cleaning the different object without deleting them and importing again?</p> <p>Thank in advance for your help.</p> <p>Sebastien</p>
3
1,340
AsyncTask #2 java.lang.RuntimeException
<pre><code>public static Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } } private class AsyncImageLoader extends AsyncTask&lt;String, Void, Bitmap[]&gt; { Bitmap bitmap[]; protected void onPreExecute() { pDialog.setMessage(getContext().getResources().getString(R.string.please_wait)); showDialog(); } @Override protected Bitmap[] doInBackground(String... params) { hideDialog(); bitmap = new Bitmap[2]; bitmap[0] = getBitmapFromURL(params[0]); bitmap[1] = getBitmapFromURL(params[1]); return bitmap; } @Override protected void onPostExecute(Bitmap[] bm) { imgCover.setImageBitmap(bm[1]); bm[1].recycle(); imgProfile.setImageBitmap(bm[0]); bm[0].recycle(); if (MainActivity.PROFILE_UID.equals(MainActivity.USER_UID)) FragmentDrawer.imgProfileNavDrawer.setImageBitmap(bm[0]); // Sol drawer' da çıkan yuvarlak resmi güncellemek için } } </code></pre> <blockquote> <p>01-10 21:11:14.621 7906-8194/project.com.holobech E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) at java.util.concurrent.FutureTask.setException(FutureTask.java:219) at java.util.concurrent.FutureTask.run(FutureTask.java:239) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:856) Caused by: java.lang.OutOfMemoryError at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:528) at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:600) at project.com.holobech.activity.ProfileFragment.getBitmapFromURL(ProfileFragment.java:508) at project.com.holobech.activity.ProfileFragment$AsyncImageLoader.doInBackground(ProfileFragment.java:529) at project.com.holobech.activity.ProfileFragment$AsyncImageLoader.doInBackground(ProfileFragment.java:516) at android.os.AsyncTask$2.call(AsyncTask.java:287) at java.util.concurrent.FutureTask.run(FutureTask.java:234)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)             at java.lang.Thread.run(Thread.java:856)</p> </blockquote> <p>It works perfect for Android 5.0 and higher versions. But when i try with 4.2.2 version, that error occure. How can i fix this problem ? Thanks in advice</p>
3
1,611
Python - Help me find a better way to extract and join all hashtags into a new dict value for each tweet
<p>I am attempting to parse some Twitter data that is from the Twitter Streaming API and is stored in a nested JSON format. I would like to create a new dict key:value pair called <code>'HASHTAGS'</code> that holds all of the hashtags in an array. I do not want to use a regex to extract the values from the tweet text, instead, I want to do this based on the nested JSON metadata field <code>['entities']['hashtags']['text']</code>.</p> <p>The difficulty comes into the fact that not all tweets have a hashtag, and therefore might not have this field. On top of this, some tweets might have multiple hashtags, and I want to extract all of them, not just the first one. </p> <p>I think I've found a way to do this, but it seems very clunky, and not ideal. Also, this only creates the dict <code>'HASHTAGS'</code> for tweets that have a hashtag. I want <code>'HASHTAGS'</code> to be created for every record, but only be populated for records that have a hashtag, including multiple hashtags. </p> <p><strong>DATA</strong></p> <pre><code>{"created_at":"Fri Nov 21 01:17:34 +0000 2014","id":535602890459455488,"id_str":"535602890459455488","text":"RT @rightinillinois: Obama says get right with the law as he's breaking the oath to America's face. #tcot","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":71807953,"id_str":"71807953","name":"USA Hipster","screen_name":"USAHipster","location":"Made in USA","url":null,"description":"HUGE FoxNews FAN!!! USA watchdog, conservative, christian, tea party supporter, whitewater rafter and snow skiier. Whoosh!","protected":false,"verified":false,"followers_count":9066,"friends_count":7566,"listed_count":256,"favourites_count":178,"statuses_count":70404,"created_at":"Sat Sep 05 14:07:14 +0000 2009","utc_offset":-21600,"time_zone":"Central Time (US &amp; Canada)","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"9AE4E8","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/34629530\/WavingFlag.jpg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/34629530\/WavingFlag.jpg","profile_background_tile":true,"profile_link_color":"0084B4","profile_sidebar_border_color":"BDDCAD","profile_sidebar_fill_color":"D6D2D3","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/1252787025\/flag_06_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/1252787025\/flag_06_normal.jpg","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Fri Nov 21 01:12:36 +0000 2014","id":535601639378653184,"id_str":"535601639378653184","text":"Obama says get right with the law as he's breaking the oath to America's face. #tcot","source":"\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":72580029,"id_str":"72580029","name":"Jerry","screen_name":"rightinillinois","location":"","url":null,"description":null,"protected":false,"verified":false,"followers_count":2696,"friends_count":1815,"listed_count":110,"favourites_count":14,"statuses_count":12527,"created_at":"Tue Sep 08 15:29:16 +0000 2009","utc_offset":-21600,"time_zone":"Central Time (US &amp; Canada)","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"1A1B1F","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme9\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme9\/bg.gif","profile_background_tile":false,"profile_link_color":"2FC2EF","profile_sidebar_border_color":"181A1E","profile_sidebar_fill_color":"252429","profile_text_color":"666666","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/486610981003337728\/vDH2QZ6y_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/486610981003337728\/vDH2QZ6y_normal.jpeg","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":1,"favorite_count":1,"entities":{"hashtags":[{"text":"tcot","indices":[79,84]}],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"tcot","indices":[100,105]}],"trends":[],"urls":[],"user_mentions":[{"screen_name":"rightinillinois","name":"Jerry","id":72580029,"id_str":"72580029","indices":[3,19]}],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416532654763"} {"created_at":"Fri Nov 21 01:19:45 +0000 2014","id":535603439942635520,"id_str":"535603439942635520","text":"RT @fishinsam: #cspanchat dont we have people here that are citizens that need to get right with the law?","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":67169191,"id_str":"67169191","name":"Kitty Smalls","screen_name":"FluffySays","location":"USA","url":"http:\/\/politicsthetruthisoutthere.blogspot.com\/","description":"Progressive ALL THE WAY! Family person. Love country. Despise ignorance! Education promoter. Baffled over people following leaders without examining facts.","protected":false,"verified":false,"followers_count":1257,"friends_count":1367,"listed_count":25,"favourites_count":454,"statuses_count":28433,"created_at":"Thu Aug 20 00:08:53 +0000 2009","utc_offset":-28800,"time_zone":"Pacific Time (US &amp; Canada)","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"FCB6EC","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"088253","profile_sidebar_border_color":"F257E8","profile_sidebar_fill_color":"F587C5","profile_text_color":"634047","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/371440359\/Twitter_Name_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/371440359\/Twitter_Name_normal.jpg","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Fri Nov 21 01:13:32 +0000 2014","id":535601875899273216,"id_str":"535601875899273216","text":"#cspanchat dont we have people here that are citizens that need to get right with the law?","source":"\u003ca href=\"http:\/\/janetter.net\/\" rel=\"nofollow\"\u003eJanetter\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":55830051,"id_str":"55830051","name":"fishinsam","screen_name":"fishinsam","location":"","url":null,"description":null,"protected":false,"verified":false,"followers_count":220,"friends_count":24,"listed_count":16,"favourites_count":6,"statuses_count":59611,"created_at":"Sat Jul 11 13:26:50 +0000 2009","utc_offset":-21600,"time_zone":"Central Time (US &amp; Canada)","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/2223044616\/18_fish_normal.JPG","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/2223044616\/18_fish_normal.JPG","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":1,"favorite_count":1,"entities":{"hashtags":[{"text":"cspanchat","indices":[0,10]}],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"cspanchat","indices":[15,25]}],"trends":[],"urls":[],"user_mentions":[{"screen_name":"fishinsam","name":"fishinsam","id":55830051,"id_str":"55830051","indices":[3,13]}],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416532785770"} {"created_at":"Fri Nov 21 01:26:49 +0000 2014","id":535605218314960896,"id_str":"535605218314960896","text":"mariabotta: I support POTUS plan of action for #ImmigrationReform not deporting families, and allowing get right with the law. Don't Forg...","source":"\u003ca href=\"http:\/\/ifttt.com\" rel=\"nofollow\"\u003eIFTTT\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":2895978157,"id_str":"2895978157","name":"A.T.O.M","screen_name":"atomsoffice","location":"","url":null,"description":null,"protected":false,"verified":false,"followers_count":70,"friends_count":0,"listed_count":15,"favourites_count":0,"statuses_count":24639,"created_at":"Mon Nov 10 20:44:30 +0000 2014","utc_offset":-21600,"time_zone":"Central Time (US &amp; Canada)","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/531910902312751104\/XA8nxcOD_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/531910902312751104\/XA8nxcOD_normal.jpeg","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"ImmigrationReform","indices":[47,65]}],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416533209767"} {"created_at":"Fri Nov 21 01:48:24 +0000 2014","id":535610646772342784,"id_str":"535610646772342784","text":"RT @JeffVaughn: Excerpt from @BarackObama #Immigration address: \"If you meet the criteria, you can come out of the shadows and get right wi\u2026","source":"\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":2540471527,"id_str":"2540471527","name":"Jeffrey Lindahl","screen_name":"JeffreyLindahl","location":"Dearborn Heights, MI","url":null,"description":"Just me #UniteBlue","protected":false,"verified":false,"followers_count":25,"friends_count":169,"listed_count":5,"favourites_count":2655,"statuses_count":2883,"created_at":"Sun Jun 01 23:57:20 +0000 2014","utc_offset":null,"time_zone":null,"geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"022330","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme15\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme15\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"A8C7F7","profile_sidebar_fill_color":"C0DFEC","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/473253422045478912\/1nsQ3RnG_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/473253422045478912\/1nsQ3RnG_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/2540471527\/1406322531","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Fri Nov 21 00:57:38 +0000 2014","id":535597874252632064,"id_str":"535597874252632064","text":"Excerpt from @BarackObama #Immigration address: \"If you meet the criteria, you can come out of the shadows and get right with the law.\"","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":25276610,"id_str":"25276610","name":"Jeff Vaughn","screen_name":"JeffVaughn","location":"Motor City ","url":"http:\/\/facebook.com\/jeffvaughnjournalist","description":"WXYZ-TV 5pm Anchor \/ Reporter. Colorado kid and Kansas (State) boy. Lucky husband, devoted dad, cyclist and three time Emmy award winner.","protected":false,"verified":false,"followers_count":3429,"friends_count":1279,"listed_count":148,"favourites_count":1416,"statuses_count":12911,"created_at":"Thu Mar 19 12:13:20 +0000 2009","utc_offset":-21600,"time_zone":"Central Time (US &amp; Canada)","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"334582","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/239808685\/JeffBkgd2.jpg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/239808685\/JeffBkgd2.jpg","profile_background_tile":false,"profile_link_color":"1B213B","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"5781BD","profile_text_color":"000000","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/2463854806\/9dtz8rpwbpajpax4npds_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/2463854806\/9dtz8rpwbpajpax4npds_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/25276610\/1357443681","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":2,"favorite_count":1,"entities":{"hashtags":[{"text":"Immigration","indices":[26,38]}],"trends":[],"urls":[],"user_mentions":[{"screen_name":"BarackObama","name":"Barack Obama","id":813286,"id_str":"813286","indices":[13,25]}],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"Immigration","indices":[42,54]}],"trends":[],"urls":[],"user_mentions":[{"screen_name":"JeffVaughn","name":"Jeff Vaughn","id":25276610,"id_str":"25276610","indices":[3,14]},{"screen_name":"BarackObama","name":"Barack Obama","id":813286,"id_str":"813286","indices":[29,41]}],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416534504012"} {"created_at":"Sat Nov 22 13:11:02 +0000 2014","id":536144826434342912,"id_str":"536144826434342912","text":"The people of Israel were trying to get right with God by keeping the law instead of by trusting in him. Romans 9:32","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":498244376,"id_str":"498244376","name":"The Bible for Life","screen_name":"TheBibleForLife","location":"Chesapeake, Virginia USA","url":"http:\/\/www.biblegateway.com\/","description":"Scripture, ReTweets and More! Dedicated to spreading God's word to all the earth. #FollowJesus","protected":false,"verified":false,"followers_count":2541,"friends_count":1972,"listed_count":54,"favourites_count":3476,"statuses_count":6011,"created_at":"Mon Feb 20 20:57:31 +0000 2012","utc_offset":-18000,"time_zone":"Eastern Time (US &amp; Canada)","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/444222787947732992\/oXTqO4Fx.jpeg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/444222787947732992\/oXTqO4Fx.jpeg","profile_background_tile":false,"profile_link_color":"1754BD","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/449241503643086848\/tLsUwfd5_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/449241503643086848\/tLsUwfd5_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/498244376\/1367010961","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416661862368"} {"created_at":"Sat Nov 22 13:11:48 +0000 2014","id":536145021654011904,"id_str":"536145021654011904","text":"RT @TheBibleForLife: The people of Israel were trying to get right with God by keeping the law instead of by trusting in him. Romans 9:32","source":"\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":36842985,"id_str":"36842985","name":"December4th\u2764","screen_name":"XOXOsunasia","location":"Norfolk, VA","url":"https:\/\/m.facebook.com\/profile.php?id=1374928106095929","description":"Hi ! i came up with a campaign called How Would You Feel ? (HWYF) Its a Anti-Bullying Campaign.","protected":false,"verified":false,"followers_count":4534,"friends_count":4489,"listed_count":30,"favourites_count":22287,"statuses_count":172349,"created_at":"Fri May 01 01:29:09 +0000 2009","utc_offset":-18000,"time_zone":"Quito","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"EBEBEB","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/806596237\/74fd71bd32d4f90c0c444fefa437dc0f.jpeg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/806596237\/74fd71bd32d4f90c0c444fefa437dc0f.jpeg","profile_background_tile":true,"profile_link_color":"4A913C","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"F3F3F3","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/534818464075354112\/S6vI47M6_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/534818464075354112\/S6vI47M6_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/36842985\/1411541625","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Sat Nov 22 13:11:02 +0000 2014","id":536144826434342912,"id_str":"536144826434342912","text":"The people of Israel were trying to get right with God by keeping the law instead of by trusting in him. Romans 9:32","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":498244376,"id_str":"498244376","name":"The Bible for Life","screen_name":"TheBibleForLife","location":"Chesapeake, Virginia USA","url":"http:\/\/www.biblegateway.com\/","description":"Scripture, ReTweets and More! Dedicated to spreading God's word to all the earth. #FollowJesus","protected":false,"verified":false,"followers_count":2541,"friends_count":1972,"listed_count":54,"favourites_count":3476,"statuses_count":6011,"created_at":"Mon Feb 20 20:57:31 +0000 2012","utc_offset":-18000,"time_zone":"Eastern Time (US &amp; Canada)","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/444222787947732992\/oXTqO4Fx.jpeg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/444222787947732992\/oXTqO4Fx.jpeg","profile_background_tile":false,"profile_link_color":"1754BD","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/449241503643086848\/tLsUwfd5_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/449241503643086848\/tLsUwfd5_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/498244376\/1367010961","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":1,"favorite_count":0,"entities":{"hashtags":[],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"trends":[],"urls":[],"user_mentions":[{"screen_name":"TheBibleForLife","name":"The Bible for Life","id":498244376,"id_str":"498244376","indices":[3,19]}],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416661908912"} {"created_at":"Sat Nov 22 13:37:11 +0000 2014","id":536151406764621824,"id_str":"536151406764621824","text":"Obama 2 Boehner on Fri.defending his exec.action:\"The Rep.leader has stood between \u201cmillions of people&amp;amp;the chance 2 get right with the law.\u201d","source":"\u003ca href=\"http:\/\/twitter.com\/#!\/download\/ipad\" rel=\"nofollow\"\u003eTwitter for iPad\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":329231890,"id_str":"329231890","name":"Margaret Morris","screen_name":"margaretvmorris","location":"Jacksonville, FL","url":null,"description":"Now, just a mom, grandmother and great-grandmother...peacemaker, pol.independent, beginning to love the sound of Liberal Democrat. I've found my voice!","protected":false,"verified":false,"followers_count":1836,"friends_count":1913,"listed_count":53,"favourites_count":8795,"statuses_count":43699,"created_at":"Mon Jul 04 18:52:36 +0000 2011","utc_offset":null,"time_zone":null,"geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/516238772196106240\/HQ_XqjiL_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/516238772196106240\/HQ_XqjiL_normal.jpeg","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"en","timestamp_ms":"1416663431241"} </code></pre> <p><strong>CURRENT PROCESS</strong></p> <pre><code># load data into a list of dicts tweets = [] for line in open('tweets.json'): try: tweets.append(json.loads(line)) except: pass # check if line contains a hashtag, and if so, extact all hashtags into a list hashtags = [] if len(line['entities']['hashtags']) &gt; 0: hashtags.extend(line['entities']['hashtags']) line['HASHTAGS'] = [tag['text'] for tag in hashtags] </code></pre>
3
9,079
Filter a dataframe column based on values in a second column being within a tolerance value of any rows in a second dataframe
<p>I am dealing with experimental measurements of time-correlated gamma-ray emissions with a pair of detectors. I have a long-form dataframe which lists every gamma-ray detected and displays its energy, the timestamp of the event, and the detector channel. Here is the sample structure of this dataframe:</p> <pre><code>df Energy Timestamp Channel 0 639 753437128196030 1 1 798 753437128196010 2 2 314 753437131148580 1 3 593 753437131148510 2 4 2341 753437133607800 1 </code></pre> <p>I must filter these data and according to the following conditions: Return the energies of all events detected in Channel 1 which occur within one user-selectable <code>timing_window</code> of events detected in Channel 2. Furthermore, only the events in Channel 2 that are within the energy range <code>[E_lo, E_hi]</code> should be considered when evaluating the timing window conditions.</p> <p>So far, I have tried the following:</p> <p>Separate the energy data of each detector into individual dataframes:</p> <pre><code>d1_all = df[(df["Channel"] == 1)] d2_all = df[(df["Channel"] == 2)] </code></pre> <p>Reset the indices of <code>d1_all</code>:</p> <pre><code>d1_all = d1_all.reset_index() d1_all = d1_all.drop(['index'], axis=1) d1_all.head() </code></pre> <p>Retain only the events in <code>d2_all</code> which occur in the range <code>[E_lo=300, E_hi=600]</code></p> <pre><code>d2_gate = d2_all[(d2_all["Energy"] &gt;= 300) &amp; (d2_all["Energy"] &lt;=600)] </code></pre> <p>Reset the indices of <code>d2_all</code>:</p> <pre><code>d2_gate = d2_gate.reset_index() d2_gate = d2_gate.drop(['index'], axis=1) d2_gate.head() </code></pre> <p><em>Everything up to this point works fine.</em> <strong>Here is the biggest problem.</strong> The following code evaluates each event in detector 1 to determine if its timestamp is within one <code>timing_window</code> of the timestamp corresponding to ANY event within the energy range E_lo to E_hi in detector 2. The problem is that this dataframe can have on the order of 10's to 100's of thousands of entries for each detector, and the current code takes essentially forever to run. This code uses nested <code>for</code> loops.</p> <pre><code>for i in range(0, d1_all.shape[0]): coincidence = False for j in range(0, d2_gate.shape[0]): if ((d1_all.iloc[i]["Timestamp"]) &gt;= (d2_gate.iloc[j]["Timestamp"] - coin_window)) and ((d1_all.iloc[i] ["Timestamp"]) &lt;= (d2_gate.iloc[j]["Timestamp"] + coin_window)): coincidence = True break else: pass if coincidence == True: pass elif coincidence == False: d1_all = d1_all.drop([i]) </code></pre> <p>Any help identifying a faster implementation of evaluating for coincidences would be greatly appreciated! Thank you!</p>
3
1,073
Using if statements with strings in c++
<p>I am trying to perform binary addition using strings. When using if statement, I am always getting the output "did not go in ifs". Please help me and tell me if I am doing any bad practice or any error. Beginner in c++.</p> <pre><code>while(k &gt;= 0) { if (Bin_input1[k] == 0 &amp;&amp; Bin_input2[k] == 0) { if (carry == 0) { Bin_output[k] = 0; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; carry = 0; k = k-1; } else { Bin_output[k] = 1; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; carry = 0; k = k-1; } } else if (Bin_input1[k] == 0 &amp;&amp; Bin_input2[k] == 1) { if (carry == 0) { Bin_output[k] = 1; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; k = k-1; } else { Bin_output[k] = 1; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; carry = 1; k = k-1; } } else if (Bin_input1[k] == 1 &amp;&amp; Bin_input2[k] == 0) { if (carry == 0) { Bin_output[k] = 1; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; k = k-1; } else { Bin_output[k] = 1; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; carry = 1; k = k-1; } } else if (Bin_input1[k] == 1 &amp;&amp; Bin_input2[k] == 1) { { Bin_output[k] = 1; cout &lt;&lt;Bin_output[k] &lt;&lt; endl; carry = 1; k = k-1; } } else cout&lt;&lt; "did not go in ifs" &lt;&lt; endl ; k = k - 1; } return Bin_output; </code></pre>
3
1,108
In angularjs dynamic button creation is correct but validation is not correct
<p>in my code buttons are created correctly but after typing the first row,click Add fields.the close button is disabled in first row.but i want only disable in current typing row.other close buttons are enable.</p> <p>HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="okay.js"&gt; &lt;/script&gt; &lt;/head&gt; &lt;body ng-app="testApp"&gt; &lt;div ng-controller="MainCtrl"&gt; &lt;form name="frm" class="form-inline" novalidate&gt; &lt;div class="form-group"&gt; &lt;input type="string" name="cat_name" class="form-control" ng-model="cat_name" placeholder="Enter Category Name" ng-pattern="/^[a-zA-Z]*$/" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="cat_desc" class="form-control" ng-model="cat_desc" placeholder="Enter Your Description" ng-pattern="/^[a-zA-Z]*$/" required&gt; &lt;/div&gt; &lt;br&gt; &lt;fieldset data-ng-repeat="choice in choices track by $index "&gt; &lt;br&gt; &lt;div class="form-group"&gt; &lt;input type="text" ng-model="choice.itemName" class="form-control" name="item_name" placeholder="Category Item Name" ng-pattern="/^[a-zA-Z]*$/" required&gt; &lt;div class="form-group"&gt; &lt;input type="text" ng-model="choice.itemDesc" class="form-control" name="item_desc" placeholder="Category Description" ng-pattern="/^[a-zA-Z]*$/" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="number" ng-model="choice.itemView" class="form-control" name="item_count" ng-pattern="/^[0-9]/"placeholder="Category Item View Count" required&gt; &lt;p class="help-block" ng-show="frm.item_count.$error.pattern"&gt;numbers only allowed&lt;/p&gt; &lt;select id="country" ng-model="choice.states" name="state" ng-options="country for (country, states) in countries"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;option value=''&gt;Choose&lt;/option&gt; &lt;/select&gt;City: &lt;select id="state" ng-disabled="!choice.states" name="city" ng-model="one"&gt; &lt;option value=""&gt;Choose&lt;/option&gt; &lt;option ng-repeat="state in choice.states" value="{{state.id}}"&gt;{{state.city}}&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;button ng-click="removeChoice()" class="remove btn btn-danger" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.item_name.$invalid||frm.item_desc.$invalid"&gt;close&lt;/button&gt; &lt;/fieldset&gt; &lt;br&gt; &lt;button class="addfields btn btn-success" ng-click="addNewChoice()" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.item_name.$invalid||frm.item_desc.$invalid"&gt;Add fields&lt;/button&gt; &lt;button class="addfields btn btn-success" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.item_name.$invalid||frm.item_desc.$invalid " &gt;Save&lt;/button&gt; &lt;span class="help-block" style="color:red"ng-show="frm.cat_desc.$error.pattern" style:"color:red"&gt;ERROR:&lt;BR/&gt;text only allowed&lt;/span &gt; &lt;span class="help-block" style="color:red"ng-show="frm.item_desc.$error.pattern"&gt;ERROR:&lt;BR/&gt;text only allowed&lt;/span &gt; &lt;span class="help-block" style="color:red"ng-show="frm.cat_name.$error.pattern"&gt;ERROR:&lt;BR/&gt;text only allowed&lt;/span &gt; &lt;span class="help-block"style="color:red" ng-show="frm.item_name.$error.pattern"&gt;ERROR:&lt;BR/&gt;text only allowed&lt;/span &gt; &lt;/div&gt; &lt;div id="choicesDisplay"&gt; {{ newItemNo }} &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>okay. js (angular File)</p> <pre><code>var app=angular.module('testApp', []); app.controller('MainCtrl', function($scope) { $scope.choices = [{id: 'choice1'}]; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length+1; $scope.choices.push({'id':'choice'+newItemNo}); }; $scope.removeChoice = function() { $scope.choices.splice(this.$index,1); }; $scope.countries = { 'Andhra': [{ 'id': '01', 'city': "Guntur" }, { 'id': '02', 'city': "Hyderabad" }], 'Tamilnadu': [{ 'id': '03', 'city': "CBE" }, { 'id': '04', 'dep': "Trichy" }] }; }); </code></pre>
3
2,207
Can't Add/Accept and Decline/Cancel Friend requests on Django
<p>Able to Send Friend requests successfully but responding to the requests are an issue. When you press Accept to Add, the button is removed but the Friend isn't added or when you press Cancel to Decline, nothing happens. </p> <p>Tried adding a forms</p> <pre><code>class Add_Friend(forms.ModelForm): model = UserProfile def add_friend(request, user_profile): request.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() request.friends.add(user_profile) user_profile.friends.add(self) request.friend_requests.remove(user_profile) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() </code></pre> <pre><code>class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(blank=True, max_length=128) friends = models.ManyToManyField('self', blank=True, related_name='friends') friend_requests = models.ManyToManyField('self', blank=True, related_name='friend_requests') def send_friend_request(self, user_profile): self.friend_requests.add(user_profile) noti = Notification.objects.create(owner=self, type=Notification.FRIEND_REQUEST, sender=user_profile.user.username) self.notification_set.add(noti) return self.friend_requests.count() def add_friend(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() self.friends.add(user_profile) user_profile.friends.add(self) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() def cancel_friend_request(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() noti = Notification.objects.create(owner=user_profile, type=Notification.DECLINED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friend_requests.count() def __str__(self): return self.get_first_name() #Takes you to the userprofile page def get_absolute_url(self): return "/users/{}".format(self.id) </code></pre> <pre><code>@method_decorator(login_required, name='dispatch') class SendFriendRequestView(View): def get(self, request, *args, **kwargs): profile_id = request.GET.get('profile_id') requester_id = request.GET.get('requester_id') target = UserProfile.objects.get(id=profile_id) requester = UserProfile.objects.get(id=requester_id) target.send_friend_request(requester) message = 'Friend request to {} sent!'.format(target.visible_name) messages.info(request, message) return redirect('profile', username=target.user.username) @method_decorator(login_required, name='dispatch') class CancelFriendRequestView(View): def cancel_friend_request(request, id): if request.user.is_authenticated(): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.filter( from_user=request.user, to_user=user).first() frequest.delete() return HttpResponseRedirect('/users') @method_decorator(login_required, name='dispatch') class AddFriendView(View): def get(self, request, *args, **kwargs): try: profile_id = request.GET.get('profile_id') requester_id = request.GET.get('requester_id') target = UserProfile.objects.get(id=profile_id) requester = UserProfile.objects.get(id=requester_id) target.add_friend(requester) message = 'Added friend {}!'.format(target.visible_name) messages.info(request, message) return redirect('friends', username=target.user.username) except Exception as e: print('Error: {}'.format(e)) </code></pre> <pre><code>url(r'^friend-request/send/(?P&lt;id&gt;[\w\-]+)/$', send_friend_request), url(r'^friend-request/cancel/(?P&lt;id&gt;[\w\-]+)/$', cancel_friend_request), url(r'^friend-request/accept/(?P&lt;id&gt;[\w\-]+)/$', accept_friend_request), </code></pre> <pre><code>{% if user.userprofile in userprofile.friends.all %} &lt;form&gt; &lt;button id="remove_friend" data-requesterid="{{user.userprofile.id}}" data-profileid="{{userprofile.id}}"&gt; Remove friend &lt;/button&gt; &lt;/form&gt; {% elif user.userprofile in userprofile.friend_requests.all %} Friend request pending... &lt;form&gt; &lt;button id="cancel_friend_request " data-requesterid="{{user.userprofile.id}}" data-profileid="{{userprofile.id}}"&gt; Cancel &lt;/button&gt; &lt;/form&gt; {% else %} &lt;form&gt; &lt;button id="send_friend_request" data-requesterid="{{user.userprofile.id}}" data-profileid="{{userprofile.id}}"&gt; Send friend request &lt;/button&gt; &lt;/form&gt; {% endif %} </code></pre> <p>I'd like the User to be able to Accept/Decline Friend Requests.</p>
3
2,151
The tmx map is only rendering two blocks into the screen and all the rest is black
<p><a href="https://i.stack.imgur.com/EI5rX.png" rel="nofollow noreferrer">The print from my game</a></p> <p>I'm learning to develope a game like supermario through a tutorial on youtube (<a href="https://www.youtube.com/watch?v=P8jgD-V5jG8&amp;t=43s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=P8jgD-V5jG8&amp;t=43s</a>), the code that the author of the tutorial makes available in his github is <strong>still working today</strong>, however it is the complete code of the game, and I am still in video class 6, because it was here that his result got different from mine (as you can see from the image).</p> <p>I would be very grateful if any of you more experienced developers could tell me where I'm wrong to be only showing up 2 blocks of tmx map. I apologize for my english, thanks for trying to help.</p> <p>The main class of the game:</p> <p><code>public class MarioBros extends Game {</code> </p> <pre><code>public SpriteBatch batch; public static final int V_WIDTH = 400; public static final int V_HEIGHT = 208; @Override public void create () { batch = new SpriteBatch(); setScreen(new PlayScreen(this)); } @Override public void render () { super.render(); //Delega o metodo render para as SCREENS que estão ativas. } @Override public void dispose () { batch.dispose(); } </code></pre> <p>}</p> <p>The PlayScreen (I think the problem is here!):</p> <pre><code>public class PlayScreen implements Screen { private MarioBros game; private OrthographicCamera gamecam; private Viewport gamePort; private HUD hud; private TmxMapLoader maploader; private TiledMap map; private OrthogonalTiledMapRenderer renderer; public PlayScreen(MarioBros game) { this.game = game; gamecam = new OrthographicCamera(); gamecam.position.set(gamePort.getWorldWidth() / 2, gamePort.getWorldHeight() / 2, 0); gamePort = new FitViewport(MarioBros.V_WIDTH, MarioBros.V_HEIGHT, gamecam); gamePort.apply(); hud = new HUD(game.batch); // Loading the map we made in Tile maploader = new TmxMapLoader(); map = maploader.load("level1.tmx"); renderer = new OrthogonalTiledMapRenderer(map); } @Override public void show() { } public void handleInput(float dt) { if (Gdx.input.isTouched()) gamecam.position.x += 100 * dt; } public void update(float dt) { handleInput(dt); gamecam.update(); } @Override public void render(float delta) { update(delta); Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); renderer.render(); game.batch.setProjectionMatrix(hud.stage.getCamera().combined); hud.stage.draw(); } @Override public void resize(int width, int height) { gamePort.update(width, height); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { renderer.dispose(); } </code></pre> <p>}</p> <p>The Hud:</p> <pre><code>public class HUD implements Disposable{ public Stage stage; private Viewport viewport; // Novo viewport private Integer worldTimer; private float timeCount; private Integer score; Label countdownLabel; // Label é equivalente ao widget, nessa biblioteca gdx Label scoreLabel; Label timeLabel; Label levelLabel; Label worldLabel; Label marioLabel; public HUD(SpriteBatch sb){ worldTimer = 300; timeCount = 0; score = 0; viewport = new FitViewport(MarioBros.V_WIDTH, MarioBros.V_HEIGHT, new OrthographicCamera()); stage = new Stage(viewport, sb); // Stage é um bloco que você insere coisas (inicialmente soltas dentro dele) Table table = new Table(); // Prender os itens em uma tabela table.top(); // Coloca no topo do nosso stage table.setFillParent(true); // largura do nosso stage countdownLabel = new Label(String.format("%03d", worldTimer), new Label.LabelStyle(new BitmapFont(), Color.WHITE)); scoreLabel = new Label(String.format("%06d", score), new Label.LabelStyle(new BitmapFont(), Color.WHITE)); timeLabel = new Label("TIME", new Label.LabelStyle(new BitmapFont(), Color.WHITE)); levelLabel =new Label("1-1", new Label.LabelStyle(new BitmapFont(), Color.WHITE)); worldLabel =new Label("WORLD", new Label.LabelStyle(new BitmapFont(), Color.WHITE)); marioLabel =new Label("MARIO", new Label.LabelStyle(new BitmapFont(), Color.WHITE)); //expandX vai expandir X ao maximo, por isso devemos por em todos para eles dividirem igualmente o eixo X. table.add(marioLabel).expandX().padTop(10); table.add(worldLabel).expandX().padTop(10); table.add(timeLabel).expandX().padTop(10); table.row(); table.add(scoreLabel).expandX(); table.add(levelLabel).expandX(); table.add(countdownLabel).expandX(); //inserir a table no estagio stage.addActor(table); } @Override public void dispose() { stage.dispose(); } </code></pre> <p>}</p> <p>Thank you for taking your time to try to help me, I already lost a whole week trying to solve this =/ (sad)</p>
3
1,797
expected primary-expression before ' arrayName '
<p>I dont undersatnd why this expected primary-exception errors are there!!! ... :</p> <pre><code>Running /home/ubuntu/workspace/sample.cpp /home/ubuntu/workspace/sample.cpp: In function ‘int main()’: /home/ubuntu/workspace/sample.cpp:50:22: error: expected primary-expression before ‘arrayHelpfull’ std::string arrayHelpfull[3], ^ /home/ubuntu/workspace/sample.cpp:51:10: error: expected primary-expression before ‘double’ double arrayHelpfullPoints[3], ^ /home/ubuntu/workspace/sample.cpp:52:22: error: expected primary-expression before ‘arrayNone’ std::string arrayNone[3], ^ /home/ubuntu/workspace/sample.cpp:53:10: error: expected primary-expression before ‘double’ double arrayNonePoints[3], ^ /home/ubuntu/workspace/sample.cpp:54:23: error: expected primary-expression before ‘arrayHarmfull’ std::string arrayHarmfull[3], ^ /home/ubuntu/workspace/sample.cpp:55:11: error: expected primary-expression before ‘double’ double arrayHarmfullPoints[3], ^ /home/ubuntu/workspace/sample.cpp:61:20: error: expected primary-expression before ‘arrayHelpfull’ std::string arrayHelpfull[3], ^ /home/ubuntu/workspace/sample.cpp:62:8: error: expected primary-expression before ‘double’ double arrayHelpfullPoints[3], ^ /home/ubuntu/workspace/sample.cpp:63:20: error: expected primary-expression before ‘arrayNone’ std::string arrayNone[3], ^ /home/ubuntu/workspace/sample.cpp:64:8: error: expected primary-expression before ‘double’ double arrayNonePoints[3], ^ /home/ubuntu/workspace/sample.cpp:65:21: error: expected primary-expression before ‘arrayHarmfull’ std::string arrayHarmfull[3], ^ /home/ubuntu/workspace/sample.cpp:66:9: error: expected primary-expression before ‘double’ double arrayHarmfullPoints[3], ^ /home/ubuntu/workspace/sample.cpp:74:20: error: expected primary-expression before ‘arrayHelpfull’ std::string arrayHelpfull[3], ^ /home/ubuntu/workspace/sample.cpp:75:8: error: expected primary-expression before ‘double’ double arrayHelpfullPoints[3], ^ /home/ubuntu/workspace/sample.cpp:76:20: error: expected primary-expression before ‘arrayNone’ std::string arrayNone[3], ^ /home/ubuntu/workspace/sample.cpp:77:8: error: expected primary-expression before ‘double’ double arrayNonePoints[3], ^ /home/ubuntu/workspace/sample.cpp:78:21: error: expected primary-expression before ‘arrayHarmfull’ std::string arrayHarmfull[3], ^ /home/ubuntu/workspace/sample.cpp:79:9: error: expected primary-expression before ‘double’ double arrayHarmfullPoints[3], ^ </code></pre> <p>Code:</p> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; #include&lt;fstream&gt; void printingItems( std::string arrayHelpfull[3], double arrayHelpfullPoints[3], std::string arrayNone[3], double arrayNonePoints[3], std::string arrayHarmfull[3], double arrayHarmfullPoints[3], std::string option ) { std::cout &lt;&lt; option &lt;&lt; std::endl; } int main(){ std::string arrayHelpfull[3] = {"fruits", "soda" , "candy"}; double arrayHelpfullPoints[3] = {20.4,50.2,30.0}; std::string arrayNone[3] = {"chair", "shoe" , "pencil"}; double arrayNonePoints[3] = {0,0,0}; std::string arrayHarmfull[3] = {"meth", "dirtyneedle","ninga"}; double arrayHarmfullPoints[3] = {-20,-50,-30}; int userChoice = 0; while (userChoice != 4) { std::cout &lt;&lt; "1 - Just Plain Items" &lt;&lt; std::endl &lt;&lt; "2 - Helpfull Items" &lt;&lt; std::endl &lt;&lt; "3 - Harmfull Items" &lt;&lt; std::endl &lt;&lt; "4 - Quit" &lt;&lt; std::endl; std::cin &gt;&gt; userChoice; switch (userChoice) { case 1: printingItems( std::string arrayHelpfull[3], double arrayHelpfullPoints[3], std::string arrayNone[3], double arrayNonePoints[3], std::string arrayHarmfull[3], double arrayHarmfullPoints[3], "Plain" ); break; case 2: printingItems( std::string arrayHelpfull[3], double arrayHelpfullPoints[3], std::string arrayNone[3], double arrayNonePoints[3], std::string arrayHarmfull[3], double arrayHarmfullPoints[3], "Helpfull" ); break; case 3: printingItems( std::string arrayHelpfull[3], double arrayHelpfullPoints[3], std::string arrayNone[3], double arrayNonePoints[3], std::string arrayHarmfull[3], double arrayHarmfullPoints[3], "Harmfull" ); break; } } } </code></pre>
3
2,316
INVALID_CLIENT: Invalid redirect URI error when running GitHub pages application. Uses Spotify API
<p>I've deployed a React application to GitHub pages that uses the Spotify API to get the currently playing track on Spotify and display it in the web page. This runs great locally and used a local server running on port 8888 to send the api requests and redirect to the app running on localhost:3000. The issue is that the app as is gives the above error when I attempt to request the token from the Spotify API and I'm guessing it's because the redirect uri that I'm using is no longer valid since the app is now on GitHub and can't communicate with localhost:3000.</p> <p>The following is the code that ran on localhost:8888 and retrieved the access token. I changed my redirect URI to match the location of the hosted version of the app.</p> <pre><code>var express = require('express'); // Express web server framework var request = require('request'); // "Request" library var querystring = require('querystring'); var cookieParser = require('cookie-parser'); var client_id = '[MY_CLIENT_ID]'; // Your client id var client_secret = '[MY_CLIENT_SECRET]'; // Your secret var redirect_uri = 'http://malcolmross19.github.io/project/'; // Your redirect uri /** * Generates a random string containing numbers and letters * @param {number} length The length of the string * @return {string} The generated string */ var generateRandomString = function(length) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i &lt; length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; var stateKey = 'spotify_auth_state'; var app = express(); app.use(express.static(__dirname + '/public')) .use(cookieParser()); app.get('/login', function(req, res) { var state = generateRandomString(16); res.cookie(stateKey, state); // your application requests authorization var scope = 'user-read-private user-read-email user-read-playback-state'; res.redirect('https://accounts.spotify.com/authorize?' + querystring.stringify({ response_type: 'code', client_id: client_id, scope: scope, redirect_uri: redirect_uri, state: state })); }); app.get('/callback', function(req, res) { // your application requests refresh and access tokens // after checking the state parameter var code = req.query.code || null; var state = req.query.state || null; var storedState = req.cookies ? req.cookies[stateKey] : null; if (state === null || state !== storedState) { res.redirect('/#' + querystring.stringify({ error: 'state_mismatch' })); } else { res.clearCookie(stateKey); var authOptions = { url: 'https://accounts.spotify.com/api/token', form: { code: code, redirect_uri: redirect_uri, grant_type: 'authorization_code' }, headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, json: true }; request.post(authOptions, function(error, response, body) { if (!error &amp;&amp; response.statusCode === 200) { var access_token = body.access_token, refresh_token = body.refresh_token; var options = { url: 'https://api.spotify.com/v1/me', headers: { 'Authorization': 'Bearer ' + access_token }, json: true }; // use the access token to access the Spotify Web API request.get(options, function(error, response, body) { console.log(body); }); // we can also pass the token to the browser to make requests from there res.redirect('http://malcolmross19.github.io/project/#' + querystring.stringify({ access_token: access_token, refresh_token: refresh_token })); } else { res.redirect('/#' + querystring.stringify({ error: 'invalid_token' })); } }); } }); app.get('/refresh_token', function(req, res) { // requesting access token from refresh token var refresh_token = req.query.refresh_token; var authOptions = { url: 'https://accounts.spotify.com/api/token', headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, form: { grant_type: 'refresh_token', refresh_token: refresh_token }, json: true }; request.post(authOptions, function(error, response, body) { if (!error &amp;&amp; response.statusCode === 200) { var access_token = body.access_token; res.send({ 'access_token': access_token }); } }); }); console.log('Listening on 8888'); app.listen(8888); </code></pre> <p>The following is the code for the app itself. I'm sure I need to change the href attribute in the link to go somewhere other than localhost:8888 but I'm not sure exactly where.</p> <pre><code>import React, { Component } from 'react'; import './App.css'; import SpotifyWebApi from 'spotify-web-api-js'; import ReactCountdownClock from 'react-countdown-clock'; const spotifyApi = new SpotifyWebApi(); class App extends Component { constructor(){ super(); const params = this.getHashParams(); const token = params.access_token; if (token) { spotifyApi.setAccessToken(token); } this.state = { loggedIn: token ? true : false, nowPlaying: { name: 'Not Checked', albumArt: ''}, currentCount: 5, clockHidden: true, songInfoHidden: true, answer: '' } this.getNowPlaying = this.getNowPlaying.bind(this); this.getHashParams = this.getHashParams.bind(this); this.toggleClock = this.toggleClock.bind(this); this.toggleInfo = this.toggleInfo.bind(this); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } getNowPlaying(){ spotifyApi.getMyCurrentPlaybackState() .then((response) =&gt; { console.log(response) this.setState({ nowPlaying: { name: response.item.name, albumArt: response.item.album.images[0].url } }); }) } getHashParams(){ var hashParams = {}; var e, r = /([^&amp;;=]+)=?([^&amp;;]*)/g, q = window.location.hash.substring(1); e = r.exec(q) while (e) { hashParams[e[1]] = decodeURIComponent(e[2]); e = r.exec(q); } return hashParams; } toggleClock(){ this.setState({ clockHidden: !this.state.clockHidden }); } toggleInfo(){ this.toggleClock(); this.setState({ songInfoHidden: !this.state.songInfoHidden, }); } buttonClick(e){ this.getNowPlaying(); if(this.state.songInfoHidden){ this.toggleClock(); } else { this.toggleInfo(); this.setState({ answer: '' }); } } handleChange(event){ this.setState({ answer: event.target.value }); } handleSubmit(event){ event.preventDefault(); this.toggleInfo(); } render() { return ( &lt;div className="App"&gt; &lt;div className="MainHeader"&gt; {!this.state.loggedIn &amp;&amp; &lt;div&gt; &lt;h1&gt;Login to Spotify to use Name That Tune&lt;/h1&gt; &lt;/div&gt;} {this.state.loggedIn &amp;&amp; &lt;div&gt; &lt;h1&gt;Name That Tune&lt;/h1&gt; &lt;/div&gt;} &lt;a href="http://localhost:8888"&gt;Request Access From Spotify&lt;/a&gt; &lt;/div&gt; &lt;div className="Body"&gt; &lt;hr /&gt; {this.state.loggedIn &amp;&amp; !this.state.clockHidden &amp;&amp; &lt;ReactCountdownClock seconds={30} color='#5CC8FF' alpha={0.9} size={720} onComplete={() =&gt; this.toggleInfo()} /&gt;} {this.state.loggedIn &amp;&amp; !this.state.songInfoHidden &amp;&amp; &lt;div&gt; &lt;h1 className="Header"&gt;How Did You Do?&lt;/h1&gt; &lt;div className="NowPlaying"&gt;Now Playing: { this.state.nowPlaying.name }&lt;/div&gt; &lt;/div&gt;} &lt;br /&gt; {this.state.loggedIn &amp;&amp; !this.state.songInfoHidden &amp;&amp; &lt;div&gt; &lt;img src={this.state.nowPlaying.albumArt} style={{ height: 650 }}/&gt; &lt;/div&gt;} {this.state.loggedIn &amp;&amp; !this.state.clockHidden &amp;&amp; &lt;form onSubmit={this.handleSubmit}&gt; &lt;label&gt; &lt;input type="text" value={this.state.answer} placeholder="Enter Your Answer Here" onChange={this.handleChange} /&gt; &lt;/label&gt; &lt;input type="submit" value="Check Answer" /&gt; &lt;/form&gt;} &lt;br /&gt; {this.state.loggedIn &amp;&amp; !this.state.songInfoHidden &amp;&amp; &lt;div&gt; &lt;h1&gt;Your Answer:&lt;br /&gt;&lt;/h1&gt; &lt;div className="Answer"&gt;{this.state.answer}&lt;/div&gt; &lt;/div&gt;} &lt;br /&gt; {this.state.loggedIn &amp;&amp; &lt;button className="NowPlayingButton" onClick={() =&gt; this.buttonClick()}&gt; Check Now Playing &lt;/button&gt; } &lt;/div&gt; &lt;/div&gt; ); } } export default App; </code></pre>
3
4,158
Web browser navigation crash in wp8
<p>I am developing windows phone app .In this app i need to integrate with foursquare,So I loaded the url of foursqare in web browser.Web browser loaded the four square login page upto this it is working fine when i enter the login details and press enter,Then i will hide web browser and show the data in a list which came from service.After 10-15 seconds app gets crashes.This crash will not seen in emulator it happens only in phone(lumia 520).In lumia 920 it works fine</p> <p>my xaml code</p> <pre><code> &lt;Grid Grid.ColumnSpan="2" Name="browserGrid" Visibility="Visible"&gt; &lt;phone:WebBrowser x:Name="foursquareBrowser" IsScriptEnabled="True" VerticalAlignment="Top" Height="720" /&gt; &lt;!--&lt;ProgressBar x:Name="progressBar" IsIndeterminate="True" Visibility="Collapsed"/&gt;--&gt; &lt;/Grid&gt; </code></pre> <p>browser.cs</p> <pre><code> void foursquareBrowser_Loaded(object sender, RoutedEventArgs e) { try { foursquareBrowser.Navigate(new Uri("https://foursquare.com/oauth2/authorize?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&amp;response_type=code&amp;redirect_uri=http://www.visitabudhabi.ae")); foursquareBrowser.Navigating+=foursquareBrowser_Navigating; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void foursquareBrowser_Navigating(object sender, NavigatingEventArgs e) { try { if (e.Uri.OriginalString.Contains("https://foursquare.com/login")) { foursquareBrowser.Navigate(new Uri("https://foursquare.com/oauth2/authorize?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&amp;response_type=code&amp;redirect_uri=http://www.visitabudhabi.ae")); } else if (e.Uri.OriginalString.Contains("code=")) { uri = e.Uri.OriginalString.ToString().Split(new string[] { "code=" }, StringSplitOptions.None).Last(); uri = uri.Remove(uri.Length - 4); WebClient wc = new WebClient(); string postData = string.Empty; wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; wc.UploadStringAsync(new Uri("https://foursquare.com/oauth2/access_token?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&amp;client_secret=1ROOV3FGYQZMVXV0TB1BRMHRIKB3RHI224M2NV0YFC0XXC1U&amp;grant_type=authorization_code&amp;redirect_uri=http://www.visitabudhabi.ae&amp;code=" + uri, UriKind.Absolute), "POST", postData.ToString()); wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc1_UploadStringCompleted); foursquareBrowser.Navigating-=foursquareBrowser_Navigating; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } </code></pre> <p>It is crashing simply without any debugging information.</p>
3
1,412
Handling processes in C
<p>I have a problem when trying to handle a SIGUSR1 signal sent from a father process to all of his child's process. The handler on the child's does nothing. I checked for the result of the kill command and it returns 0 meaning that the message sent was ok . Can anyone help with this? Below is the code of the child process. I use execl to differ the childs code from the father. Note that the handler works well for alarm calls</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;signal.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; /*Global declerations*/ int alarmflag=0; double result=0; int fd[2]; /*Handler for the alarm and SIGUSR1 signal*/ void signal_handler (int sig) { printf("******************"); if(sig==SIGALRM) { printf("Im child with pid:%d im going to die my value is %lf \n",getpid(),result); alarmflag=1; } if(sig==SIGUSR1) { printf("gotit!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); } } double p_calculation () { int i=2; result=3; double prosimo=-1; while(!alarmflag) { prosimo=prosimo*(-1); result=result+(prosimo*(4/((double)i*((double)i+1)*((double)i+2)))); i=i+2; } } main(int argc,char *argv[]) { int fd[2]; /*handling signals*/ signal(SIGALRM,signal_handler); signal(SIGUSR1,signal_handler); /*Notify for execution time*/ printf("PID : %d with PPID : %d executing for %d seconds \n",getpid(),getppid(),atoi(argv[1])); /*end this after the value passed as argument*/ alarm(atoi(argv[1])); p_calculation(); /*Notify for finish*/ printf("Done!!!\n"); } </code></pre> <p>The code for the father follows : </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;signal.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; pid_t *childs; //array for storing childs pids int number_of_childs;//variable for the number of childs int count_controls=0; /*Handler for the SIGINT signal*/ void control_handler(int sig) { int j; for (j=0;j&lt;number_of_childs;j++) { kill(childs[j],SIGUSR1); } } main (int argc,char *argv[]){ int i,child_status; int fd[2]; char cast[512]; int pid; number_of_childs=atoi(argv[1]); signal(SIGINT,control_handler); childs=malloc(number_of_childs*sizeof (pid_t)); if(pipe(fd)==-1) { perror("pipe");exit(1); } for (i=0;i&lt;number_of_childs;i++){ pid=fork(); /*Create pipes to communicate with all children*/ /*Fathers code goes here*/ if(pid!=0) { printf("Parent process: PID= %d,PPID=%d, CPID=%d \n",getpid(),getppid(),pid); childs[i]=pid; // Keep all your childs in an array printf("Child:%d\n",childs[i]); } /*If you are a child*/ else { /*Change the code for the childs and set the time of execution*/ sprintf(cast,"%d",i+1); execl("./Child.out","",cast,NULL); } } /*Father should never terminate*/ while (1); } </code></pre>
3
1,248
angular-ui-carousel just showing next and previous buttons. No slider or images
<p>I am using angular-ui-carousel as mentioned in <a href="https://www.npmjs.com/package/angular-ui-carousel" rel="nofollow noreferrer">https://www.npmjs.com/package/angular-ui-carousel</a>. However when I code it up it just shows the previous and next buttons. Can anyone please suggest what I have done wrong. I am also open to other ways of creating multi-item carousel. Please help as I am stuck!</p> <p>HTML:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"&gt; &lt;link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.css"&gt; &lt;link rel = "stylesheet" href = "/BookBox/assets/libs/angular-ui-carousel/dist/ui-carousel.css"&gt; &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"&gt;&lt;/script&gt; &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"&gt;&lt;/script&gt; &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.js"&gt;&lt;/script&gt; &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.js"&gt;&lt;/script&gt; &lt;script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.js"&gt;&lt;/script&gt; &lt;script src="/BookBox/assets/libs/angular-ui-carousel/dist/ui-carousel.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="/BookBox/components/anonymousHomePage/anonymousHomePageService.js"&gt;&lt;/script&gt; &lt;script src="/BookBox/components/anonymousHomePage/anonymousHomePageController.js"&gt;&lt;/script&gt; &lt;script src="/BookBox/shared/searchBox/searchBoxService.js"&gt;&lt;/script&gt; &lt;script src="/BookBox/shared/searchBox/searchBoxController.js"&gt;&lt;/script&gt; &lt;style&gt; &lt;/style&gt; &lt;/head&gt; &lt;body ng-app="anonymousHomePageCtrl" ng-controller="anonymousHomeCtrl as ctrl"&gt; &lt;div style="width: 500px; margin: 0 auto;"&gt; &lt;ui-carousel slides="ctrl.popularBooks" slides-to-show="4" slides-to-scroll="1" initial-slide="1" autoplay="false" dots="false"&gt; &lt;carousel-item&gt; &lt;a href="#" &gt; &lt;img alt="category1" ng-src="{{item.localImageUrl}}" height="200" width="100"&gt; &lt;div class='d-flex justify-content-center'&gt; &lt;span&gt;{{item.title}}&lt;/span&gt; &lt;/div&gt; &lt;div class='d-flex justify-content-center'&gt; &lt;span&gt;{{item.author}}&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/carousel-item&gt; &lt;/ui-carousel&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Array in my angular controller:</p> <pre><code>self.popularBooks=[{title:"A Brief Hstory of Time", author:"Stephen Hawking", localImageUrl:"http://localhost:8383/BookBox/assets/img/bookCovers/I1.jpg"}, {title:"Life In Motion", author:"Misty Copeland", localImageUrl:"http://localhost:8383/BookBox/assets/img/bookCovers/I2.jpg"}, {title:"Loosing My Virginity", author:"Richard Branson", localImageUrl:"http://localhost:8383/BookBox/assets/img/bookCovers/I3.jpg"}, {title:"Wings Of Fire", author:"APJ Abdul Kalam", localImageUrl:"http://localhost:8383/BookBox/assets/img/bookCovers/I4.jpg"}, {title:"Thinking Fast and Slow", author:"Daniel Kahnamen", localImageUrl:"http://localhost:8383/BookBox/assets/img/bookCovers/I5.jpg"}]; </code></pre>
3
1,950
AngularJS Modal Service Stops Working
<p>I've created a <code>modal</code> service within my Angular app that I can inject into controllers or directives. I'm running into a problem where after opening/closing a modal multiple times, everything within the modal stops workings. The modal works by grabbing content from a hidden div on the page and popping it into the modal. I've been able to determine that at some point, the value of <code>modal.settings</code> changes. If I insert a <code>debugger</code> at the beginning of my <code>modal.open</code> function and save the value of <code>var x = settings</code> in my console, I can see that after a few cycles, <code>x !== settings</code>. I've also tried comparing <code>modal.settings</code>, but the same thing happens. Eventually, after a few cycles, <code>modal.settings</code> changes and things stop working.</p> <p>I think I need to refactor this service, but I'm not sure where to start and could use some guidance.</p> <p>Here is the service code:</p> <pre><code>app.service('modal', ['$compile', function($compile) { var modal = this; modal.settings; modal.contents; modal.overlay = $('&lt;div id="overlay"&gt;&lt;/div&gt;'); modal.modal = $('&lt;div id="modal"&gt;&lt;/div&gt;'); modal.content = $('&lt;div id="content"&gt;&lt;/div&gt;'); modal.closeBtn = $('&lt;div id="close"&gt;&lt;i class="fa fa-times"&gt;&lt;/div&gt;'); modal.modal.hide(); modal.overlay.hide(); modal.modal.append(modal.content, modal.closeBtn); $(document).ready(function(){ $('body').append(modal.overlay, modal.modal); }); modal.open = function (settings) { if(!modal.settings) { modal.settings = settings; } modal.content.empty().append(modal.settings.content); if(modal.settings.class) modal.modal.addClass(modal.settings.class); if(modal.settings.height) modal.modal.css({ height: modal.settings.height }); if(modal.settings.width) modal.modal.css({ width: modal.settings.width }); if(modal.settings.content_height) modal.modal.css({ height: modal.settings.content_height }); if(modal.settings.content_width) modal.modal.css({ width: modal.settings.content_width }); if(modal.settings.fitToWindow) { modal.settings.width = $(window).width() - 160; modal.settings.height = $(window).height() - 160; }; center(modal.settings.top); $(window).bind('resize.modal', center); modal.modal.show(); modal.overlay.show(); $(modal.closeBtn).add(modal.overlay).on('click', function(e) { e.stopPropagation(); modal.close(); }); $(document).on('keyup', function(e) { if (e.keyCode == 27) { modal.close(); $(document).unbind('keyup'); } }) }; modal.close = function() { debugger; modal.settings.elem.empty().append(modal.settings.content); modal.modal.hide(); modal.overlay.hide(); modal.content.empty(); $(window).unbind('resize.modal'); }; function center(top) { if(!top || !isInt(top)) top = 130; var mLeft = -1 * modal.modal.width() / 2; modal.modal.css({ top: top + 'px', left: '50%', marginLeft: mLeft }); function isInt(n) { return n % 1 === 0; } } }]); </code></pre> <p>Here is how the modal is opened from the controller or directive:</p> <pre><code>modal.open({ content: $('#edit_story_' + story.id), elem: $('#edit_story_' + story.id + '_container') }); </code></pre> <p>I also tried running my <code>elem</code> through the compiler first like so:</p> <pre><code>modal.open({ content: $compile($('#edit_story_' + story.id))($scope), elem: $('#edit_story_' + story.id + '_container') }); </code></pre> <p>That solved my initial problem, but now after a few cycles my modal contents are duplicated. I get one form stacked upon another.</p>
3
1,696
Global variables between C and C++
<p>I'm developing a mixed C/C++ program for an ARM STM32F4, but I have problems in accessing global variables defined in the C part. Here is a simple test code to reproduce the problem.</p> <p>test.h:</p> <pre><code>#ifndef TEST_H_ #define TEST_H_ #ifdef __cplusplus extern "C" { #endif extern const char* strings[]; #ifdef __cplusplus } #endif #endif /* TEST_H_ */ </code></pre> <p>test.c:</p> <pre><code>#include &lt;test.h&gt; const char* strings[] = {"string a", "string b", "string c" }; </code></pre> <p>main.hpp</p> <pre><code>#ifndef MAIN_HPP_ #define MAIN_HPP_ #define STM32F4 #include &lt;test.h&gt; #include &lt;libopencm3/stm32/rcc.h&gt; #include &lt;libopencm3/stm32/gpio.h&gt; #endif /* MAIN_HPP_ */ </code></pre> <p>main.cpp:</p> <pre><code>#include &lt;main.hpp&gt; int main(void) { char s2[3][9]; rcc_periph_clock_enable(RCC_GPIOD); gpio_mode_setup(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO12); while (1) { for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 9; j++) { s2[i][j] = strings[i][j]; if (s2[i][j] == 'i') { gpio_toggle(GPIOD, GPIO12); } for (int k = 0; k &lt; 1000000; k++) { __asm__("nop"); } } } } } </code></pre> <p>However, when I run it in the debugger I can see that the memory where strings[0] (for example) is pointing is completely zeroed.</p> <p>Note: the part in the while loop is not relevant, I've just added it to have some feedback and to avoid that the compiler strips the unused values of strings.</p> <p>So what am I doing wrong here?</p> <p><strong>EDIT</strong></p> <p>I'm working with Eclipse under Linux, gnu-arm-none-eabi.</p> <p>complier and linker command lines and output:</p> <pre><code>arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-move-loop-invariants -Wunused -Wuninitialized -Wall -Wextra -Wmissing-declarations -Wconversion -Wpointer-arith -Wpadded -Wshadow -Wlogical-op -Waggregate-return -Wfloat-equal -g3 -I"/home/andrea/ownCloud/src/arm/libopencm3/include" -I"/home/andrea/ownCloud/src/arm/testt/src" -std=gnu++11 -fabi-version=0 -fno-exceptions -fno-rtti -fno-use-cxa-atexit -fno-threadsafe-statics -Wabi -Wctor-dtor-privacy -Wnoexcept -Wnon-virtual-dtor -Wstrict-null-sentinel -Wsign-promo -MMD -MP -MF"src/main.d" -MT"src/main.o" -c -o "src/main.o" "../src/main.cpp" In file included from /home/andrea/ownCloud/src/arm/libopencm3/include/libopencm3/stm32/rcc.h:32:0, from /home/andrea/ownCloud/src/arm/testt/src/main.hpp:14, from ../src/main.cpp:20: /home/andrea/ownCloud/src/arm/libopencm3/include/libopencm3/stm32/f4/rcc.h:640:11: warning: padding struct to align 'rcc_clock_scale::plln' [-Wpadded] uint16_t plln; ^ /home/andrea/ownCloud/src/arm/libopencm3/include/libopencm3/stm32/f4/rcc.h:644:11: warning: padding struct to align 'rcc_clock_scale::flash_config' [-Wpadded] uint32_t flash_config; ^ Finished building: ../src/main.cpp Building file: ../src/test.c Invoking: Cross ARM C Compiler arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-move-loop-invariants -Wunused -Wuninitialized -Wall -Wextra -Wmissing-declarations -Wconversion -Wpointer-arith -Wpadded -Wshadow -Wlogical-op -Waggregate-return -Wfloat-equal -g3 -I"/home/andrea/ownCloud/src/arm/libopencm3/include" -I"/home/andrea/ownCloud/src/arm/testt/src" -std=gnu11 -Wmissing-prototypes -Wstrict-prototypes -Wbad-function-cast -MMD -MP -MF"src/test.d" -MT"src/test.o" -c -o "src/test.o" "../src/test.c" Finished building: ../src/test.c Building target: testt.elf Invoking: Cross ARM C++ Linker arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-move-loop-invariants -Wunused -Wuninitialized -Wall -Wextra -Wmissing-declarations -Wconversion -Wpointer-arith -Wpadded -Wshadow -Wlogical-op -Waggregate-return -Wfloat-equal -g3 -T "/home/andrea/ownCloud/src/arm/testt/src/stm32f407g-discovery.ld" -T "/home/andrea/ownCloud/src/arm/testt/src/libopencm3_stm32f4.ld" -nostartfiles -Xlinker --gc-sections -L"/home/andrea/ownCloud/src/arm/libopencm3/lib" -Wl,-Map,"testt.map" --specs=nano.specs -o "testt.elf" ./src/main.o ./src/test.o -lopencm3_stm32f4 Finished building target: testt.elf </code></pre> <p>Linker scripts (not the cleanest one, I did some testing with it).</p> <pre><code>MEMORY { rom (rx) : ORIGIN = 0x08000000, LENGTH = 1024K ram (rwx) : ORIGIN = 0x20000000, LENGTH = 128K } _stack_size = 0x400; /* Include the common ld script. */ INCLUDE libopencm3_stm32f4.ld </code></pre> <p>libopencm3_stm32f4.ld:</p> <pre><code>/* Enforce emmition of the vector table. */ EXTERN (vector_table) /* Define the entry point of the output file. */ ENTRY(reset_handler) /* Define sections. */ SECTIONS { .text : { *(.vectors) /* Vector table */ *(.text*) /* Program code */ . = ALIGN(4); *(.rodata*) /* Read-only data */ . = ALIGN(4); } &gt;rom /* C++ Static constructors/destructors, also used for __attribute__ * ((constructor)) and the likes */ .preinit_array : { . = ALIGN(4); __preinit_array_start = .; KEEP (*(.preinit_array)) __preinit_array_end = .; } &gt;rom .init_array : { . = ALIGN(4); __init_array_start = .; KEEP (*(SORT(.init_array.*))) KEEP (*(.init_array)) __init_array_end = .; } &gt;rom .fini_array : { . = ALIGN(4); __fini_array_start = .; KEEP (*(.fini_array)) KEEP (*(SORT(.fini_array.*))) __fini_array_end = .; } &gt;rom /* * Another section used by C++ stuff, appears when using newlib with * 64bit (long long) printf support */ .ARM.extab : { *(.ARM.extab*) } &gt;rom .ARM.exidx : { __exidx_start = .; *(.ARM.exidx*) __exidx_end = .; } &gt;rom . = ALIGN(4); _etext = .; .data : { _data = .; *(.data*) /* Read-write initialized data */ . = ALIGN(4); _edata = .; } &gt;ram AT &gt;rom _data_loadaddr = LOADADDR(.data); .bss : { *(.bss*) /* Read-write zero initialized data */ *(COMMON) . = ALIGN(4); _ebss = .; } &gt;ram . = ALIGN(4); _end_bss = .; end = .; _end = .; _heap_bottom = .; _heap_top = ORIGIN(ram)+LENGTH(ram)-_stack_size; _stack_bottom =_heap_top; _stack_top = ORIGIN(ram) + LENGTH(ram); /* * The .eh_frame section appears to be used for C++ exception handling. * You may need to fix this if you're using C++. */ /DISCARD/ : { *(.eh_frame) } } PROVIDE(_stack = ORIGIN(ram) + LENGTH(ram)); </code></pre> <p><strong>EDIT</strong></p> <p>I'm looking into the problem but I'm a bit puzzled.</p> <p>The startup code includes the following:</p> <pre><code>for (src = &amp;_data_loadaddr, dest = &amp;_data; dest &lt; &amp;_edata; src++, dest++) { *dest = *src; } </code></pre> <p>So it seems ok to me.</p> <p>The .map file gives the following infos:</p> <pre><code>.data 0x0000000020000000 0xc load address 0x000000000800038c 0x0000000020000000 _data = . *(.data*) .data.strings 0x0000000020000000 0xc ./src/test.o 0x0000000020000000 strings 0x000000002000000c . = ALIGN (0x4) 0x000000002000000c _edata = . 0x000000002000000c _data = . *(.data*) 0x000000002000000c . = ALIGN (0x4) 0x000000002000000c _edata = . 0x000000000800038c _data_loadaddr = LOADADDR (.data) .igot.plt 0x000000002000000c 0x0 load address 0x0000000008000398 </code></pre> <p>Now, when I run the debugger I see that right from the start &amp;_data==&amp;_edata==0x2000000c , and I notice also that _data is present two times in the .map file.</p> <p>So, is there an error in the linker script?</p>
3
4,017
Get the average of the values of one column for the values in another
<p>I was not so sure how to ask this question. i am trying to answer what is the average tone when an initiative is mentioned and additionally when a topic, and a goal( or achievement) are mentioned. My dataframe (df) has many mentions of 70 initiatives (rows). meaning my df has 500+ rows of data, but only 70 Initiatives.</p> <p>My data looks like this</p> <pre><code>&gt; tabmean Initiative Topic Goals Achievements Tone 1 52 44 2 2 2 2 294 42 2 2 2 3 103 31 2 2 2 4 52 41 2 2 2 5 87 26 2 1 1 6 52 87 2 2 2 7 136 81 2 2 2 8 19 7 2 2 1 9 19 4 2 2 2 10 0 63 2 2 2 11 0 25 2 2 2 12 19 51 2 2 2 13 52 51 2 2 2 14 108 94 2 2 1 15 52 89 2 2 2 16 110 37 2 2 2 17 247 25 2 2 2 18 66 95 2 2 2 19 24 49 2 2 2 20 24 110 2 2 2 </code></pre> <p>I want to find what is the mean or average Tone when an Initiative is mentioned. as well as what is the Tone when an Initiative, a Topic and a Goal are mentioned at the same time. The code options for Tone are : positive(coded: 1), neutral(2), negative (coded:3), and both positive and negative(4). Goals and Achievements are coded yes(1) and no(2).</p> <p>I have used this code:</p> <pre><code>GoalMeanTone &lt;- tabmean %&gt;% group_by(Initiative,Topic,Goals,Tone) %&gt;% summarize(averagetone = mean(Tone)) </code></pre> <p>With Solution output :</p> <pre><code>GoalMeanTone # A tibble: 454 x 5 # Groups: Initiative, Topic, Goals [424] Initiative Topic Goals Tone averagetone &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; 1 0 104 2 0 NA 2 0 105 2 0 NA 3 0 22 2 0 NA 4 0 25 2 0 NA 5 0 29 2 0 NA 6 0 30 2 1 NA 7 0 31 1 1 NA 8 0 42 1 0 NA 9 0 44 2 0 NA 10 0 44 NA 0 NA # ... with 444 more rows </code></pre> <p>note that for Initiative Value 0 means &quot;other initiative&quot;.</p> <p>and I've also tried this code</p> <pre><code>library(plyr) GoalMeanTone2 &lt;- ddply( tabmean, .(Initiative), function(x) mean(tabmean$Tone) ) </code></pre> <p>with solution output</p> <pre><code>&gt; GoalMeanTone2 Initiative V1 1 0 NA 2 1 NA 3 101 NA 4 102 NA 5 103 NA 6 104 NA 7 105 NA 8 107 NA 9 108 NA 10 110 NA </code></pre> <p>Note that in both instances, I do not get an average for Tone but instead get NA's</p> <p>I have removed the NAs in the df from the column &quot;Tone&quot; also have tried to remove all the other mission values in the df ( its only about 30 values that i deleted). and I have also re-coded the values for Tone :</p> <pre><code>tabmean&lt;-Meantable %&gt;% mutate(Tone=recode(Tone, `1`=&quot;1&quot;, `2`=&quot;0&quot;, `3`=&quot;-1&quot;, `4`=&quot;2&quot;)) </code></pre> <p>I still cannot manage to get the average tone for an initiative. Maybe the solution is more obvious than i think, but have gotten stuck and have no idea how to proceed or solve this.</p> <p>i'd be super grateful for a better code to get this. Thanks!</p>
3
2,212
Virtual keyboard in TASM
<p>I know it's quite a long-shot but I'm stuck in the middle of a school assembly project and as I'm pretty new to programming, I'm having a hard time tracking down the problem(s) in my code.</p> <p>I'm trying to make an virtual (on-screen) keyboard. The values of the location of each button is found in 2 arrays, one for the X value of the center of the button, other for the Y.</p> <p>Example arrays keyboard's top row:</p> <pre><code>x_arr dw 13,37,61,85,109,133,157,181,205,229 y_arr dw 113,113,113,113,113,113,113,113,113,113 </code></pre> <p>The computer waits for a mouse click from the user and using an algorithm finds if or which button was pressed, then matches that button with an array of ascii values of each letter:</p> <pre><code>letter_arr db 81,87,68,82,84,89,85,73,79,80 ;QWERTYUIOP </code></pre> <p>My program doesn't seem to work. I'll add the full code and a picture of the keyboard itself.</p> <p>Sorry if anything was bit messy. Thanks in advance!</p> <p><a href="https://i.stack.imgur.com/Dnlq6.png" rel="nofollow noreferrer">image link</a></p> <pre><code>IDEAL MODEL small STACK 0f500h ;--------------- MAX_BMP_WIDTH = 320 MAX_BMP_HEIGHT = 200 SMALL_BMP_HEIGHT = 40 SMALL_BMP_WIDTH = 40 DATASEG ;------Image related data------ OneBmpLine db MAX_BMP_WIDTH dup (0) ;One Color line read buffer ScreenLineMax db MAX_BMP_WIDTH dup (0) ;One Color line read buffer FileHandle dw ? Header db 54 dup(0) Palette db 400h dup (0) SmallPicName db 'keyboar1.bmp',0 BmpFileErrorMsg db 'Error At Opening Bmp File .', 0dh, 0ah,'$' ErrorFile db 0 BB db "BB..",'$' BmpLeft dw ? BmpTop dw ? BmpColSize dw ? BmpRowSize dw ? ;-----Program related data----- mouse_click dw ? letter_arr db 81,87,68,82,84,89,85,73,79,80 ;array containing ascii values of letters x_arr dw 13,37,61,85,109,133,157,181,205,229 ;array containing x value of center of buttons representing letters in letter_arr y_arr dw 113,113,113,113,113,113,113,113,113,113 ;array containing y value of center of buttons representing letters in letter_arr mouse_last_button dw 0 ;holds the value of last mouse button clicked mouse_button dw 1 ;holds the value of mouse button clicked CODESEG ;================PROCEDURES================ ;----------------- proc OpenShowBmp near push cx push bx call OpenBmpFile cmp [ErrorFile],1 je @@ExitProc call ReadBmpHeader ; from here assume bx is global param with file handle. call ReadBmpPalette call CopyBmpPalette call ShowBMP call CloseBmpFile @@ExitProc: pop bx pop cx ret endp OpenShowBmp ;----------------- proc OpenBmpFile near ;input dx filename to open mov ah, 3Dh xor al, al int 21h jc @@ErrorAtOpen mov [FileHandle], ax jmp @@ExitProc @@ErrorAtOpen: mov [ErrorFile],1 @@ExitProc: ret endp OpenBmpFile proc CloseBmpFile near mov ah,3Eh mov bx, [FileHandle] int 21h ret endp CloseBmpFile ;----------------- proc ReadBmpHeader near ; Read 54 bytes the Header push cx push dx mov ah,3fh mov bx, [FileHandle] mov cx,54 mov dx,offset Header int 21h pop dx pop cx ret endp ReadBmpHeader ;----------------- proc ReadBmpPalette near ; Read BMP file color palette, 256 colors * 4 bytes (400h) ; 4 bytes for each color BGR + null) push cx push dx mov ah,3fh mov cx,400h mov dx,offset Palette int 21h pop dx pop cx ret endp ReadBmpPalette ;----------------- proc CopyBmpPalette near ; Will move out to screen memory the colors ; video ports are 3C8h for number of first color ; and 3C9h for all rest push cx push dx mov si,offset Palette mov cx,256 mov dx,3C8h mov al,0 ; black first out dx,al ;3C8h inc dx ;3C9h CopyNextColor: mov al,[si+2] ; Red shr al,2 ; divide by 4 Max (cos max is 63 and we have here max 255 ) (loosing color resolution). out dx,al mov al,[si+1] ; Green. shr al,2 out dx,al mov al,[si] ; Blue. shr al,2 out dx,al add si,4 ; Point to next color. (4 bytes for each color BGR + null) loop CopyNextColor pop dx pop cx ret endp CopyBmpPalette ;----------------- proc ShowBMP ; BMP graphics are saved upside-down. ; Read the graphic line by line (BmpRowSize lines in VGA format), ; displaying the lines from bottom to top. push cx mov ax, 0A000h mov es, ax mov cx,[BmpRowSize] mov ax,[BmpColSize] ; row size must dived by 4 so if it less we must calculate the extra padding bytes xor dx,dx mov si,4 div si mov bp,dx mov dx,[BmpLeft] @@NextLine: push cx push dx mov di,cx ; Current Row at the small bmp (each time -1) add di,[BmpTop] ; add the Y on entire screen ; next 5 lines di will be = cx*320 + dx , point to the correct screen line mov cx,di shl cx,6 shl di,8 add di,cx add di,dx ; small Read one line mov ah,3fh mov cx,[BmpColSize] add cx,bp ; extra bytes to each row must be divided by 4 mov dx,offset ScreenLineMax int 21h ; Copy one line into video memory cld ; Clear direction flag, for movsb mov cx,[BmpColSize] mov si,offset ScreenLineMax rep movsb ; Copy line to the screen pop dx pop cx loop @@NextLine pop cx ret endp ShowBMP ;----------------- proc setGraphic ;sets graphic mode mov ax, 13h int 10h ret endp setGraphic ;----------------- proc initMouse ;initializes mouse mov ax, 0 int 33h ;resets mouse mov ax, 1 int 33h ;shows pointer ret endp initMouse ;----------------- proc initImage ;imports keyboard bitmap mov [BmpLeft],0 mov [BmpTop],0 mov [BmpColSize], 320 mov [BmpRowSize] ,200 mov dx,offset SmallPicName call OpenShowBmp ret endp initImage ;----------------- proc getMouseClick mov ax, [mouse_button] ;stores te value of the last state of the mouse mov [mouse_last_button], ax mov ax, 03h int 33h ;gets mouse information mov [mouse_button], bx ;saves the click inforamtion shr cx, 1 ;halves the x position value since the interrupt returns double ret endp getMouseClick ;----------------- proc checkMouseButton mov ax, [mouse_button] ;waits for the user to click left mouse button cmp ax, 1 jne mouseLoop cmp ax, [mouse_last_button] ;if button pressed before is the same as the current one, jne mouseLoop ;skip the letter printing jmp doLoop ret endp checkMouseButton ;----------------- proc checkX mov ax,cx ;saves the x value of the click for later pop cx ;pops the current value of counter to cx push ax mov si, offset x_arr add si,cx mov ax, [si] ;moves the value at x array at index number cx (counter) to ax ;add ax, 9 ;checks if the click was inside a button range on x axis (9 pixels left and right of the center) pop cx cmp cx, ax ja mouseLoop mov ax, [si] sub ax, 9 cmp cx, ax jb mouseLoop endp checkX ;----------------- proc checkY mov si, offset y_arr add si,cx mov ax, [si] sub ax, 9 ;checks if the click was inside a button range on y axis (9 pixels above and below the center) cmp dx, ax jb mouseLoop mov ax, [si] add ax, 9 cmp dx, ax ja writeLetter ret endp checkY ;----------------- proc printLetter mov si, offset letter_arr ;prints the letter whose ascii value matches the x and y values found previously add si,cx mov dl, [si] mov ah, 2h int 21h ret endp printLetter ;----------------- ;================PROCEDURES================ start: mov ax,@data mov ds,ax call setGraphic ;sets graphic mode call initMouse ;initializes mouse call initImage ;displays keyboard image mov cx, 10 ;iterates over all of the buttons in the keyboard until one matches a clicks location mouseLoop: push cx call getMouseClick call checkMouseButton call checkX call checkY pop cx dec cx loop mouseLoop writeLetter: call printLetter doLoop: mov cx,10 jmp mouseLoop exit: mov ax, 4c00h int 21h END start </code></pre>
3
3,587
Extract single data value from retrieved firebase json objects
<p>In my android app I want to retrieve only a single value from all the nodes of firebase json objects and check... My firebase database looks like -> <a href="https://i.stack.imgur.com/nYBZI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nYBZI.png" alt="enter image description here"></a></p> <p>Now i am using this code to achieve my task but I am getting null everytime as output..</p> <pre><code>public class optChos extends AppCompatActivity { DatabaseReference ref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_opt_chos); final FirebaseDatabase database = FirebaseDatabase.getInstance(); ref = database.getReference("vendorDtl"); } public void fetchkey(View view) { EditText etx=findViewById(R.id.etkey); String keysrch=etx.getText().toString(); Log.i("optionchoose","fetchkeycalled"); Toast.makeText(getApplicationContext(),"Key finfing",Toast.LENGTH_SHORT).show(); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot vst:dataSnapshot.getChildren()) { vendor vn = vst.getValue(vendor.class); Toast.makeText(getApplicationContext(), "Email is-&gt; " + vn.getNam(), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "key is-&gt; " + vn.getVky(), Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getApplicationContext(),"nothing fetched",Toast.LENGTH_SHORT).show(); } }); } @Override protected void onStart() { super.onStart(); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot vst:dataSnapshot.getChildren()) { vendor vn = vst.getValue(vendor.class); Toast.makeText(getApplicationContext(), "Email is-&gt; " + vn.getNam(), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "key is-&gt; " + vn.getVky(), Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getApplicationContext(),"nothing fetched",Toast.LENGTH_SHORT).show(); } }); } </code></pre> <p>}</p> <p>Here <code>fetchkey(View view)</code> is the onclick function of a button..</p> <blockquote> <p>I want to retrieve that <code>vid</code> from every node and check with a user entered value ..How can i do that?</p> </blockquote>
3
1,088
ssh fails to connect but scp works in gitlab-ci
<p>I am using gitlab secrets to pass the ssh private key for it to connect to a remote server. For scp works fine but running ssh doesn't.</p> <p>I can even see the ssh logs on the server when the gitlab pipeline runs and tries to do ssh.</p> <p>Here is the output from gitlab-pipeline:</p> <pre><code>ssh -i /root/.ssh/id_rsa -vvv root@$DEPLOYMENT_SERVER_IP "docker login -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD} ${CI_REGISTRY};" OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n 7 Dec 2017 debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 19: Applying options for * debug2: resolving "157.245.xxx.xxx" port 22 debug2: ssh_connect_direct: needpriv 0 debug1: Connecting to 157.245.xxx.xxx [157.245.xxx.xxx] port 22. debug1: connect to address 157.245.xxx.xxx port 22: Connection refused ssh: connect to host 157.245.xxx.xxx port 22: Connection refused </code></pre> <p>Here is my gitlab pipeline which fails:</p> <pre><code>deploy_production: stage: deploy image: python:3.6-alpine before_script: - 'which ssh-agent || ( apk update &amp;&amp; apk add openssh-client)' - eval "$(ssh-agent -s)" - mkdir -p ~/.ssh - chmod 700 ~/.ssh - echo "$DEPLOY_SERVER_PRIVATE_KEY" | tr -d '\r' &gt; ~/.ssh/id_rsa - chmod 600 ~/.ssh/id_rsa - ssh-add ~/.ssh/id_rsa - apk add gcc musl-dev libffi-dev openssl-dev iputils - ssh-keyscan $DEPLOYMENT_SERVER_IP &gt;&gt; ~/.ssh/known_hosts - chmod 644 ~/.ssh/known_hosts script: - scp -r ./docker-compose.yml root@${DEPLOYMENT_SERVER_IP}:~/ - scp -r ./env/production/docker-compose.yml root@${DEPLOYMENT_SERVER_IP}:~/docker-compose-prod.yml - ssh -i /root/.ssh/id_rsa -vvv root@$DEPLOYMENT_SERVER_IP "docker login -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD} ${CI_REGISTRY};" environment: production only: - "master" </code></pre> <p>sshd auth logs:</p> <pre><code>sshd[27552]: Connection closed by 35.231.235.202 port 53870 [preauth] sshd[27554]: Connection closed by 35.231.235.202 port 53872 [preauth] sshd[27553]: Connection closed by 35.231.235.202 port 53874 [preauth] sshd[27558]: Accepted publickey for root from 35.231.235.202 port 53876 ssh2: RSA SHA256:bS8IsyG4kyKcTtfrW+h4kw1JXbBSQfO6Jk6X/JKL1CU sshd[27558]: pam_unix(sshd:session): session opened for user root by (uid=0) systemd-logind[945]: New session 649 of user root. sshd[27558]: Received disconnect from 35.231.235.202 port 53876:11: disconnected by user sshd[27558]: Disconnected from user root 35.231.235.202 port 53876 sshd[27558]: pam_unix(sshd:session): session closed for user root systemd-logind[945]: Removed session 649. sshd[27560]: Received disconnect from 222.186.15.160 port 64316:11: [preauth] sshd[27560]: Disconnected from authenticating user root 222.186.15.160 port 64316 [preauth] sshd[27685]: Accepted publickey for root from 35.231.235.202 port 53878 ssh2: RSA SHA256:bS8IsyG4kyKcTtfrW+h4kw1JXbBSQfO6Jk6X/JKL1CU sshd[27685]: pam_unix(sshd:session): session opened for user root by (uid=0) systemd-logind[945]: New session 650 of user root. sshd[27685]: Received disconnect ected by user sshd[27685]: Disconnected from user root 35.231.235.202 port 53878 sshd[27685]: pam_unix(sshd:session): session closed for user root systemd-logind[945]: Removed session 650. </code></pre>
3
2,828
how to solve overlay2 make du report wrong disk size and make shell give no space left on disk error
<p>I use the same docker image to launch many containers, now, the /var/lib/docker/overlay2 take up all my disk space, when I login into the shell, it tells me that no space left on the disk, and features like tab completion is disabled.</p> <p>But, ncdu show that I have a lot of space on disk.</p> <p>So, what should I do to make the system report the right disk usage?</p> <pre><code># df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/vg_root-lv_root 50G 47G 0 100% / devtmpfs 7.8G 0 7.8G 0% /dev tmpfs 7.8G 8.0K 7.8G 1% /dev/shm tmpfs 7.8G 339M 7.4G 5% /run tmpfs 7.8G 0 7.8G 0% /sys/fs/cgroup /dev/sda1 477M 192M 256M 43% /boot /dev/mapper/vg_root-lv_home 860G 637G 180G 79% /home tmpfs 1.6G 0 1.6G 0% /run/user/1000 overlay 50G 47G 0 100% /var/lib/docker/overlay2/de427a5be70251c986f52d0706d52dee990d70d30f8c2272134be930e4df5e39/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/7e4eaae4e80c19fbb1404dede478a8f71923a6522c7de69289e20183adbad595/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/aaccc3c3715af52b5ee80c85f4bdab6731f6b0432818f2d2d380bff042f854ec/merged shm 64M 0 64M 0% /var/lib/docker/containers/c04f9158e166e40ee3fae1c20e11d920f086beccd66bcee15aafcdf43a3c3f14/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/fad78e540d824ae0c773c541b903771544bd4a0e1fa278f6d71cbfeb62b5a9fc/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/e5c2a66f0f0013320592e174341446e03af92bf85aa31b4aa1edfdf7c62947ff/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/9a9d82a83c94fff9a3922609d1a2385b173a06f095b4ae0172711d830b5f6d7c/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/c672e6a835a9203f802a30bb477953bf543fe3d27815c1ca5a9b19a966b60cb6/merged shm 64M 0 64M 0% /var/lib/docker/containers/8d2a85881a24fd3dbe2c6b89ca1ca20589e3a9305d2e4ddb509e0606d3ee1624/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/85c9f2a9f740b06fdc3ac2de0e3fd263a0cb99d2e8b82970196c8a779be64aa5/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/faa892c1b6d212ac4fc1278d726f7bef3d55c0314cd266dcabce273138b0c805/merged shm 64M 0 64M 0% /var/lib/docker/containers/e04764245c6053839785406dbb3803dc7652f0370816691a26cd0ef52416f9ba/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/7b78bde8e9842f78fa3de8784f1a9d7479c6f0859a8569feb6e397155357d1d9/merged shm 64M 4.0K 64M 1% /var/lib/docker/containers/bcea21f2959df00d92651364b9b1d1fd1592edd76ebc96e74517d27e9781d73c/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/a81222a086a3332812b09215200500801a1bf6e6c6750bb2e4ba8b447984b2b2/merged shm 64M 0 64M 0% /var/lib/docker/containers/3c20969a057dd02b683e06e3cec5367b5249ec8179fb360e4cade14ae8428709/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/f585a30576aac3c01e2e013fd575ca0c530b1007708c9a28f18dadd47c2f9fe2/merged shm 64M 0 64M 0% /var/lib/docker/containers/c6c35094b2a60960974f8b1551497d12c654ee18125931cb38fd8d04de3547c5/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/376a8bdffeb163b6f6e56b322eaba36ac5ab55db9118ed2a009380d7d2ee210f/merged shm 64M 0 64M 0% /var/lib/docker/containers/db781659cd0665b8e23bea94930bf72f0a68e6547a2fa23e5776758d3b277bff/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/9d863f4774b646b797f23d059658ec5fbb263f6298c29342936a719d60d80e26/merged shm 64M 0 64M 0% /var/lib/docker/containers/eb518881186826e39b322107257db511c1d57eeefe89872b8d12d0d0c06dbe58/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/fd6ca2f68ee1138d9e89d3f43a58486125560695bad1dda200c023de0562e264/merged shm 64M 0 64M 0% /var/lib/docker/containers/0c3c63e10ba60fd6a5339155f48794744b094810bec218de2127ecd2eb777f37/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/61f63c9f8aa9c8bef92c7e59a8af8f8ef23b256e413b813aefc59a5146042639/merged shm 64M 0 64M 0% /var/lib/docker/containers/49113505a8b0376f66eaf73c7592e4ebd3bd353b3b787f0b1ad800954c1cdb93/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/506ea7261f670f3375f5aec1242954152b53df076d25442edeebada3d45c26fa/merged shm 64M 0 64M 0% /var/lib/docker/containers/8c208146a365fc5e0f37ca62ab43eafc3d39ad83d5255775295aec2e3cd66b59/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/9f79a0563202b2278119735ce49ae72a19d31ce2d61ecc53bdbc77a99fe99e2c/merged shm 64M 0 64M 0% /var/lib/docker/containers/b932912cc08e23d740664b90073cf9d1184ef890a757fdc8264229e8e135bf41/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/e976176926d38bfa5465c845c78555f522738be3398fe74dce6db30c710147e4/merged shm 64M 0 64M 0% /var/lib/docker/containers/6ff287ddd9f8aea1937954864eaf64db5c6334db0f6edb99655d6d5e479e0868/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/762d362bbf279e1f3d1c94378b6244b6587f8a42f49386913d787ef6cf4d7cc9/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/cfedd98eddf04e6a70ffe4e4677e9706ae767dcc35c046a74ff8684eda0ab721/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/1fffc46bfb192758fe68847831eee74e3b3c7a0f1c83ba9872c40987a33c0011/merged shm 64M 0 64M 0% /var/lib/docker/containers/2c975f00d82fefd7a21f9dae494e82579d54d8c1f52ba0d96f1efab2a96682fb/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/70f3735bdba66e10142e421aa5419f55a2b652bafc21d420d2a9cdb6a56d6a9a/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/678032472ea06a749fe2fd67f8490d99228899be7ae38d9dde092f9c89e11893/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/49ba932bb2aac3afb9fc3b03337c8dce1c170f32418716174248e1ae7d67c9c9/merged shm 64M 20K 64M 1% /var/lib/docker/containers/5b9042f0a3dd2e69e29d1aeab2b0e0b2653353382443111e68c89fc7eb2fc85e/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/7dc462026410b4631eb96e0b9e5f0e2b304685226c402370c4747ddce52a08cd/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/a0e8ed4fa8bce5a91620f58326876b3b225b2677139beb78d007e4e745d313aa/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/393e044a1e5beca1231ccc87e519f2c05d4a66f02c29fba0ac0e7215623292b5/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/9d88e58d86ddb8a59e38b6ab23ce3bd0b5830566d8254b350e6ba6cbc8da88fe/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/f762fce5d845b64db036f75fcecbf307cf059a67af34feb4dd9d68046e12f4a3/merged overlay 50G 47G 0 100% /var/lib/docker/overlay2/c8a9bbee38a777ac15df037c1987fcba4737ec0b4ab6402406154086ac0615a9/merged shm 64M 0 64M 0% /var/lib/docker/containers/e0debd9645d878c23e65e31b395d4828d19ea330452e1a9766d659bee03d334b/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/e44b3d2e5e7c7a341a2f7730db993d6c4367122ea89b9b3be7a76572c05d9a8a/mounts/shm shm 64M 20K 64M 1% /var/lib/docker/containers/c447baa10ed917b49ca27136458ca8f831ef92cd5c0077e336450503eabef86a/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/864c4efbb9deb38a12acc1d8b983be6e3e14ebbfbe4072de99f7cd187a1c773e/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/79d4e8be28c78c082d242614423a28320dc0854da00238811ae7087563c2aeab/mounts/shm shm 64M 0 64M 0% /var/lib/docker/containers/75b69e0f773aa1a8b68e8ac3a0c2f20fee76f6fa8b787085db558f9799463c53/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/99fb3d86e69f54f54b86436be025834a03caf04c0fff81581c4a2f1f3bbed5c4/merged shm 64M 0 64M 0% /var/lib/docker/containers/0d15184afd24ef235d95f27bdbb4b7a34523eaf6ae49de8ffdeeb55b2b4a3209/mounts/shm overlay 50G 47G 0 100% /var/lib/docker/overlay2/b57c998741c5d0491cf5805c4a56acf6377aedb1864d519bdd816e51dcaa2de8/merged shm 64M 0 64M 0% /var/lib/docker/containers/912522b1d92b7670627bc7c233be76bfe88c123f7f701acf73fbb42f59d9155a/mounts/shm [root@localhost]# du -hx --max-depth=1 /var/lib/docker/ 16G /var/lib/docker/overlay2 2.4G /var/lib/docker/containers 20K /var/lib/docker/builder 193M /var/lib/docker/swarm 26M /var/lib/docker/image 4.0K /var/lib/docker/trust 4.0K /var/lib/docker/runtimes 20K /var/lib/docker/plugins 22M /var/lib/docker/network 4.0K /var/lib/docker/tmp 72K /var/lib/docker/buildkit 1.3M /var/lib/docker/containerd 216K /var/lib/docker/volumes 19G /var/lib/docker/ [root@localhost]# du -h --max-depth=1 /var/lib/docker/ 38G /var/lib/docker/overlay2 2.4G /var/lib/docker/containers 20K /var/lib/docker/builder 193M /var/lib/docker/swarm 26M /var/lib/docker/image 4.0K /var/lib/docker/trust 4.0K /var/lib/docker/runtimes 20K /var/lib/docker/plugins 22M /var/lib/docker/network 4.0K /var/lib/docker/tmp 72K /var/lib/docker/buildkit 1.3M /var/lib/docker/containerd 216K /var/lib/docker/volumes 40G /var/lib/docker/ </code></pre> <p>when press tab in shell:</p> <pre><code>-bash: cannot create temp file for here-document: No space left on device </code></pre>
3
6,307
ERROR Error: Cannot insert a destroyed View in a ViewContainer
<p>I have designed a page generator by configuration app and it works fine and generate components and render them on the page as good as it should.</p> <p>But when i try to render a new page by new configuration, i get this error <code>ERROR Error: Cannot insert a destroyed View in a ViewContainer!</code> right when the generator service try to render the first component on the page after cleaning the page.</p> <p>The pages configuration arrives from <code>pageConfigService</code> at <code>ngOnInit</code> in <code>NemoContainerComponent</code> and error appears when <code>pageGenerator</code> try to render the <code>WidgetContainerComponent</code>.</p> <p>** UPDATE **</p> <p>Page will be generate after changing the rout, all of the routes base component is the <code>NemoContainerComponent</code> and when route changes, the <code>NemoContainerComponent</code> destroyed and created again.</p> <p>** UPDATE **</p> <p>This is <code>NemoContainerComponent</code>:</p> <pre><code>@Component({ selector: 'nemo-container', templateUrl: './nemo-container.component.html', encapsulation: ViewEncapsulation.None }) export class NemoContainerComponent { private subscription: Subscription = new Subscription(); @ViewChild(ChildReferenceDirective) childReference: ChildReferenceDirective; constructor( private pageGenerator: PageGeneratorService, private route: ActivatedRoute, private routeService: RouteService, private router: Router, private storeEngine: StoreEngineService, private pageConfigService: PageConfigService ) { this.subscription.add(route.params.subscribe((params) =&gt; { this.routeService.setRouteService = params; })); let activeRoute = router.url.split('/').join(' '); document.body.className += ' ' + activeRoute; } ngOnInit() { this.pageGenerator.containerRef = this.childReference.viewReference; this.subscription.add(this.pageConfigService .get(this.route.data['value'].page) .subscribe(data =&gt; { this.pageGenerator.renderNewPageByConfigurationFile(data.json) })); } ngOnDestroy() { this.subscription.unsubscribe(); } } </code></pre> <p><code>WidgetContainerComponent</code> is here:</p> <pre><code>@Widget({ typeName: 'widget-container', displayName: '', type: 'parent', settings: [] }) @Component({ selector: 'widget-container', templateUrl: "widget-container.component.html", encapsulation: ViewEncapsulation.None }) export class WidgetContainerComponent { @ViewChild(ChildReferenceDirective, { read: ViewContainerRef }) childRef; get childReference(): ViewContainerRef { return this.childRef; } private data: ObjectInterface = {}; set widgetData(value: ObjectInterface) { for (let item in value) { this.data[item] = value[item]; } } get widgetData(): ObjectInterface { return this.data; } public id: string = ''; } </code></pre> <p>** UPDATE **</p> <p>angular pack version: 4.4.6</p> <p>** UPDATE **</p> <p>thanks in advance for your helps :)</p>
3
1,139
Laravel query returns unexpected order
<p>I'm using Laravel Query Builder to get a set of rows, ordering them by 2 columns, <code>ticket_id</code> then <code>id</code> (previously <code>created_at</code>). However the result orders them by <code>ticket_id</code> (correct), but the <code>id</code> (or <code>created_at</code>) secondary order is incorrect. Am I approaching this wrong, misunderstanding ordering?</p> <p>Here's my query:</p> <pre><code>$responses = Response::where('status', '=', 'closed'); -&gt;select('id', 'ticket_id', 'created_at', 'author_id') -&gt;orderBy('ticket_id', 'id') -&gt;get(); </code></pre> <p>Which in turn, returns:</p> <pre><code> 0 =&gt; array:3 [ "ticket_id" =&gt; 14 "id" =&gt; 71 "time" =&gt; "2018-05-25 08:55:03" ] 1 =&gt; array:3 [ "ticket_id" =&gt; 14 "id" =&gt; 75 "time" =&gt; "2018-05-25 12:48:45" ] 2 =&gt; array:3 [ "ticket_id" =&gt; 14 "id" =&gt; 72 "time" =&gt; "2018-05-25 08:55:53" ] 3 =&gt; array:3 [ "ticket_id" =&gt; 13 "id" =&gt; 70 "time" =&gt; "2018-05-25 08:53:50" ] 4 =&gt; array:3 [ "ticket_id" =&gt; 13 "id" =&gt; 76 "time" =&gt; "2018-05-29 12:30:46" ] 5 =&gt; array:3 [ "ticket_id" =&gt; 13 "id" =&gt; 74 "time" =&gt; "2018-05-25 11:30:36" ] </code></pre> <p>You see for ticket 14, the order is 71, 75, 72, rather than 71, 72, 75.</p> <p>Here's the table structure too:</p> <pre><code>+------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | ticket_id | int(11) | NO | | NULL | | | author_id | int(11) | NO | | NULL | | | status | int(11) | NO | | 0 | | | content | text | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | | assets | text | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+ </code></pre>
3
1,194
flutter keep data after reset password
<p>i'm work on flutter project . i create a simple function to change password . it's works fine but ( the password change correctly) but i can't keep my actual screen after password changed. i losed all data as you see . My question is How i can keep data in screen after the change of password .</p> <p>password screen :</p> <p><a href="https://i.stack.imgur.com/J3PKA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J3PKA.png" alt="enter image description here" /></a></p> <p>My screen after the password changed :</p> <p><a href="https://i.stack.imgur.com/SWtBT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SWtBT.png" alt="enter image description here" /></a></p> <p>and this is my code :</p> <pre><code> Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return SafeArea( /* minimum: const EdgeInsets.only( top: 20.0, right: 5.0, left: 5.0, bottom: 10.0),*/ child: Center( child: Scaffold( resizeToAvoidBottomInset: true, backgroundColor: Color(0xFFF6F7F8), body: SingleChildScrollView( child: Form( key: _formKey, child: FutureBuilder&lt;User&gt;( future: boxApi.getUser(), builder: (context, snapshot) { // ignore: missing_return print(snapshot.data); switch (snapshot.connectionState) { case ConnectionState.none: return Text('no connection'); case ConnectionState.active: case ConnectionState.waiting: return Center( child: CircularProgressIndicator(), ); break; case ConnectionState.done: if (snapshot.hasError) { return Text('error'); } else if (snapshot.hasData) { // String price = snapshot.data['body'].; // print(&quot;${snapshot.data}&quot;); return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( padding: EdgeInsets.only(top: 16), width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height / 4, decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.white60, blurRadius: 15.0, offset: Offset(0.0, 0.75)) ], gradient: LinearGradient( begin: Alignment(0.5, 0.85), end: Alignment(0.48, -1.08), colors: [ const Color(0xFF0B0C3A), const Color(0xFF010611), ], stops: [ 0.0, 0.5, ], ), //color: blue, borderRadius: BorderRadius.only( bottomRight: Radius.circular(32), bottomLeft: Radius.circular(32))), child: Column( children: [ Row( children: [ SizedBox( width: 30, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( &quot;${snapshot.data.name}&quot;, style: TextStyle( color: Colors.white, fontSize: 25, fontWeight: FontWeight.bold), ), SizedBox( height: 10, ), Text( &quot;${snapshot.data.phone}&quot;, style: TextStyle( color: Colors.white60, fontSize: 18, //fontWeight: FontWeight.w300 ), ), ]) ], ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( margin: EdgeInsets.symmetric( vertical: 10), width: size.width * 0.4, child: ElevatedButton( /*onPressed: () =&gt; [ modifyUserName(), // modifyUserEmail(), // modifyUserAdress() ],*/ onPressed: () { editUserProfile(); // modifyUserEmail(); }, child: Text('Enregistrer'), style: ElevatedButton.styleFrom( primary: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius .circular( 20), side: BorderSide( color: Colors .white)), ), )), SizedBox( width: 20, ), ], ) ], ), ), Container( height: MediaQuery.of(context).size.height / 1.5, // padding: EdgeInsets.only( // top: 32, // ), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( width: size.width * 0.94, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( padding: EdgeInsets.only( left: 10, right: 10, bottom: 20, top: 20), child: Column( mainAxisAlignment: MainAxisAlignment .start, crossAxisAlignment: CrossAxisAlignment .start, children: [ Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ Text( 'Votre nom :', style: TextStyle( color: Color( 0xFF4053FCF), fontSize: 16, fontWeight: FontWeight .w600), ), IconButton( icon: Icon( CommunityMaterialIcons .pencil, color: Colors .grey, ), onPressed: () { myFocusNode .requestFocus(); // setState(() { enableup = true; // }); }) ], ), TextFormField( controller: _nameController, enabled: enableup, focusNode: myFocusNode, enableInteractiveSelection: false, keyboardType: TextInputType .text, decoration: InputDecoration( hintText: &quot;${snapshot.data.name}&quot;, hintStyle: TextStyle( color: Colors .grey, fontSize: 14.0)), ), SizedBox( height: 15, ), Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ Text( 'Mot de passe :', style: TextStyle( color: Color( 0xFF4053FCF), fontSize: 16, fontWeight: FontWeight .w600), ), IconButton( icon: Icon( CommunityMaterialIcons .pencil, color: Colors .grey, ), onPressed: () async { await cahngePwd( context); }) ], ), TextFormField( enabled: enablepwd, focusNode: passwordNode, enableInteractiveSelection: false, obscureText: true, keyboardType: TextInputType .text, decoration: InputDecoration( hintText: &quot;*************&quot;, hintStyle: TextStyle( color: Colors .grey, fontSize: 14.0)), } else { return Text('No Data'); } break; default: return Container(); break; } } } void changePassword() async { setState(() {}); String old_password = _oldController.text; String new_password = _newController.text; String confirm_password = _confirmController.text; try { await userApi.changePassword( old_password, new_password, confirm_password); } catch (err) { print(err.toString()); // Todo: add Snackbar } Navigator.of(context).pop(); // Dismiss alert dialog setState(() {}); </code></pre>
3
15,912
Making a sidebar collapsable on mobile
<p>I have a row of two columns. The left column has a sidebar that stacks on top of the column on the right column on and below the iPad's width. I want it to be collapsible, show active link on as the title and dropdown to show the menu when clicked.</p> <p>I have tried a few ways to achieve this but I cannot get it to work.</p> <p>Here's the HTML:</p> <pre><code>&lt;div class=&quot;col-lg-3 customer-portal-base&quot;&gt; &lt;ul class=&quot;side-bar&quot;&gt; &lt;li class=&quot;side-bar__item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link&quot;&gt;Account&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;side-bar__item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link&quot;&gt;Orders&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;side-bar__item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link&quot;&gt;Order details&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;side-bar__item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link&quot;&gt;My details&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;side-bar__item side-bar__item--is-active&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link side-bar__item-link--is-active&quot;&gt;Account settings&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;side-bar__item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link&quot;&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;side-bar__item&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;side-bar__item-link&quot;&gt;Logout&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>And here's the SCSS:</p> <pre><code>.side-bar { padding: 0; background-color: white; list-style: none; margin-top: 0; width: 97%; &amp;__item { &amp;-link { font-weight: lighter; transition: all 0.5s; &amp;--is-active { color: blue; font-weight: 600; &amp;::after { background-image: url(&quot;&quot;); content: &quot;&quot;; display: inline-block; background-repeat: no-repeat; background-position: center center; width: 1.8rem; height: 1rem; margin-left: 3rem; transform: translateY(0.2rem); @include sidebar-breakpoint { display: none; } } } &amp;:hover, &amp;:active { color: blue; } } cursor: pointer; padding: 1.1rem 0 1.1rem 1.5rem; border-bottom: solid 1px grey; font-size: 0.9rem; &amp;:last-child { border-bottom: 0; } } } </code></pre>
3
1,491
Triggers and Actions for Creature AI
<p>Despite my creature AI working (for the most part), I feel like the way I've set it up is terribly inefficient and likely committing some programming sins. I want to rewrite it to be more clean, efficient, and easier to maintain but I'm not exactly sure where to begin. </p> <p>In my creature AI, I have a list of triggers, such as OnSpawn, OnDeath, or OnCollisionEnter. Within each trigger is a list of actions such as "Cast a Spell" or "Play an Animation". When a trigger's conditions are met, its list of actions are processed to check if it's not already in our processing list, adds it, and then plays their associated actions. When the trigger's conditions are not met, the list of actions are removed from this process list, and similarly processes through some remove functions to clean up behavior.</p> <p>Some code that I've simplified:</p> <pre><code> void Update() { if (canAct &amp;&amp; !dead) { CheckTriggers(); PlayAllActions(); } } private void CheckTriggers() { for (int i = 0; i &lt; actions.Length; i++) { switch (actions[i].trigger) { case ActionTrigger.Trigger.OnCollisionEnter: if (isColliding) AddActionList(actions[i].actionSetList); else RemoveActionList(actions[i].actionSetList); break; case ActionTrigger.Trigger.UponBeingAttacked: if (hasBeenAttacked) AddActionList(actions[i].actionSetList); break; } } } public void AddActionList(ActionSetList actionSetList) { bool containsItem = existingActionsList.Any(item =&gt; item == actionSetList); if (containsItem) return; existingActionsList.Add(actionSetList); } private void PlayAllActions() { if (existingActionsList.Count &gt; 0) for (int i = 0; i &lt; existingActionsList.Count; i++) ActionPlayEffect(existingActionsList[i]); } public void ActionPlayEffect(ActionSetList actionSetList) { for (int i = 0; i &lt; actionSetList.Length; i++) { switch (actionSetList[i].type) { case ActionSet.Type.CastSpell: if (spellRoutine == null &amp;&amp; actionSetList[i].cooldownTimeRemaining &lt;= 0) spellRoutine = StartCoroutine(Cast(actionSetList[i])); break; case ActionSet.Type.PlayAnim: if (!isInActionPose) { animator.SetTrigger("ActionTrigger"); animator.SetInteger("Action", (int)actionSetList[i].animToPlay+1); isInActionPose = true; } break; } } } public void RemoveActionList(ActionSetList actionSetList) { bool containsItem = existingActionsList.Any(item =&gt; item == actionSetList); if (containsItem) { ActionRemoveEffect(actionSetList); existingActionsList.Remove(actionSetList); } } public void ActionRemoveEffect(ActionSetList actionSetList) { for (int i = 0; i &lt; actionSetList.Length; i++) { switch (actionSetList[i].type) { case ActionSet.Type.CastSpell: CancelCast(); break; case ActionSet.Type.PlayAnim: animator.SetTrigger("ActionTrigger"); animator.SetInteger("Action", 0); isInActionPose = false; break; } } } </code></pre> <p>What can I do to build a more efficient creature AI?</p>
3
1,870
AngularJS ng-repeat Post Value not getting in proper pattern
<p>I'm new in AngularJS I want to get post value in proper format. When I use field name as key in checkbox it gives proper value but when I use id as key it does't.</p> <p>Given below code with name as key</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { $scope.mainMenu = {}; $scope.submenu = {}; $scope.pagemenu ={}; $scope.menu = {}; $scope.menus = [ {"menuID":"11","sub_menu":"N","name":"dashboard","sub_menus":""}, {"menuID":"1","sub_menu":"Y","name":"settings","sub_menus":[{"sub_menuID":"1","name":"settings1","page":"Y","pages":[{"pageID":"1","name":"page1"},{"pageID":"2","name":"page2"}]},{"sub_menuID":"2","name":"settings2","page":"N","pages":""}]}, {"menuID":"2","sub_menu":"Y","name":"help","sub_menus":[{"sub_menuID":"3","name":"help1","page":"N","pages":""},{"sub_menuID":"4","name":"help2","page":"N","pages":""}]}, {"menuID":"3","sub_menu":"Y","name":"contact","sub_menus":[{"sub_menuID":"5","name":"contact1","page":"N","pages":""},{"sub_menuID":"6","name":"contact2","page":"N","pages":""}]} ]; $scope.assignValue = function(menuId,submenuId,pageId){ /* if(!$scope.mainMenu[menuId]&amp;&amp;!$scope.submenu[menuId]&amp;&amp;!$scope.pagemenu[menuId]){ delete($scope.mainMenu[menuId]); delete($scope.submenu[menuId]); delete($scope.pagemenu[menuId]); } */ $scope.menu=Object.assign({},$scope.mainMenu, $scope.submenu,$scope.pagemenu); console.log($scope.menu); } $scope.submit = function(){ // alert(JSON.stringify($scope.menu)); console.log(JSON.stringify($scope.menu)); console.log($scope.menu); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;rules&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"&gt;&lt;/script&gt; &lt;script src="mainCtrl.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="app"&gt; &lt;div ng-controller="MainCtrl"&gt; &lt;form ng-submit="submit()"&gt; &lt;ul&gt; &lt;li ng-repeat="x in menus"&gt; &lt;input type="checkbox" ng-change= "assignValue(x.menuID)" ng-model="mainMenu[x.name]" ng-true-value="'{{x.menuID}}'"&gt;{{x.name}} &lt;ul ng-if="[x.sub_menu] == 'Y'"&gt; &lt;li ng-repeat="subMenu in x.sub_menus"&gt; &lt;input type="checkbox" ng-model="submenu[x.name][subMenu.name]" ng-true-value="'{{subMenu.sub_menuID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,null)"&gt;{{subMenu.name}} &lt;ul ng-if="[subMenu.page] == 'Y'"&gt; &lt;li ng-repeat="page in subMenu.pages"&gt; &lt;input type="checkbox" ng-model="pagemenu[x.name][subMenu.name][page.name]" ng-true-value="'{{page.pageID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,page.pageID)"&gt;{{page.name}} &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;button&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>And the code with id as key</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { $scope.mainMenu = {}; $scope.submenu = {}; $scope.pagemenu ={}; $scope.menu = {}; $scope.menus = [ {"menuID":"11","sub_menu":"N","name":"dashboard","sub_menus":""}, {"menuID":"1","sub_menu":"Y","name":"settings","sub_menus":[{"sub_menuID":"1","name":"settings1","page":"Y","pages":[{"pageID":"1","name":"page1"},{"pageID":"2","name":"page2"}]},{"sub_menuID":"2","name":"settings2","page":"N","pages":""}]}, {"menuID":"2","sub_menu":"Y","name":"help","sub_menus":[{"sub_menuID":"3","name":"help1","page":"N","pages":""},{"sub_menuID":"4","name":"help2","page":"N","pages":""}]}, {"menuID":"3","sub_menu":"Y","name":"contact","sub_menus":[{"sub_menuID":"5","name":"contact1","page":"N","pages":""},{"sub_menuID":"6","name":"contact2","page":"N","pages":""}]} ]; $scope.assignValue = function(menuId,submenuId,pageId){ /* if(!$scope.mainMenu[menuId]&amp;&amp;!$scope.submenu[menuId]&amp;&amp;!$scope.pagemenu[menuId]){ delete($scope.mainMenu[menuId]); delete($scope.submenu[menuId]); delete($scope.pagemenu[menuId]); }*/ $scope.menu=Object.assign({},$scope.mainMenu, $scope.submenu,$scope.pagemenu); console.log($scope.menu); } $scope.submit = function(){ // alert(JSON.stringify($scope.menu)); console.log(JSON.stringify($scope.menu)); console.log($scope.menu); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;rules&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"&gt;&lt;/script&gt; &lt;script src="mainCtrl.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="app"&gt; &lt;div ng-controller="MainCtrl"&gt; &lt;form ng-submit="submit()"&gt; &lt;ul&gt; &lt;li ng-repeat="x in menus"&gt; &lt;input type="checkbox" ng-change= "assignValue(x.menuID)" ng-model="mainMenu[x.menuID]" ng-true-value="'{{x.menuID}}'"&gt;{{x.name}} &lt;ul ng-if="[x.sub_menu] == 'Y'"&gt; &lt;li ng-repeat="subMenu in x.sub_menus"&gt; &lt;input type="checkbox" ng-model="submenu[x.menuID][subMenu.sub_menuID]" ng-true-value="'{{subMenu.sub_menuID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,null)"&gt;{{subMenu.name}} &lt;ul ng-if="[subMenu.page] == 'Y'"&gt; &lt;li ng-repeat="page in subMenu.pages"&gt; &lt;input type="checkbox" ng-model="pagemenu[x.menuID][subMenu.sub_menuID][page.pageID]" ng-true-value="'{{page.pageID}}'" ng-change= "assignValue(x.menuID,subMenu.sub_menuID,page.pageID)"&gt;{{page.name}} &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;button&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
3,133
jQuery get() php button submit
<p>I have the following jquery code</p> <pre><code>$(document).ready(function() { //Default Action $("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: &lt;?=$tab;?&gt;}); $("#responsecontainer").load("testing.php?chat=1"); var refreshId = setInterval(function() { $("#responsecontainer").load('testing.php?chat=1'); }, 9000); $("#responsecontainer2").load("testing.php?console=1"); var refreshId = setInterval(function() { $("#responsecontainer2").load('testing.php?console=1'); }, 9000); $('#chat_btn').click(function(event) { event.preventDefault(); var say = jQuery('input[name="say"]').val() if (say) { jQuery.get('testing.php?action=chatsay', { say_input: say} ); jQuery('input[name="say"]').attr('value','') } else { alert('Please enter some text'); } }); $('#console_btn').click(function(event) { event.preventDefault(); var sayc = jQuery('input[name="sayc"]').val() if (sayc) { jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} ); jQuery('input[name="sayc"]').attr('value','') } else { alert('Please enter some text'); } }); $('#kick_btn').click(function(event) { event.preventDefault(); var player_name = jQuery('input[name="player"]').val() if (player_name) { jQuery.get('testing.php?action=kick', { player_input: player_name} ); } else { alert('Please enter some text'); } }); }); </code></pre> <p>Sample Form</p> <pre><code> &lt;form id=\"kick_player\" action=\"\"&gt; &lt;input type=\"hidden\" name=\"player\" value=\"$pdata[name]\"&gt; &lt;input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"&gt;&lt;/form&gt; </code></pre> <p>And the handler code</p> <pre><code>if ($_GET['action'] == 'chatsay') { $name = USERNAME; $chatsay = array($_GET['say_input'],$name); $api-&gt;call("broadcastWithName",$chatsay); die("type: ".$_GET['type']." ".$_GET['say_input']); } if ($_GET['action'] == 'consolesay') { $consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input']; $say = array($consolesay); $api-&gt;call("broadcast",$say); die("type: ".$_GET['type']." ".$_GET['sayc_input']); } if ($_GET['action'] == 'kick') { $kick = "kick ".$_GET['player_input']; $kickarray = array($kick); $api-&gt;call("runConsoleCommand", $kickarray); die("type: ".$_GET['type']." ".$_GET['player_input']); } </code></pre> <p>When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.</p> <p>What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking? </p> <p>I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(</p>
3
1,086
Getting errors after attempting to update log4j and remove display tag
<p>I've recently had to update my log4j dependency as the old one was being pulled in by displaytag. I've converted all of the necessary tables, and things seem to be running fine on the front end, but I'm receiving the following error in the log:</p> <pre><code>Exception while visiting META-INF/versions/9/module-info.class of size 703 Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/StackLocator.class of size 7373 Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/ProcessIdUtil.class of size 778 Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/Base64Util.class of size 862 Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/StackLocator$FqcnCallerLocator.class of size 1894 Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/internal/DefaultObjectInputFilter.class of size 2913 [2022-02-24T11:06:07.096-0600] [glassfish 4.1] [SEVERE] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=50 _ThreadName=deployment-jar-scanner] [timeMillis: 1645722367096] [levelValue: 1000] [[ Exception while visiting META-INF/versions/9/module-info.class of size 703 java.lang.IllegalArgumentException at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:170) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:153) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:424) at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:359) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:165) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:127) at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:345) at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:68) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:304) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:293) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ]] [2022-02-24T11:06:07.098-0600] [glassfish 4.1] [SEVERE] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=50 _ThreadName=deployment-jar-scanner] [timeMillis: 1645722367098] [levelValue: 1000] [[ Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/StackLocator.class of size 7373 java.lang.IllegalArgumentException at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:170) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:153) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:424) at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:359) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:165) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:127) at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:345) at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:68) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:304) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:293) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ]] [2022-02-24T11:06:07.106-0600] [glassfish 4.1] [SEVERE] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=50 _ThreadName=deployment-jar-scanner] [timeMillis: 1645722367106] [levelValue: 1000] [[ Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/ProcessIdUtil.class of size 778 java.lang.IllegalArgumentException at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:170) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:153) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:424) at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:359) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:165) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:127) at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:345) at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:68) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:304) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:293) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ]] [2022-02-24T11:06:07.113-0600] [glassfish 4.1] [SEVERE] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=50 _ThreadName=deployment-jar-scanner] [timeMillis: 1645722367113] [levelValue: 1000] [[ Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/Base64Util.class of size 862 java.lang.IllegalArgumentException at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:170) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:153) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:424) at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:359) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:165) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:127) at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:345) at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:68) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:304) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:293) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ]] [2022-02-24T11:06:07.115-0600] [glassfish 4.1] [SEVERE] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=50 _ThreadName=deployment-jar-scanner] [timeMillis: 1645722367115] [levelValue: 1000] [[ Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/StackLocator$FqcnCallerLocator.class of size 1894 java.lang.IllegalArgumentException at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:170) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:153) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:424) at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:359) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:165) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:127) at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:345) at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:68) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:304) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:293) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ]] [2022-02-24T11:06:07.118-0600] [glassfish 4.1] [SEVERE] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=50 _ThreadName=deployment-jar-scanner] [timeMillis: 1645722367118] [levelValue: 1000] [[ Exception while visiting META-INF/versions/9/org/apache/logging/log4j/util/internal/DefaultObjectInputFilter.class of size 2913 java.lang.IllegalArgumentException at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:170) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:153) at org.glassfish.hk2.external.org.objectweb.asm.ClassReader.&lt;init&gt;(ClassReader.java:424) at org.glassfish.hk2.classmodel.reflect.Parser$5.on(Parser.java:359) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.handleEntry(ReadableArchiveScannerAdapter.java:165) at com.sun.enterprise.v3.server.ReadableArchiveScannerAdapter.onSelectedEntries(ReadableArchiveScannerAdapter.java:127) at org.glassfish.hk2.classmodel.reflect.Parser.doJob(Parser.java:345) at org.glassfish.hk2.classmodel.reflect.Parser.access$300(Parser.java:68) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:304) at org.glassfish.hk2.classmodel.reflect.Parser$3.call(Parser.java:293) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ]] </code></pre> <p>Below is my pom.xml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;name&gt;username-service&lt;/name&gt; &lt;properties&gt; &lt;endorsed.dir&gt;${project.build.directory}/endorsed&lt;/endorsed.dir&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;com.dakuupa&lt;/groupId&gt; &lt;artifactId&gt;struts2-crud-framework&lt;/artifactId&gt; &lt;version&gt;1.0.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-web-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-api&lt;/artifactId&gt; &lt;version&gt;2.12.4&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-core&lt;/artifactId&gt; &lt;version&gt;2.12.4&lt;/version&gt; &lt;/dependency&gt; &lt;!-- above 2 dependencies are for log4j JDK 7 --&gt; &lt;!-- below 2 dependencies for removing server warnings in glassfish about slfj4 --&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-to-slf4j&lt;/artifactId&gt; &lt;version&gt;2.12.4&lt;/version&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.7.25&lt;/version&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-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;compilerArguments&gt; &lt;endorseddirs&gt;${endorsed.dir}&lt;/endorseddirs&gt; &lt;/compilerArguments&gt; &lt;/configuration&gt; &lt;/plugin&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.3&lt;/version&gt; &lt;configuration&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;validate&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${endorsed.dir}&lt;/outputDirectory&gt; &lt;silent&gt;true&lt;/silent&gt; &lt;artifactItems&gt; &lt;artifactItem&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-endorsed-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;type&gt;jar&lt;/type&gt; &lt;/artifactItem&gt; &lt;/artifactItems&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>And my web.xml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt; &lt;filter&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;listener&gt; &lt;listener-class&gt;org.apache.tiles.web.startup.TilesListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;error-page&gt; &lt;error-code&gt;500&lt;/error-code&gt; &lt;location&gt;/error.jsp&lt;/location&gt; &lt;/error-page&gt; &lt;jsp-config&gt; &lt;/jsp-config&gt; &lt;security-constraint&gt; &lt;display-name&gt;SecurityConstraintLoginRequired&lt;/display-name&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;AllWebResources&lt;/web-resource-name&gt; &lt;description/&gt; &lt;url-pattern&gt;/admin/*&lt;/url-pattern&gt; &lt;url-pattern&gt;/secure/*&lt;/url-pattern&gt; &lt;url-pattern&gt;/personsearch/*&lt;/url-pattern&gt; &lt;url-pattern&gt;/JsonSearch&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;auth-constraint&gt; &lt;description&gt;AuthenticationConstraint&lt;/description&gt; &lt;role-name&gt;userRole&lt;/role-name&gt; &lt;/auth-constraint&gt; &lt;/security-constraint&gt; &lt;login-config&gt; &lt;auth-method&gt;BASIC&lt;/auth-method&gt; &lt;realm-name&gt;ldap&lt;/realm-name&gt; &lt;/login-config&gt; &lt;security-role&gt; &lt;role-name&gt;userRole&lt;/role-name&gt; &lt;/security-role&gt; &lt;/web-app&gt; </code></pre> <p>I'm not used to posting on here, so please let me know if any more information is needed to help.</p>
3
8,347
Accessing MVC's model property from Javascript to fill jQuery datatable insted of using json
<p>I am trying to build an ASP.NET MVC application I want to return a model instead of json but I need help to use to model to fill my datatable. </p> <p>Here is my Javascript:</p> <pre><code> @section Scripts{ &lt;script type="text/javascript" charset="utf8" src="~/Scripts/DataTables/jquery.dataTables.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function () { $('#proveedorContactoTable').DataTable({ "ajax": { "url": "/fichaProveedor/loadProveedorContactoTable", "type": "GET", "datatype": "json" }, "columns": [ { "data": "nombre_contacto", "autoWidth": true }, /* index = 0 */ { "data": "apellido_contacto", "autoWidth": true }, /* index = 1 */ { "data": "carga_contacto", "autoWidth": true }, /* index = 2 */ { "data": "telefono_fijo_contacto", "autoWidth": true }, /* index = 3 */ { "data": "telefono_movil_contacto", "autoWidth": true }, /* index = 4 */ { "data": "correo_contacto", "autoWidth": true }, /* index = 5 */ { "data": "principal", "autoWidth": true }, /* index = 6 */ { "data": "contacto_id", "width": "50px", "render": function (data) { return '&lt;a class="popup" href="/fichaProveedor/Detalles/' + data + '"&gt;Editar&lt;/a&gt;'; /* index = 7 */ } }, { "data": "contacto_id", "width": "50px", "render": function (data) { return '&lt;a class="btn btn-primary" href="/fichaProveedor/Eliminar/' + data + '"&gt;Eliminar&lt;/a&gt;'; /* index = 8 */ } } ], 'columnDefs': [{ 'targets': [7, 8], /* column index */ 'orderable': false, /* true or false */ }] }); }); &lt;/script&gt; } </code></pre> <p>And here is my html table</p> <pre><code>&lt;div class="dvScroll"&gt; &lt;table id="myTable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Proveedor Id&lt;/th&gt; &lt;th&gt;Nombre&lt;/th&gt; &lt;th&gt;Dirección&lt;/th&gt; &lt;th&gt;Código postal&lt;/th&gt; &lt;th&gt;Cuidad&lt;/th&gt; &lt;th&gt;País&lt;/th&gt; &lt;th&gt;Pagina internet&lt;/th&gt; &lt;th&gt;Edit&lt;/th&gt; &lt;th&gt;Delete&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>I have the following model that contains a list of "contactos" I want to use all its elements to fill the jQuery table. Here is my model and some of the properties contained in the model.</p> <pre><code>@model erp_colombia.Models.proveedorModel @foreach (var contacto in Model.contactos) { @contacto.contacto_id @contacto.apellido_contacto } </code></pre> <p>Here is my controller so far</p> <pre><code>[HttpPost] public ActionResult Editar(inventarioModel gestiondeubicacione) { inventarioContext gestiondeubicaciones = new inventarioContext(); bool status = false; if (ModelState.IsValid) { if (gestiondeubicacione.componente_id &gt; 0) { //Edit var gestiondeubicacionesFound = gestiondeubicaciones.GetAllInventarios().Where(a =&gt; a.componente_id == gestiondeubicacione.ubicacion_id).FirstOrDefault(); if (gestiondeubicacionesFound != null) { gestiondeubicacionesFound.armario = gestiondeubicacione.armario; gestiondeubicacionesFound.cajon = gestiondeubicacione.cajon; } } else { //gestiondeubicaciones.addInvenotryLocationToDB(gestiondeubicacione); TempData["msgType"] = messageType.success; TempData["msg"] = "Nueva ubicación agregada!"; //Save new one //dc.Employees.Add(emp); } //gestiondeubicaciones.updateInvenotryLocationToDB(gestiondeubicacione); TempData["msgType"] = messageType.success; TempData["msg"] = "La ubicación ha sido actualizada!"; //Update //dc.SaveChanges(); status = true; } return new JsonResult { Data = new { status = status } }; } </code></pre> <p>How can I use my model inside the Javascript instead of the json? Thank you very much for your help.</p>
3
2,623
My recyclerview data keeps getting doubled when i switch to some other fragment and return to that fragment which has the recyclerview
<p>I have a MainActivity where I replace the fragments in a FrameLayout using getSupportFragmentManager().beginTransaction.replace() and the PositionsFragment as given below. </p> <p>When I open PositionFragment initially, data is perfectly displayed, but when I switch to dashboard and then again switch to PositionsFragment, the cards in the recyclerview get doubled. </p> <p>They get doubled every time I switch. I tried clearing the arrayList using productList.clear(); but didn't work. </p> <p>MainActivity where I replace the fragments.</p> <pre><code>case R.id.nav_dashboard: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new DashboardFragment()).commit(); toolbar.setTitle("Dashboard"); break; case R.id.nav_positions: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new PositionsFragment()).commit(); toolbar.setTitle("Positions"); break; </code></pre> <p>PositionsFragment </p> <pre><code>public class PositionsFragment extends Fragment{ public static Spinner spinner; RecyclerView recyclerView; ProgressBar progressBar; ArrayList&lt;Products&gt; productList=new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; positionsArray; FloatingActionButton fab; public PositionsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v=inflater.inflate(R.layout.fragment_positions, container, false); return v; } @Override public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) { super.onViewCreated(v, savedInstanceState); fab=v.findViewById(R.id.positionsFab); progressBar=v.findViewById(R.id.progressBarPositions); progressBar.setVisibility(View.VISIBLE); spinner=v.findViewById(R.id.positionsSpinner); recyclerView=v.findViewById(R.id.positionsRecyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); productList.clear(); new fetchDataPositions(new OnPositionsFetched() { @Override public void OnPositionsFetched() { progressBar.setVisibility(View.INVISIBLE); positionsArray=fetchDataPositions.getArrayList(); for (int i=0;i&lt;positionsArray.size();i++){ productList.add(new Products(//data)); } final PositionsRecyclerAdapter recyclerAdapter=new PositionsRecyclerAdapter(getActivity(),productList,getActivity()); recyclerView.setAdapter(recyclerAdapter); } }).execute(url); ArrayAdapter&lt;CharSequence&gt; adapter = ArrayAdapter.createFromResource(getActivity(), R.array.positions_spinner_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } } </code></pre>
3
1,269
How to select options from two different dropdowns of same css class name using javascript or jquery
<p>I want to update values of two dropdowns as shown in attached image, have a look on html code for the same(using same css proprty for both select)</p> <pre><code>&lt;div class="container-fluid" role="main" style="margin-top: 100px;"&gt; &lt;form id="allPhotoForm"&gt; &lt;fieldset&gt; &lt;legend&gt; Total Pending photos : ${count} &lt;input type="button" id="allPhotoFormBtn" class="btn btn-primary btn-xs pull-right" value="Update All"&gt; &lt;/legend&gt; &lt;/fieldset&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox" class="checkbox1" id="selecctall"&gt; Select All &lt;/label&gt; &lt;/div&gt; &lt;select class="form-control" name="status" id="${imageId}"&gt; &lt;option value="APPROVED"&gt;Approved&lt;/option&gt; &lt;option value="REJECTED"&gt;Rejected&lt;/option&gt; &lt;option value="PENDING"&gt;Pending&lt;/option&gt; &lt;/select&gt; Reason : &lt;span style="float: right;"&gt; &lt;select class="form-control" name="status"&gt; &lt;option value="Animal" id="animal"&gt;Animal&lt;/option&gt; &lt;option value="Bad" id="bad"&gt;Bad&lt;/option&gt; &lt;option value="Baby" id="baby"&gt;Baby&lt;/option&gt; &lt;option value="Celebrity" id="celebrity"&gt;Celebrity&lt;/option&gt; &lt;option value="Flower" id="flower"&gt;Flower&lt;/option&gt; &lt;option value="God" id="god"&gt;God&lt;/option&gt; &lt;option value="Good" id="good"&gt;Good&lt;/option&gt; &lt;option value="Others" id="others"&gt;Others&lt;/option&gt; &lt;/select&gt; &lt;/span&gt; </code></pre> <p>and </p> <pre><code>&lt;div class="checkbox"&gt;&lt;label&gt; &lt;input type="checkbox" class="checkbox1 status" value="id=${id}&amp;objectId=${imageId}&amp;status=&amp;reason="&gt;Check me out &lt;/label&gt; &lt;/div&gt; </code></pre> <p><a href="https://i.stack.imgur.com/g6Hrk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g6Hrk.png" alt="enter image description here"></a></p> <p>AJAX code for the same is as follows which binds all input data and pushes to API</p> <pre><code>$('#allPhotoFormBtn').on( "click", function(event) { event.preventDefault(); var allCheckBox = document.querySelectorAll('.status'); var data = []; $(allCheckBox).each( function(index) { if ($(this).is(':checked')) { var status = $( $(this).parent().parent().prev()) .val(); data.push($(this).val().replace("status=", "status=" + status)); } }); $.ajax({ url : "/curation/updateAll", data : { 'data' : data.join(',') }, type : "POST", success : function(response) { if (response) location.reload(); }, error : function(rs) { console.log(rs); } }) }); </code></pre> <p>I am able to fetch one drop down value successfully, but unable to fetch another one, below statement gives only one dropdown value but not both.</p> <pre><code>var status = $($(this).parent().parent().prev()).val(); </code></pre>
3
2,167
Android XML - Trying to hide remove "preference" option
<p>Trying to hide the "DisableGMS" option but dont know where to put the code or how to use it, there arent many examples that i can find online on how to implement "removePreference". everyone just say use "removePreference" but no implementation examples on how its used in the code or where its put. Can someone please put it in for me?</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;ListPreference android:entries="@array/LockScreenEffectName" android:title="Unlock effect settings" android:key="lockscreen_effect" android:summary="Set the phone to unlock effect" android:entryValues="@array/LockScreenEffectValue"/&gt; &lt;SwitchPreference android:title="Moon calendar lock screen settings" android:key="lockscreen_showmoon" android:summary="It is displayed on the moon lock screen" android:summaryOn="moon lock screen has been enabled" android:summaryOff="moon lock screen has been disabled"/&gt; &lt;SwitchPreference android:title="Lock screen clock shows seconds" android:key="aurora_lockscreen_seconds" android:summary="Second display on the lock screen" android:summaryOn="Lock screen has been displayed in seconds" android:summaryOff="Lock screen has hidden seconds"/&gt; &lt;EditTextPreference android:title="Custom lock screen operator name" android:key="CarrierText_Keyguard" android:summary="Lock screen will display the operator name custom name" android:dialogTitle="Please enter the custom lock screen operator name"/&gt; &lt;ListPreference android:entries="@array/SettingName" android:title="System Settings Style" android:key="listui" android:summary="Setting your favorite style system settings" android:entryValues="@array/SettingValue"/&gt; &lt;SwitchPreference android:title="WIFI signal optimization" android:key="WifiManager" android:summary="WIFI signal optimization" android:summaryOn="It has opened WIFI Optimization" android:summaryOff="WIFI optimization has been closed"/&gt; &lt;ListPreference android:entries="@array/ScreenModeName" android:title="Screen display mode" android:key="ScreenMode" android:summary="Change the screen display mode" android:entryValues="@array/ScreenModeValue"/&gt; &lt;SwitchPreference android:title="3 dot menu mode" android:key="3dot_menu" android:summary="Three menu keys increase" android:summaryOn="3:00 menu has been opened" android:summaryOff="3:00've hidden menu"/&gt; &lt;ListPreference android:entries="@array/SoundVolumeName" android:title="Sound volume settings" android:key="SoundVolume" android:summary="Appropriate adjustments phone loud sound" android:entryValues="@array/SoundVolumeValue"/&gt; &lt;ListPreference android:entries="@array/LocationName" android:title="Network Location Service Engine" android:key="networklocation" android:summary="Choose Baidu or Google engine" android:entryValues="@array/LocationValue"/&gt; &lt;SwitchPreference android:title="DisableGMS" android:key="gms_service" android:summary="to disable gms" android:summaryOn="GMS Enabled" android:summaryOff="GMS Disabled"/&gt; &lt;SwitchPreference android:title="Lock Screen Weather" android:key="LockScreenWeather" android:summary="Lock screen display weather information" android:summaryOn="Lock screen weather enabled" android:summaryOff="Lock screen weather disabled"/&gt; &lt;SwitchPreference android:title="Lock screen pedometer" android:key="LockScreenSteps" android:summary="Lock screen information display pedometer" android:summaryOn="Lock screen pedometer has been shown" android:summaryOff="Lock screen pedometer has been hidden"/&gt; &lt;SwitchPreference android:title="Quick Unlock the lock screen (no point OK)" android:key="AutoUnlock" android:summary="In the lock screen is OK to complete the password entry point" android:summaryOn="Quick Unlock enabled" android:summaryOff="Quick Unlock has been disabled"/&gt; &lt;SwitchPreference android:title="Turn on screen when a USB connection or disconnection" android:key="NoWakeOnPlugOrUnplug" android:summary="Turn screen on when USB connection or disconnection" android:summaryOn="When connected turn on" android:summaryOff="When connected stays off"/&gt; &lt;SwitchPreference android:title="Automatic brightness fine-tuning (+ -5)" android:key="AutoBrightAdjst" android:summary="Enable automatic brightness trim function" android:summaryOn="Automatic brightness trimming has been opened" android:summaryOff="Automatic brightness trimming has been closed"/&gt; &lt;SwitchPreference android:title="Status Bar Time centered" android:key="CenterTime" android:summary="Status Bar Time centered" android:summaryOn="Status Bar Time centered open" android:summaryOff="Status Bar Time centered Close"/&gt; &lt;SwitchPreference android:title="Double-click the status bar lock screen" android:key="DoubleClickOffScreen" android:summary="Double-click the status bar lock screen" android:summaryOn="Double-click the status bar lock screen has been opened" android:summaryOff="Double-click the status bar has been closed lock screen"/&gt; &lt;SwitchPreference android:title="Smart cover lock screen weather information" android:key="LockWeather" android:summary="Weather information is displayed in a holster lock screen" android:summaryOn="Case lock screen to display weather information has been" android:summaryOff="Case lock screen weather information has been hidden"/&gt; &lt;SwitchPreference android:title="Smart cover lock screen pedometer" android:key="LockWalkMate" android:summary="Whether the holster lock screen display pedometer" android:summaryOn="Case lock screen pedometer has been shown" android:summaryOff="Pedometers hide leather lock screen"/&gt; &lt;/PreferenceScreen&gt; </code></pre>
3
1,542
Validations pass but when merge() is called a validation error is thrown
<p>Sorry for asking here but I can't for the life of me understand what is going on. Been looking for answers all around the web for hours with no luck.</p> <p>I have a simple Quiz modelled in JPA, using <a href="http://www.vraptor.org/" rel="nofollow">VRaptor</a> (an MVC framework) running in a WildFly 10.0.0.Final server which uses Hibernate 5.0.7.Final. A Quiz have many Questions which have <strong>2-10</strong> Alternatives each.</p> <p>I'm currently implementing a method for users to add/remove Questions on a Quiz. Before calling <code>merge(quiz)</code> I run the validations to make sure everything is valid. It passes. I get no errors.</p> <p>Since there are no validation errors, I call <code>merge(quiz)</code> and finally I'm greeted with the following exception:</p> <pre><code>javax.validation.ConstraintViolationException: Validation failed for classes [game.Question] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Cannot be empty', propertyPath=alternatives, rootBeanClass=class game.Question, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'} ] </code></pre> <p>[Edit] If I deliberately leave something blank it does show the validation error and doesn't try to <code>merge()</code>, so validations are being run as expected.</p> <p>I've checked the whole thing manually and there really are no errors. Used this "alternative" method to check and print validation errors:</p> <pre><code>private void val(final Object obj, final String s) { final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); final javax.validation.Validator validator = factory.getValidator(); final Set&lt;ConstraintViolation&lt;Object&gt;&gt; constraintViolations = validator.validate(obj); for (final ConstraintViolation cv : constraintViolations) { log.info("-------------"); log.info(s + " ValidatationConstraint: " + cv.getConstraintDescriptor().getAnnotation()); log.info(s + " ValidatationConstraint: " + cv.getConstraintDescriptor()); log.info(s + " ValidatationConstraint: " + cv.getMessageTemplate()); log.info(s + " ValidatationConstraint: " + cv.getInvalidValue()); log.info(s + " ValidatationConstraint: " + cv.getLeafBean()); log.info(s + " ValidatationConstraint: " + cv.getRootBeanClass()); log.info(s + " ValidatationConstraint: " + cv.getPropertyPath().toString()); log.info(s + " ValidatationConstraint: " + cv.getMessage()); log.info("-------------"); } } </code></pre> <p>This is roughly what my add/remove Questions method do:</p> <pre><code>@Transactional public void updateQuestions(final String quizId, final List&lt;Question&gt; questions) { // Quizzes might have slugs (/quiz-name) final Quiz quiz = findQuizByIdString(quizId); if (quiz != null) { for (final Question question : questions) { question.setQuiz(quiz); if (question.getAlternatives() != null) { for (final Alternative alt : question.getAlternatives()) { alt.setQuestion(question); } } if (question.getId() != null) { final Question old = (Question) ps.createQuery("FROM Question WHERE id = :id AND quiz = :quiz").setParameter("id", question.getId()).setParameter("quiz", quiz).getSingleResult(); // Making sure the Question do belong to the this Quiz if (old == null) { question.setId(null); } } if (question.getId() == null) { // Set the new question up (who created, timestamp, etc.) } } quiz.setQuestions(questions); if (!validator.validate(quiz).hasErrors()) { try { entityManager.merge(quiz); } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Error while updating Quiz Questions", e); } } } } else { // Send an error to the user } } </code></pre> <p>And finally these are the (what I think) relevant parts of my entities:</p> <pre><code>@Entity public class Quiz { /* ... */ @Valid // FYI: This just makes the validation cascade @OneToMany(mappedBy = "quiz", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true) private List&lt;Question&gt; questions; /* ... */ } @Entity public class Question { /* ... */ @Valid @NotEmpty @Size(min = 2, max = 10) @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) private List&lt;Alternative&gt; alternatives; /* ... */ } @Entity public class Alternative { /* ... */ @NotBlank @Size(max = 0xFF) @Column(length = 0xFF, nullable = false) private String text; // The only field that must be filled /* ... */ } </code></pre>
3
1,920
Any solution to select the dropdown value rather than first index
<p>I have five options with same values in it. Is there any way to select all the indexes of option tag rather than first index.</p> <p>Consider this js fiddle for the same </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var duplicates = []; function checkResult(){ var box1 = document.getElementById('box_g1'); var box2 = document.getElementById('box_g2'); var box3 = document.getElementById('box_g3'); var box4 = document.getElementById('box_g4'); var box5 = document.getElementById('box_g5'); var b1 = box1.options[box1.selectedIndex].value; var b2 = box2.options[box2.selectedIndex].value; var b3 = box3.options[box3.selectedIndex].value; var b4 = box4.options[box4.selectedIndex].value; var b5 = box5.options[box5.selectedIndex].value; console.log(b1); console.log(b2); console.log(b3); console.log(b4); console.log(b5); var arr = [b1,b2,b3,b4,b5]; var hash = []; for (var n=arr.length; n--; ){ if (typeof hash[arr[n]] === 'undefined' ) hash[arr[n]] = []; hash[arr[n]].push(n); } for (var key in hash){ if (hash.hasOwnProperty(key) &amp;&amp; hash[key].length &gt; 1){ duplicates.push(key); } } if(duplicates.length &gt; 0){ alert("duplicate found"); }else{ alert("No duplicate"); } duplicates.length =0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;select name="n1" id="box_g1"&gt; &lt;option value="Default"&gt;Default&lt;/option&gt; &lt;option value="A"&gt;A&lt;/option&gt; &lt;option value="B"&gt;B&lt;/option&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="D"&gt;D&lt;/option&gt; &lt;option value="E"&gt;E&lt;/option&gt; &lt;/select&gt; &lt;br/&gt; &lt;select name="n2" id="box_g2"&gt; &lt;option value="Disabled"&gt;Disabled&lt;/option&gt; &lt;option value="A"&gt;A&lt;/option&gt; &lt;option value="B"&gt;B&lt;/option&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="D"&gt;D&lt;/option&gt; &lt;option value="E"&gt;E&lt;/option&gt; &lt;/select&gt; &lt;br/&gt; &lt;select name="n3" id="box_g3"&gt; &lt;option value="Disabled"&gt;Disabled&lt;/option&gt; &lt;option value="A"&gt;A&lt;/option&gt; &lt;option value="B"&gt;B&lt;/option&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="D"&gt;D&lt;/option&gt; &lt;option value="E"&gt;E&lt;/option&gt; &lt;/select&gt; &lt;br/&gt; &lt;select name="n4" id="box_g4"&gt; &lt;option value="Disabled"&gt;Disabled&lt;/option&gt; &lt;option value="A"&gt;A&lt;/option&gt; &lt;option value="B"&gt;B&lt;/option&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="D"&gt;D&lt;/option&gt; &lt;option value="E"&gt;E&lt;/option&gt; &lt;/select&gt; &lt;br/&gt; &lt;select name="n5" id="box_g5"&gt; &lt;option value="Disabled"&gt;Disabled&lt;/option&gt; &lt;option value="A"&gt;A&lt;/option&gt; &lt;option value="B"&gt;B&lt;/option&gt; &lt;option value="C"&gt;C&lt;/option&gt; &lt;option value="D"&gt;D&lt;/option&gt; &lt;option value="E"&gt;E&lt;/option&gt; &lt;/select&gt; &lt;br/&gt; &lt;br/&gt; &lt;input type="submit" value="Check Result" onclick="checkResult();"/&gt;</code></pre> </div> </div> </p> <p>I did some trick. But not able to identify, whether it is possible or not.</p> <p>For box2, box3, box4 and box5, if the user select 'Disbaled' option for any of the boxes rather than box1.</p> <p>the user will be shown a pop up : "Duplicates found".</p> <p>Currently, if i select <strong>"Disabled"</strong> option, it shows duplicate found which i dont want. </p>
3
1,679
Consuming restapi and store Json response to different tables in Springboot JPA?
<p>I am new to Spring boot and these JSON objects. I have a requirement where I need to invoke GET RestAPI and it returns list of nested Json Objects. I need some particular fields from Json object and store it into Database(SQL Server-backend) tables. And these tables having relationship between them,also my Entity class and these Json structure not same. below is my code, Json response:</p> <pre><code>[ { &quot;ApplicationName&quot;: &quot;ACD tool&quot;, &quot;city&quot;: &quot;Europe&quot;, &quot;IsActive&quot;: &quot;true&quot;, &quot;AppOwner&quot;: &quot;Ragavendr raj&quot;, &quot;AppTeamMember&quot;: &quot;Siyan&quot;, &quot;CreatedBy&quot;: &quot;pav&quot;, &quot;AppDetails&quot;: { &quot;Language&quot;: &quot;VB.net&quot;, &quot;Version&quot;: &quot;2.0&quot; } }, { &quot;ApplicationName&quot;: &quot;QR check&quot;, &quot;city&quot;: &quot;US&quot;, &quot;IsActive&quot;: &quot;true&quot;, &quot;AppOwner&quot;: &quot;Amar&quot;, &quot;AppTeamMember&quot;: &quot;miyas&quot;, &quot;CreatedBy&quot;: &quot;rosh&quot;, &quot;AppDetails&quot;: { &quot;Language&quot;: &quot;c#&quot;, &quot;Version&quot;: &quot;2.0&quot; } } ] </code></pre> <p>Table entities: Application Entity:</p> <pre><code> @Entity @Table(name=&quot;APPLICATION&quot;) public class Application implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=&quot;APPLICATION_ID&quot;) private long applicatioId; @Column(name=&quot;APPLICATION_NAME&quot;) private String applicationName; @ManyToMany(mappedBy=&quot;application&quot;) private List&lt;ApplicationUserRoleMap&gt; applicationUserRoleMap; @Column(name=&quot;CREATED_BY&quot;) private String createdBy; @Column(name=&quot;CREATED_ON&quot;) private String createdOn; @Column(name=&quot;MODIFIED_BY&quot;) private String modifiedBy; @Column(name=&quot;MODIFIED_ON&quot;) private String modifiedOn; @Column(name=&quot;DELETE_FLG&quot;) private String deleteFlg; @Column(name=&quot;DISPLAY_FLG&quot;) private String displayFlg; //getters and setters } </code></pre> <p>User Entity:</p> <pre><code> @Entity @Table(name=&quot;USER&quot;) public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=&quot;USER_ID&quot;) private long userId; @Column(name=&quot;USER_NAME&quot;) private String userName; @ManyToMany(mappedBy=&quot;user&quot;) private List&lt;ApplicationUserRoleMap&gt; applicationUserRoleMap; @Column(name=&quot;CREATED_BY&quot;) private String createdBy; @Column(name=&quot;CREATED_ON&quot;) private String createdOn; @Column(name=&quot;MODIFIED_BY&quot;) private String modifiedBy; @Column(name=&quot;MODIFIED_ON&quot;) private String modifiedOn; @Column(name=&quot;DELETE_FLG&quot;) private String deleteFlg; @Column(name=&quot;DISPLAY_FLG&quot;) private String displayFlg; //getters and setters } </code></pre> <p>Role Entity:</p> <pre><code> @Entity @Table(name=&quot;ROLE&quot;) public class Role implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=&quot;ROLE_ID&quot;) private long roleId; @Column(name=&quot;ROLE_NAME&quot;) private String roleName; @ManyToMany(mappedBy=&quot;role&quot;) private List&lt;ApplicationUserRoleMap&gt; applicationUserRoleMap; @Column(name=&quot;CREATED_BY&quot;) private String createdBy; @Column(name=&quot;CREATED_ON&quot;) private String createdOn; @Column(name=&quot;MODIFIED_BY&quot;) private String modifiedBy; @Column(name=&quot;MODIFIED_ON&quot;) private String modifiedOn; @Column(name=&quot;DELETE_FLG&quot;) private String deleteFlg; @Column(name=&quot;DISPLAY_FLG&quot;) private String displayFlg; //getters and setters } </code></pre> <p>ApplicationUserRoleMap entity:</p> <pre><code>@Entity @Table(name=&quot;APPLICATION_USER_ROLE_MAP&quot;) public class ApplicationUserRoleMap implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=&quot;APPLICATION_USER_ROLE_MAP_ID&quot;) private long applicatioUserRoleMapId; @ManyToMany @JoinColumn(name=&quot;APPLICATION_ID&quot;) private List&lt;Application&gt; application; @ManyToMany @JoinColumn(name=&quot;USER_ID&quot;) private List&lt;User&gt; user; @ManyToMany @JoinColumn(name=&quot;ROLE_ID&quot;) private List&lt;Role&gt; role; @Column(name=&quot;CREATED_BY&quot;) private String createdBy; @Column(name=&quot;CREATED_ON&quot;) private String createdOn; @Column(name=&quot;MODIFIED_BY&quot;) private String modifiedBy; @Column(name=&quot;MODIFIED_ON&quot;) private String modifiedOn; @Column(name=&quot;DELETE_FLG&quot;) private String deleteFlg; @Column(name=&quot;DISPLAY_FLG&quot;) private String displayFlg; //getters and setters } </code></pre> <p>From json object fields AppOwner and AppTeamMember should added to roles table and their corresponding name added to user table, role-user-appliication ids mapping added to map table.</p> <p>Can someone suggest me the best way to achieve this...Thanks</p>
3
2,569
StructureFareRulesRQ Parse Failure - Visual Studio Web Reference Naming Convention Error?
<p>I'm trying to call the StructureFareRulesRQ API from Sabre but its seems as though this API is different than the rest of the Sabre APIs. After adding the wsdl file to my project, I am expecting the Web Service call method to be named something like StructureFareRulesRQService but that doesn't exist. Instead I get StructureFareRulesRQ as the actual service and StructureFareRulesRQ1 as the wrapper class for the XML message. As the wrapper class has the wrong name, when it gets serialized, it creates a bogus XML message (see below).</p> <p>I know I can probably dig through the reference.cs file and do a find/replace, but I'm concerned that doing that will require me to do the same thing whenever a new version comes online. Has anyone else run into this, or am I going nuts? </p> <p>Example XML Payload which returns a "Error ErrorCode="009400" ErrorMessage="PARSE FAILURE - INVALID REQUEST" response from Sabre:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;StructureFareRulesRQ1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;PriceRequestInformation CurrencyCode="USD" BuyingDate="2019-05-21T13:46:00" xmlns="http://webservices.sabre.com/sabreXML/2003/07"&gt; &lt;PassengerTypes&gt; &lt;PassengerType Code="ADT" /&gt; &lt;/PassengerTypes&gt; &lt;ReturnAllData /&gt; &lt;/PriceRequestInformation&gt; &lt;AirItinerary xmlns="http://webservices.sabre.com/sabreXML/2003/07"&gt; &lt;OriginDestinationOptions&gt; &lt;OriginDestinationOption&gt; &lt;FlightSegment SegmentType="A" DepartureDate="2019-08-17T17:35:00" BookingDate="2019-05-21T13:46:00" RealReservationStatus="SS"&gt; &lt;DepartureAirport LocationCode="ORD" /&gt; &lt;ArrivalAirport LocationCode="HEL" /&gt; &lt;MarketingAirline Code="AY" /&gt; &lt;OperatingAirline Code="AY" /&gt; &lt;/FlightSegment&gt; &lt;PaxTypeInformation FareBasisCode="IFLE2US2" PassengerType="ADT" FareComponentNumber="0" /&gt; &lt;/OriginDestinationOption&gt; &lt;OriginDestinationOption&gt; &lt;FlightSegment SegmentType="A" DepartureDate="2019-08-18T13:25:00" BookingDate="2019-05-21T13:46:00" RealReservationStatus="SS"&gt; &lt;DepartureAirport LocationCode="HEL" /&gt; &lt;ArrivalAirport LocationCode="SVO" /&gt; &lt;MarketingAirline Code="AY" /&gt; &lt;OperatingAirline Code="SU" /&gt; &lt;/FlightSegment&gt; &lt;PaxTypeInformation FareBasisCode="IFLE2US2" PassengerType="ADT" FareComponentNumber="0" /&gt; &lt;/OriginDestinationOption&gt; &lt;OriginDestinationOption&gt; &lt;FlightSegment SegmentType="A" DepartureDate="2019-08-29T10:40:00" BookingDate="2019-05-21T13:46:00" RealReservationStatus="SS"&gt; &lt;DepartureAirport LocationCode="SVO" /&gt; &lt;ArrivalAirport LocationCode="HEL" /&gt; &lt;MarketingAirline Code="AY" /&gt; &lt;OperatingAirline Code="SU" /&gt; &lt;/FlightSegment&gt; &lt;PaxTypeInformation FareBasisCode="IFLE2US2" PassengerType="ADT" FareComponentNumber="0" /&gt; &lt;/OriginDestinationOption&gt; &lt;OriginDestinationOption&gt; &lt;FlightSegment SegmentType="A" DepartureDate="2019-08-29T13:55:00" BookingDate="2019-05-21T13:46:00" RealReservationStatus="SS"&gt; &lt;DepartureAirport LocationCode="HEL" /&gt; &lt;ArrivalAirport LocationCode="ORD" /&gt; &lt;MarketingAirline Code="AY" /&gt; &lt;OperatingAirline Code="AY" /&gt; &lt;/FlightSegment&gt; &lt;PaxTypeInformation FareBasisCode="IFLE2US2" PassengerType="ADT" FareComponentNumber="0" /&gt; &lt;/OriginDestinationOption&gt; &lt;/OriginDestinationOptions&gt; &lt;/AirItinerary&gt; &lt;/StructureFareRulesRQ1&gt; </code></pre>
3
1,618
Push Notifications don't appear on devices
<p>I have already written a lot of code in which I set notifications and try to send a notification from a user to another but now here is my problem, there isn't any notification that appears on the other user's device. The app doesn't crash and I have don't have build failed so I really don't know where I am wrong. Thanks in advance for your answers, here's my code...</p> <p>// Parts about push notifications in AppDelegate.swift</p> <pre><code>static let NOTIFICATION_URL = "https://gcm-http.googleapis.com/gcm/send" static var DEVICEID = String() static let SERVERKEY = "AAAAuIcRiYI:APA91bHA8Q4IJBG9dG4RY9YOZ3v4MlcVZjmYs3XhiMY3xpQm3bTSjrINUiImaE0t17Y6mghR2vN1ezJTMSVFmHlgOUBX8KQZEckgwCkc1tlMdpm_UjxobmrHf3GbvwrKtHVZsJR-v1GG" #available(iOS 10.0, *){ UNUserNotificationCenter.current().delegate = self // Request Autorization. let option : UNAuthorizationOptions = [.alert,.badge,.sound] UNUserNotificationCenter.current().requestAuthorization(options: option) { (bool, err) in } } else{ let settings : UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() UIApplication.shared.applicationIconBadgeNumber = 0 func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { guard let newToken = InstanceID.instanceID().token() else {return} AppDelegate.DEVICEID = newToken connectToFCM() } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -&gt; Void) { let notification = response.notification.request.content.body print(notification) completionHandler() } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { guard let token = InstanceID.instanceID().token() else {return} AppDelegate.DEVICEID = token print(token) connectToFCM() } func connectToFCM() { Messaging.messaging().shouldEstablishDirectChannel = true } </code></pre> <p>// Parts about notifications in messages.swift, I call this function after the user sends a message in way that the person who receives the message receives at the same time a notification.</p> <pre><code>fileprivate func setupPushNotification(fromDevice:String) { Database.database().reference().child("users").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in let value = snapshot.value as? NSDictionary let device = value?["device"] as? String ?? "" guard let message = self.authorText else {return} let title = "You received a new message !" let body = "from \(message)" let toDeviceID = device var headers:HTTPHeaders = HTTPHeaders() headers = ["Content-Type":"application/json","Authorization":"key=\(AppDelegate.SERVERKEY)" ] let notification = ["to":"\(toDeviceID)","notification":["body":body,"title":title,"badge":1,"sound":"default"]] as [String:Any] Alamofire.request(AppDelegate.NOTIFICATION_URL as URLConvertible, method: .post as HTTPMethod, parameters: notification, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in print(response) } }) } </code></pre>
3
1,148
Apache James Mail Server: Where to put custom Mailets?
<p>I want to wite a custom Mailet for the Apache James Mail Server.</p> <p>I'm running James through Docker via the <code>linagora/james-project</code> image. The setup works (only locally of course, but that's enough for the moment), as I can set up accounts and connect to them with Thunderbird via IMAP and I can send mails between those accounts.</p> <p>Now I want to deploy my custom Mailet to this setup. I have tried it using this tutorial: <a href="https://james.apache.org/server/3/dev-extend-mailet.html" rel="nofollow noreferrer">https://james.apache.org/server/3/dev-extend-mailet.html</a> (I had to create the folder /conf/lib/ since it didn't exist) but it won't work. In the Log I see errors like this one:</p> <pre><code>james | [main] INFO org.apache.james.mailetcontainer.lib.AbstractStateMailetProcessor - Matcher All instantiated. james | [main] ERROR org.apache.james.mailetcontainer.lib.AbstractStateMailetProcessor - Unable to init mailet com.jeremiaslubberger.mailets.TestMailet: javax.mail.MessagingException: Can not load mailet com.jeremiaslubberger.mailets.TestMailet; james | nested exception is: james | java.lang.ClassNotFoundException: com.jeremiaslubberger.mailets.TestMailet james | javax.mail.MessagingException: Can not load mailet com.jeremiaslubberger.mailets.TestMailet; james | nested exception is: james | java.lang.ClassNotFoundException: com.jeremiaslubberger.mailets.TestMailet </code></pre> <p>By searching the source code, I found the file <code>ExtendedClassLoader.java</code> where there is a line <code>public static final String EXTENSIONS_JARS_FOLDER_NAME = "extensions-jars/";</code> So I tried creating this folder (in the James root folder) and putting the JAR containing the custom Mailet there.</p> <p>This still produces errors and doesn't work, however the Log now looks like this:</p> <pre><code>james | [main] INFO org.apache.james.mailetcontainer.lib.AbstractStateMailetProcessor - Matcher All instantiated. james | Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/mailet/GenericMailet james | at java.lang.ClassLoader.defineClass1(Native Method) james | at java.lang.ClassLoader.defineClass(ClassLoader.java:763) james | at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) james | at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) james | at java.net.URLClassLoader.access$100(URLClassLoader.java:73) james | at java.net.URLClassLoader$1.run(URLClassLoader.java:368) james | at java.net.URLClassLoader$1.run(URLClassLoader.java:362) james | at java.security.AccessController.doPrivileged(Native Method) james | at java.net.URLClassLoader.findClass(URLClassLoader.java:361) james | at java.lang.ClassLoader.loadClass(ClassLoader.java:424) james | at java.lang.ClassLoader.loadClass(ClassLoader.java:357) james | at org.apache.james.utils.ExtendedClassLoader.locateClass(ExtendedClassLoader.java:80) james | at org.apache.james.utils.GuiceGenericLoader.instanciate(GuiceGenericLoader.java:37) james | at org.apache.james.utils.GuiceMailetLoader.getMailet(GuiceMailetLoader.java:45) </code></pre> <p>My custom Mailet does extend GenericMailet, but so do all other (default) Mailets. Also, I exported my mailet including all resources, so there should be nothing missing there. Now I'm out of ideas.</p> <p>Can anyone please help? Where do I need to put the JAR containing my custom Mailet?</p>
3
1,172
@PostConstuct does not appear to work and @autowire gives an error
<p>I am new to spring and am creating a spring web application. The application I'm writing has a <code>Class PreLoadService</code>. In this class is a method defined with <code>@PostConstruct</code> that calls a DAO to load the data. The DAO instance is declared in the class with the <code>@autowired</code>.</p> <p>The Controller for the JSP then declares an instance of the <code>PreLoadService</code> and calls the getter to retrieve the data that should have been loaded in the <code>@PostConstruct</code>. The data is never loaded and an exception is also thrown on the <code>@autowired</code>.</p> <p>Since this did not work I tried a simple Hello World version to write a message and received the same issue. I will post this. In the WEB_INF folder I have a <code>web.xml</code> and a <code>spring3-servlet.xml</code>. In the SRC folder I have an <code>applicationContext.xml</code>. I am running on Tomcat 7.</p> <p><strong>Web.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;display-name&gt;Spring3MVC&lt;/display-name&gt; &lt;context-param&gt; &lt;param-name&gt;webAppRootKey&lt;/param-name&gt; &lt;param-value&gt;root.webpath&lt;/param-value&gt; &lt;/context-param&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet&gt; &lt;servlet-name&gt;spring3&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;spring3&lt;/servlet-name&gt; &lt;url-pattern&gt;*.html&lt;/url-pattern&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt;&lt;/web-app&gt; </code></pre> <p><strong>spring3-servlet.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!--will allow Spring to load all the components from package and all its child packages--&gt; &lt;mvc:annotation-driven /&gt; &lt;context:component-scan base-package="com.nikki.spring3.controller" /&gt; &lt;!-- will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jsp to the view in ModelAndView. --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /&gt; &lt;property name="prefix" value="/WEB-INF/jsp/" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <hr> <p><strong>applicationContext.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;mvc:annotation-driven/&gt; &lt;context:component-scan base-package="com.nikki.spring3"&gt; &lt;context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/&gt; &lt;/context:component-scan&gt; &lt;bean id="helloWorldService" class="com.nikki.spring3.beansit.HelloWorldService"&gt; &lt;property name="message" value="Preloading Init Config and Data" /&gt; </code></pre> <p> </p> <p><strong>HelloWorldService</strong></p> <pre><code>public class HelloWorldService { private String message; public void setMessage(String message){ this.message = message; } public String getMessage(){ System.out.println("Your Message : " + message); return message; } @PostConstruct public void init(){ System.out.println("Bean is going through init."); } @PreDestroy public void destroy(){ System.out.println("Bean will destroy now."); } } </code></pre> <p><strong>HelloWorldController</strong></p> <pre><code> @Controller public class HelloWorldController { @Autowired HelloWorldService helloWorldService; /* RequestMapping annotation tells Spring that this Controller should * process all requests beginning with /hello in the URL path. * That includes /hello/* and /hello.html. */ @RequestMapping("/hello") public ModelAndView helloWorld() { String message =helloWorldService.getMessage(); //"Hello World, Spring 3.0!"; return new ModelAndView("hello", "message", message); } } </code></pre> <p><strong>Error Message</strong></p> <pre><code>Exception SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloWorldController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.nikki.spring3.beansit.HelloWorldService com.nikki.spring3.controller.HelloWorldController.helloWorldService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.nikki.spring3.beansit.HelloWorldService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) </code></pre> <p>I appreciate any help. Thanks.</p>
3
2,706
Is there an other way to include Jquery lib to communicate between Angular and this library?
<p>I had to include a kind of library called RappidJS and a lot of Jquery files into an Angular 7 Project. I used an homemade fonction to do it in my component :</p> <pre><code>ngOnInit() { this.loadScript('./app/assets/node_modules/jquery/dist/jquery.js'); this.loadScript('./app/assets/node_modules/lodash/index.js'); this.loadScript('./app/assets/node_modules/backbone/backbone.js'); this.loadScript('./app/assets/build/rappid.min.js'); this.loadScript('./app/assets/src/joint.ui.inspector.min.js'); this.loadScript('./app/assets/src/joint.shapes.qad.js'); this.loadScript('./app/assets/src/selection.js'); this.loadScript('./app/assets/src/factory.js'); this.loadScript('./app/assets/src/snippet.js'); this.loadScript('./app/assets/src/app.js'); this.loadScript('./app/assets/src/index.js'); } public loadScript(url: string) { const body = &lt;HTMLDivElement&gt;document.body; const script = document.createElement('script'); script.innerHTML = ''; script.src = url; script.async = false; script.defer = true; body.appendChild(script); } </code></pre> <p>The JS execute fine and my app shows up without any problem. However i need to communicate with some functions in "app.js" to retrieve some json and use it into my angular app.</p> <p>In my component.html i have a toolbar :</p> <pre><code> &lt;div id="toolbar"&gt; &lt;button class="btn btn-secondary add-question"&gt;Ajouter Question&lt;/button&gt; &lt;button class="btn btn-secondary add-answer"&gt;Ajouter Réponse&lt;/button&gt; &lt;button class="btn btn-secondary add-API"&gt;Ajouter module API&lt;/button&gt; &lt;button class="btn btn-success add-APIEX"&gt;Ajouter module Ping&lt;/button&gt; &lt;button class="btn send-json"&gt;Envoyer JSON&lt;/button&gt; &lt;button class="btn btn-secondary preview-dialog"&gt;Lancer dialogue&lt;/button&gt; &lt;button class="btn btn-secondary code-snippet"&gt;Code Snippet&lt;/button&gt; &lt;button class="btn btn-secondary clear"&gt;Effacer Tableau&lt;/button&gt; &lt;button class="btn btn-secondary load-example"&gt;Charger le JSON&lt;/button&gt; &lt;/div&gt; and in app.js i have this : events: { 'click #toolbar .add-question': 'addQuestion', 'click #toolbar .add-API': 'addAPI', 'click #toolbar .add-APIEX': 'addAPIEX', 'click #toolbar .add-answer': 'addAnswer', 'click #toolbar .send-json': 'sendJson', 'click #toolbar .preview-dialog': 'previewDialog', 'click #toolbar .code-snippet': 'showCodeSnippet', 'click #toolbar .load-example': 'loadExample', 'click #toolbar .clear': 'clear' }, </code></pre> <p>sendJson: function() {}</p> <p>I really would like to know is there is a way to communicate between these ?</p> <p>Thanks </p>
3
1,226
How to add significance of Tukey's test to ggplot2 figure with multiple facet?
<p>I generated a plot using a long format table, ggplot() and facet_wrap() functions in Rstudio. I want to add values of Tukey's tests applied to different levels of data and annotated with a system of stars (or letters) for significance.</p> <p>Here is the example code :</p> <pre><code># create a df for example a &lt;- paste0(&quot;Sample_&quot;, rep(1:100, 1)) b &lt;- c(rep(&quot;Dubai&quot;, 30), rep(&quot;London&quot;, 35), rep(&quot;Bucarest&quot;, 35)) c &lt;- c(rep(&quot;Sun&quot;, 16), rep(&quot;Rain&quot;, 16), rep(&quot;Cloud&quot;, 17), rep(&quot;Thunder&quot;, 16), rep(&quot;Star&quot;, 35)) d &lt;- runif(n = 100, min = 0.5, max = 50) e &lt;- runif(n = 100, min = 0.5, max = 50) f &lt;- runif(n = 100, min = 0.1, max = 3) df &lt;- data.frame(&quot;Sample&quot;= a, &quot;Location&quot;=b, &quot;Obs&quot;=c, &quot;Measure1&quot;=d, &quot;Measure2&quot;=e, &quot;Measure3&quot;=f) # convert df to long format long &lt;- reshape2::melt(df, id.vars = c(&quot;Sample&quot;, &quot;Location&quot;, &quot;Obs&quot;), measure.vars = c(&quot;Measure1&quot;, &quot;Measure2&quot;, &quot;Measure3&quot;)) # make a plot p &lt;- ggplot(long,aes(Location,value, color=Obs)) + facet_wrap(~ variable, drop=T, scale=&quot;free&quot;)+ geom_boxplot(outlier.colour = NA, alpha=0.8, position = position_dodge2(width=1, preserve=&quot;single&quot;))+ geom_point(size=1.2, aes(shape=Obs), position=position_dodge(width=0.7, preserve='total'))+ scale_shape_manual(&quot;Obs&quot;, values = c(16,17,17,16,16), labels = c(&quot;Sun&quot;, &quot;Rain&quot;, &quot;Cloud&quot;, &quot;Thunder&quot;, &quot;Star&quot;))+ scale_color_manual(&quot;Obs&quot;, values=c(&quot;#00BF7D&quot;, &quot;#5B6BF7&quot;, &quot;#00B0F6&quot;, &quot;#A3A500&quot;, &quot;#F8766D&quot;), labels = c(&quot;Sun&quot;, &quot;Rain&quot;, &quot;Cloud&quot;, &quot;Thunder&quot;, &quot;Star&quot;))+ labs(x=&quot;Location&quot;, y = &quot;Measure&quot;)+ theme(legend.text.align = 0) p </code></pre> <p>I get this : <a href="https://i.stack.imgur.com/k7sLA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k7sLA.png" alt="enter image description here" /></a></p> <p>And I would like this : <a href="https://i.stack.imgur.com/c9Auo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c9Auo.png" alt="enter image description here" /></a></p> <p>I tried with geom_signif() and stat_compare_means() functions but without success. Any idea please ?</p> <p>Thank you for your attention.</p>
3
1,449
React Router v6 Redirects
<p>thank you for taking the time to review this question in advance. I have experience with v5 but since changed pretty significantly in v6 I'm quite confused on how to setup a redirect within a nested page.</p> <p>For example my page structure is as follows:</p> <pre><code>- /auth - /client - dashboard - settings - profile - password </code></pre> <p>In my <code>/client</code> route i have a redirect set as follows (where <code>APP_URL = /client</code>:</p> <pre><code>&lt;Route path=&quot;/*&quot; element={&lt;Navigate to={`${APP_URL}/dashboard`} /&gt;} /&gt; </code></pre> <p>However, within my <code>/settings</code> route i would like to have it so that <code>/settings</code> redirects to <code>/settings/profile</code>. When setting a redirect within a nested route that also has a redirect it appears to cause an endless loop or redirect to the redirect set within the parent.</p> <p><strong>App.tsx</strong></p> <pre><code>function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;Router&gt; &lt;Routes&gt; &lt;Route path=&quot;*&quot; element={&lt;Views /&gt;}/&gt; &lt;/Routes&gt; &lt;/Router&gt; &lt;/div&gt; ); } </code></pre> <p><strong>Views</strong></p> <pre><code>export const Views = () =&gt; { return ( &lt;Routes&gt; &lt;Route path=&quot;*&quot; element={&lt;Navigate to={APP_URL} /&gt;} /&gt; &lt;Route path={`${APP_URL}/*`} element={&lt;AppLayout /&gt;} /&gt; &lt;/Routes&gt; ) } </code></pre> <p><strong>AppLayout</strong></p> <pre><code>export const AppLayout = () =&gt; { return ( &lt;Content&gt; &lt;AppViews /&gt; &lt;/Content&gt; ) } </code></pre> <p><strong>AppViews</strong></p> <pre><code>export const AppViews = () =&gt; { return ( &lt;Routes&gt; &lt;Route path=&quot;/*&quot; element={&lt;Navigate to={`${APP_URL}/dashboard`} /&gt;} /&gt; &lt;Route path={`/dashboard`} element={&lt;Dashboard /&gt;} /&gt; &lt;Route path={`/settings/*`} element={&lt;Settings /&gt;} /&gt; &lt;/Routes&gt; ) } </code></pre> <p><strong>Settings</strong></p> <pre><code>const Settings = () =&gt; { return ( &lt;&gt; &lt;Routes&gt; &lt;Route path=&quot;/*&quot; element={&lt;Navigate to={`${APP_URL}/settings/profile`} /&gt;} /&gt; &lt;Route path={`/profile`} element={&lt;Profile /&gt;} /&gt; &lt;Route path={`/password`} element={&lt;Password /&gt;} /&gt; &lt;/Routes&gt; &lt;/&gt; ) } </code></pre> <p>Does anyone have any experience with this?</p>
3
1,329
Integrate nodejs into existing docker lamp container
<p>I'm currently learning how to use docker. And i have a lamp stack container, including php7.4, apache, mariadb, phpmyadmin. All is working fine. I installed Laravel into this container. It includes all needed php extensions. (I'm aware of Laravel Sail, for docker learning purposes i prefer not to use Sail. I prefer to use my own container). One problem i'm facing now is i try to install Laravel Breeze and i need to use npm commands at some point. But i couldn't manage to install nodejs into my container and i can use some help.</p> <p>This is docker-compose.yml</p> <pre><code>version: &quot;3&quot; services: webserver: build: context: ./bin/${PHPVERSION} container_name: '${COMPOSE_PROJECT_NAME}-${PHPVERSION}' restart: 'always' ports: - &quot;${HOST_MACHINE_UNSECURE_HOST_PORT}:80&quot; - &quot;${HOST_MACHINE_SECURE_HOST_PORT}:443&quot; links: - database volumes: - ${DOCUMENT_ROOT-./www}:/var/www/html - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled - ${LOG_DIR-./logs/apache2}:/var/log/apache2 environment: PMA_PORT: ${HOST_MACHINE_PMA_PORT} database: build: context: &quot;./bin/${DATABASE}&quot; container_name: '${COMPOSE_PROJECT_NAME}-database' restart: 'always' ports: - &quot;127.0.0.1:${HOST_MACHINE_MYSQL_PORT}:3306&quot; volumes: - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: ${MYSQL_DATABASE} MYSQL_USER: ${MYSQL_USER} MYSQL_PASSWORD: ${MYSQL_PASSWORD} phpmyadmin: image: phpmyadmin/phpmyadmin container_name: '${COMPOSE_PROJECT_NAME}-phpmyadmin' links: - database environment: PMA_HOST: database PMA_PORT: 3306 PMA_USER: ${MYSQL_USER} PMA_PASSWORD: ${MYSQL_PASSWORD} MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_USER: ${MYSQL_USER} MYSQL_PASSWORD: ${MYSQL_PASSWORD} ports: - '${HOST_MACHINE_PMA_PORT}:80' volumes: - /sessions - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/conf.d/php-phpmyadmin.ini redis: container_name: '${COMPOSE_PROJECT_NAME}-redis' image: redis:latest ports: - &quot;127.0.0.1:${HOST_MACHINE_REDIS_PORT}:6379&quot; </code></pre> <p>I'm pulling some variables from .env file and others from several Dockerfiles.</p> <p>I want to integrate nodejs but not for serious nodejs programming. Only for some Laravel based situations like running 'npm install', 'npm run dev' etc. I won't be needing extra details. And i guess it should run on the same volume with the php image.</p>
3
1,222
Kendo UI Grid : Drag and Drop Hierarchy not working
<p>I want to drag and drop in different Grid with hierarchical data.</p> <p>The Drag and drop is working fine but the row is not dropping in Detail item in destination grid.</p> <p>I have created the sample here. <a href="https://jsfiddle.net/ravituvar/0xe9u4g6/" rel="nofollow noreferrer">here is the sample for the same..</a></p> <p>The following code shows how i built this, but getting some issues in the same. Please help me out what mistake i am doing in this?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function convert(array) { var map = {}; for (var i = 0; i &lt; array.length; i++) { var obj = array[i]; obj.items = []; map[obj.DemographicId] = obj; var parent = obj.ParentId || '-'; if (!map[parent]) { map[parent] = { items: [] }; } map[parent].items.push(obj); } return map['-'].items; } var arr = [{"Level":1,"DemographicId":13,"ParentId":null,"Name":"Bewitched General","Description":0.335336528},{"Level":2,"DemographicId":349,"ParentId":13,"Name":"Unacceptable Experience","Description":0.335336528},{"Level":1,"DemographicId":14,"ParentId":null,"Name":"Trained Trust","Description":29.17427794},{"Level":2,"DemographicId":329,"ParentId":14,"Name":"Concerned Rest","Description":0.335336528},{"Level":2,"DemographicId":331,"ParentId":14,"Name":"Tough Sleep","Description":2.012019168},{"Level":3,"DemographicId":346,"ParentId":331,"Name":"Icy Coffee","Description":0.335336528},{"Level":3,"DemographicId":347,"ParentId":331,"Name":"Big Fix","Description":0.335336528},{"Level":3,"DemographicId":348,"ParentId":331,"Name":"Total Worry","Description":0.335336528},{"Level":3,"DemographicId":431,"ParentId":331,"Name":"Fast Discipline","Description":0.335336528},{"Level":3,"DemographicId":586,"ParentId":331,"Name":"Intrepid Sister","Description":0.335336528},{"Level":2,"DemographicId":376,"ParentId":14,"Name":"Hasty Ordinary","Description":0.335336528},{"Level":2,"DemographicId":428,"ParentId":14,"Name":"Unnatural Native","Description":1.006009584},{"Level":3,"DemographicId":442,"ParentId":428,"Name":"Tan Celebration","Description":0.335336528},{"Level":3,"DemographicId":492,"ParentId":428,"Name":"Wise Repair","Description":0.335336528},{"Level":2,"DemographicId":443,"ParentId":14,"Name":"Frightening Historian","Description":3.018028753},{"Level":3,"DemographicId":328,"ParentId":443,"Name":"Improbable Stage","Description":0.335336528},{"Level":3,"DemographicId":517,"ParentId":443,"Name":"Heavenly Debt","Description":0.335336528},{"Level":3,"DemographicId":526,"ParentId":443,"Name":"That Art","Description":2.012019168},{"Level":4,"DemographicId":524,"ParentId":526,"Name":"Vivacious Competition","Description":0.670673056},{"Level":5,"DemographicId":445,"ParentId":524,"Name":"Dependable Potato","Description":0.335336528},{"Level":4,"DemographicId":525,"ParentId":526,"Name":"Watchful Tough","Description":1.006009584},{"Level":5,"DemographicId":432,"ParentId":525,"Name":"Lovable Sing","Description":0.670673056},{"Level":6,"DemographicId":435,"ParentId":432,"Name":"Vengeful Cigarette","Description":0.335336528},{"Level":2,"DemographicId":522,"ParentId":14,"Name":"Insistent Offer","Description":0.335336528},{"Level":2,"DemographicId":590,"ParentId":14,"Name":"Oddball Airline","Description":0.335336528},{"Level":2,"DemographicId":591,"ParentId":14,"Name":"Back Outcome","Description":20.79086474},{"Level":3,"DemographicId":330,"ParentId":591,"Name":"Mushy Active","Description":0.335336528},{"Level":3,"DemographicId":427,"ParentId":591,"Name":"Immaterial Safety","Description":1.341346112},{"Level":4,"DemographicId":437,"ParentId":427,"Name":"Same Restaurant","Description":0.335336528},{"Level":4,"DemographicId":438,"ParentId":427,"Name":"Imaginary Brother","Description":0.335336528},{"Level":4,"DemographicId":613,"ParentId":427,"Name":"Bubbly Hole","Description":0.335336528},{"Level":3,"DemographicId":433,"ParentId":591,"Name":"Several Weird","Description":2.682692225},{"Level":4,"DemographicId":426,"ParentId":433,"Name":"Deadly Potato","Description":0.335336528},{"Level":4,"DemographicId":436,"ParentId":433,"Name":"Ornery Race","Description":0.335336528},{"Level":4,"DemographicId":440,"ParentId":433,"Name":"Trusting Native","Description":0.335336528},{"Level":4,"DemographicId":441,"ParentId":433,"Name":"Flowery Tower","Description":0.335336528},{"Level":4,"DemographicId":479,"ParentId":433,"Name":"Downright Fall","Description":0.335336528},{"Level":4,"DemographicId":480,"ParentId":433,"Name":"Unique Career","Description":0.335336528},{"Level":4,"DemographicId":614,"ParentId":433,"Name":"Unknown Thomas","Description":0.335336528},{"Level":3,"DemographicId":592,"ParentId":591,"Name":"Judicious Analyst","Description":0.335336528},{"Level":3,"DemographicId":593,"ParentId":591,"Name":"Hard Major","Description":0.335336528},{"Level":3,"DemographicId":595,"ParentId":591,"Name":"Naughty Temporary","Description":0.335336528},{"Level":3,"DemographicId":596,"ParentId":591,"Name":"Crisp Commission","Description":0.335336528},{"Level":3,"DemographicId":597,"ParentId":591,"Name":"Valid Funny","Description":0.335336528},{"Level":3,"DemographicId":598,"ParentId":591,"Name":"Luminous Log","Description":0.335336528},{"Level":3,"DemographicId":599,"ParentId":591,"Name":"Sour Introduction","Description":0.335336528},{"Level":3,"DemographicId":600,"ParentId":591,"Name":"Elegant Player","Description":0.335336528},{"Level":3,"DemographicId":601,"ParentId":591,"Name":"Wilted Scheme","Description":1.006009584},{"Level":4,"DemographicId":444,"ParentId":601,"Name":"That Research","Description":0.335336528},{"Level":4,"DemographicId":609,"ParentId":601,"Name":"Overcooked Message","Description":0.335336528},{"Level":3,"DemographicId":602,"ParentId":591,"Name":"Good-natured Responsibility","Description":3.688701809},{"Level":4,"DemographicId":478,"ParentId":602,"Name":"Cumbersome Battle","Description":0.335336528},{"Level":4,"DemographicId":515,"ParentId":602,"Name":"Unsightly Contest","Description":2.682692225},{"Level":5,"DemographicId":439,"ParentId":515,"Name":"Mushy Explanation","Description":0.335336528},{"Level":5,"DemographicId":508,"ParentId":515,"Name":"Obvious Pride","Description":0.670673056},{"Level":6,"DemographicId":509,"ParentId":508,"Name":"Negligible Ask","Description":0.335336528},{"Level":5,"DemographicId":514,"ParentId":515,"Name":"Concerned Classic","Description":1.341346112},{"Level":6,"DemographicId":510,"ParentId":514,"Name":"Greedy Double","Description":0.335336528},{"Level":6,"DemographicId":511,"ParentId":514,"Name":"Reflecting Poem","Description":0.335336528},{"Level":6,"DemographicId":512,"ParentId":514,"Name":"Every Finish","Description":0.335336528},{"Level":4,"DemographicId":610,"ParentId":602,"Name":"Zigzag Meet","Description":0.335336528},{"Level":3,"DemographicId":603,"ParentId":591,"Name":"Esteemed Satisfaction","Description":0.335336528},{"Level":3,"DemographicId":604,"ParentId":591,"Name":"Normal Trouble","Description":1.341346112},{"Level":4,"DemographicId":485,"ParentId":604,"Name":"Hot Fish","Description":0.335336528},{"Level":4,"DemographicId":611,"ParentId":604,"Name":"Eager Perception","Description":0.335336528},{"Level":4,"DemographicId":612,"ParentId":604,"Name":"Shocking Aside","Description":0.335336528},{"Level":3,"DemographicId":605,"ParentId":591,"Name":"Terrific King","Description":0.335336528},{"Level":3,"DemographicId":606,"ParentId":591,"Name":"Humiliating Suit","Description":0.335336528},{"Level":3,"DemographicId":607,"ParentId":591,"Name":"Serious Smile","Description":0.335336528},{"Level":3,"DemographicId":608,"ParentId":591,"Name":"Memorable Ship","Description":3.353365281},{"Level":4,"DemographicId":430,"ParentId":608,"Name":"Wan Science","Description":0.335336528},{"Level":4,"DemographicId":434,"ParentId":608,"Name":"Hard Rule","Description":0.335336528},{"Level":4,"DemographicId":473,"ParentId":608,"Name":"Marvelous Radio","Description":0.335336528},{"Level":4,"DemographicId":477,"ParentId":608,"Name":"Visible Personality","Description":0.335336528},{"Level":4,"DemographicId":481,"ParentId":608,"Name":"Scrawny Shine","Description":0.335336528},{"Level":4,"DemographicId":507,"ParentId":608,"Name":"Descriptive Pride","Description":0.335336528},{"Level":4,"DemographicId":516,"ParentId":608,"Name":"Pleased Private","Description":0.335336528},{"Level":4,"DemographicId":548,"ParentId":608,"Name":"Frizzy District","Description":0.335336528},{"Level":4,"DemographicId":615,"ParentId":608,"Name":"Juicy Organization","Description":0.335336528},{"Level":3,"DemographicId":616,"ParentId":591,"Name":"Sweaty Equal","Description":0.335336528},{"Level":3,"DemographicId":621,"ParentId":591,"Name":"Sweltering Cigarette","Description":0.335336528},{"Level":3,"DemographicId":623,"ParentId":591,"Name":"Buoyant Rule","Description":0.335336528},{"Level":3,"DemographicId":625,"ParentId":591,"Name":"Whimsical Remote","Description":0.335336528},{"Level":3,"DemographicId":633,"ParentId":591,"Name":"Notable Feed","Description":0.335336528},{"Level":3,"DemographicId":635,"ParentId":591,"Name":"Puzzled Pin","Description":1.006009584},{"Level":4,"DemographicId":594,"ParentId":635,"Name":"Plump Member","Description":0.335336528},{"Level":4,"DemographicId":636,"ParentId":635,"Name":"Colorless Service","Description":0.335336528},{"Level":2,"DemographicId":618,"ParentId":14,"Name":"Extroverted Excuse","Description":0.335336528},{"Level":2,"DemographicId":622,"ParentId":14,"Name":"Definite Sector","Description":0.335336528},{"Level":2,"DemographicId":631,"ParentId":14,"Name":"Dear Blue","Description":0.335336528},{"Level":1,"DemographicId":15,"ParentId":null,"Name":"Weird Rush","Description":3.688701809},{"Level":2,"DemographicId":461,"ParentId":15,"Name":"Vigilant Mine","Description":0.335336528},{"Level":2,"DemographicId":527,"ParentId":15,"Name":"Darling Cousin","Description":2.682692225},{"Level":3,"DemographicId":504,"ParentId":527,"Name":"Courteous Knife","Description":0.335336528},{"Level":3,"DemographicId":528,"ParentId":527,"Name":"Constant Window","Description":2.012019168},{"Level":4,"DemographicId":6,"ParentId":528,"Name":"Serene Personal","Description":0.335336528},{"Level":4,"DemographicId":518,"ParentId":528,"Name":"Cooperative Marketing","Description":0.335336528},{"Level":4,"DemographicId":530,"ParentId":528,"Name":"Likely Car","Description":0.335336528},{"Level":4,"DemographicId":531,"ParentId":528,"Name":"Worst Lip","Description":0.335336528},{"Level":4,"DemographicId":550,"ParentId":528,"Name":"Quintessential Evening","Description":0.335336528},{"Level":2,"DemographicId":529,"ParentId":15,"Name":"Knowing Debt","Description":0.335336528},{"Level":2,"DemographicId":587,"ParentId":15,"Name":"Harmless Weight","Description":0.335336528},{"Level":1,"DemographicId":16,"ParentId":null,"Name":"Tidy Mouse","Description":2.012019168},{"Level":2,"DemographicId":5,"ParentId":16,"Name":"Useless Chemistry","Description":0.335336528},{"Level":2,"DemographicId":254,"ParentId":16,"Name":"Several Expert","Description":0.335336528},{"Level":2,"DemographicId":486,"ParentId":16,"Name":"Young String","Description":0.335336528},{"Level":2,"DemographicId":519,"ParentId":16,"Name":"Ideal Army","Description":1.006009584},{"Level":3,"DemographicId":520,"ParentId":519,"Name":"Tart Text","Description":0.335336528},{"Level":3,"DemographicId":521,"ParentId":519,"Name":"Tiny Church","Description":0.335336528}] var myData = convert(arr) var dataSource1 = new kendo.data.DataSource({ data: myData }); $(document).ready(function () { var originalGrid = $("#originalGrid").kendoGrid({ dataSource: dataSource1, sortable: false, pageable: false, detailInit: detailInit1, dataBound: function () { //this.expandRow(this.tbody.find("tr.k-master-row").last()); }, columns: [ { field: "Name", title: "Name", width: "80px" }, { field: "Description", title: "Amount", width: "30px", aggregates: ["sum"], groupFooterTemplate: "Sum: #= sum # " } ] }); }); function detailInit1(e) { $("&lt;div/&gt;").appendTo(e.detailCell).kendoGrid({ dataSource: { data: e.data.items //data is the current position item, items is its child items }, scrollable: false, sortable: false, pageable: false, detailInit: detailInit1, columns: [ { field: "Name", title: "Name", width: "80px" }, { field: "Description", title: "Amount", width: "30px", aggregates: ["sum"], groupFooterTemplate: "Sum: #= sum # " } ] }); } $(document).ready(function () { var dataSource2 = new kendo.data.DataSource({ data: [] }); var grid2 = $("#grid2").kendoGrid({ dataSource: dataSource2, width: 400, sortable: false, pageable: false, detailInit: detailInit11, schema: { model: { id: "DemographicId" } }, columns: [ { field: "Name", title: "Name", width: "40px" }, { field: "Description", title: "Amount", width: "110px", aggregates: ["sum"], groupFooterTemplate: "Sum: #= sum # " } ] }); function detailInit11(e) { $("&lt;div/&gt;").appendTo(e.detailCell).kendoGrid({ dataSource: { data: e.data.items }, scrollable: false, sortable: false, pageable: false, detailInit: detailInit11, columns: [ { field: "Name", title: "Name", width: "110px" }, { field: "Description", title: "Amount", width: "110px", aggregates: ["sum"], groupFooterTemplate: "Sum: #= sum # " } ] }); } $(originalGrid).kendoDraggable({ filter: "tr", hint: function (e) { var item = $('&lt;div class="k-grid k-widget" style="background-color: DarkOrange; color: black;"&gt;&lt;table&gt;&lt;tbody&gt;&lt;tr&gt;' + e.html() + '&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;'); return item; }, group: "gridGroup1", }); var currentDataItem = null; function getItemByUid(uid, currentUid, data) { for (let index = 0; index &lt; data.length; index++) { const element = data[index]; if (element.uid == currentUid) { currentDataItem = element; return false; } else { if (element.items) { getItemByUid(element.uid, currentUid, element.items); } } } } grid2.kendoDropTarget({ drop: function (e) { var uid = e.draggable.currentTarget.data("uid"); var dataItem = getItemByUid(uid, uid, dataSource1.data()); dataSource2.add(currentDataItem); }, group: "gridGroup1", }); }); </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Kendo UI Snippet&lt;/title&gt; &lt;link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css"/&gt; &lt;link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css"/&gt; &lt;link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.silver.min.css"/&gt; &lt;link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css"/&gt; &lt;script src="https://code.jquery.com/jquery-1.12.4.min.js"&gt;&lt;/script&gt; &lt;script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;div style="width:50%;float:left" class="dragGrid"&gt; &lt;div id="originalGrid"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div style="width:50%;float:right" &gt; &lt;div id="grid2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
6,854
custom template with v-if is giving error while using inside li item - vue js
<p>I have to display menus in navigation bar. There are multiple menu items(Home, About etc). Some menu items are having submenus(2nd -3rd level). So, i created one directive to show up submenus while hovering over the menu in navigation bar.</p> <p><strong>Here is my code(old code)</strong> - v-show-sub-menu is the directive</p> <pre><code>&lt;ul class=&quot;main__menus&quot;&gt; &lt;li v-show-sub-menu v-if=&quot;m.displayMenu==='Y'&quot; v-for=&quot;(m, idx) in Menus&quot; class=&quot;main__menu&quot; :key=&quot;idx&quot; :class=&quot;{'main__menu--selected':chkMenu(m)}&quot; @click=&quot;screen.moveMenu(m)&quot;&gt; &lt;div class=&quot;main__menu-name&quot;&gt;{{getMenuName(m)}}&lt;/div&gt; &lt;ul class=&quot;main__menu__second&quot; v-show=&quot;!hideSubMenu&quot; :class=&quot;secondMenuClasses(m)&quot; @click.stop&gt; // 2nd - 3rd level menu &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>It is working fine but as per vue standard i refactored code and remove the v-if from v-for in same li tag. I used custom template syntax to check the menu will be displayed in Navigation bar or not like this below.</p> <pre><code>&lt;ul class=&quot;main__menus&quot;&gt; &lt;li v-for=&quot;(m, idx) in Menus&quot; :key=&quot;idx&quot; v-show-menu class=&quot;main__menu&quot; :class=&quot;{'main__menu--selected':chkMenu(m)}&quot; @click=&quot;screen.moveMenu(m)&quot; &gt; &lt;template v-if=&quot;m.displayMenu ==='Y'&quot;&gt; &lt;div class=&quot;main__menu-name&quot;&gt; {{ getMenuName(m) }} &lt;/div&gt; &lt;ul v-show=&quot;!hideSubMenu&quot; class=&quot;main__menu__second&quot; :class=&quot;secondMenuClasses(m)&quot; @click.stop&gt; // 2nd - 3rd level children &lt;/ul&gt; &lt;/template&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Directive</p> <pre><code>showSubMenu: { // It is showing sub menus while hovering over menus in navigation bar inserted(el) { const menu = el.querySelector('.main__menu__second'); el.addEventListener('mouseenter', () =&gt; { const { left, height } = el.getBoundingClientRect(); if (document.querySelector('#menu-area')) { document.querySelector('#menu-area').appendChild(menu); } menu.style.display = 'block'; menu.style.top = `${height}px`; menu.style.left = `${left}px`; }); menu.addEventListener('mouseenter', () =&gt; { const { left, height } = el.getBoundingClientRect(); menu.style.display = 'block'; menu.style.top = `${height}px`; menu.style.left = `${left}px`; }); el.addEventListener('mouseleave', () =&gt; { menu.style.display = 'none'; }); menu.addEventListener('mouseleave', () =&gt; { menu.style.display = 'none'; }); } } </code></pre> <p>But, It is breaking some where and directive is giving null error and there are css issues also visible. I am using computed property to solve this issue.</p> <p><strong>How to fix this problem and why it is behaving strange ?</strong></p>
3
1,834
I need to make these clouds extend to the left and right and go on forever. (Hard to explain so images are provided with further detail)
<p>So I am trying to make a cloud generation script that when going forward, left, or right it generates clouds infinitely.</p> <p>Here is an example of how it currently is, I would like it to generate clouds when moving left or right infinitely but currently it only generates clouds moving forwards infinitely. Arrows are provided in the example for better understanding. I apologize for not adding a image directly but I am unable to as I am a new user:</p> <p><a href="https://i.stack.imgur.com/4XzpZ.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/4XzpZ.jpg</a></p> <p>I would like to modify my script to make the clouds generate forward, left, and right.</p> <p>Here is my script:</p> <p><a href="https://pastebin.com/raw/vkTVrybQ" rel="nofollow noreferrer">https://pastebin.com/raw/vkTVrybQ</a></p> <pre><code>// HTML: &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot; &gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt; &lt;title&gt;cloud generation&lt;/title&gt; &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt; &lt;script src=&quot;js/ThreeWebGL.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;js/ThreeExtras.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script id=&quot;vs&quot; type=&quot;x-shader/x-vertex&quot;&gt; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } &lt;/script&gt; &lt;script id=&quot;fs&quot; type=&quot;x-shader/x-fragment&quot;&gt; uniform sampler2D map; uniform vec3 fogColor; uniform float fogNear; uniform float fogFar; varying vec2 vUv; void main() { float depth = gl_FragCoord.z / gl_FragCoord.w; float fogFactor = smoothstep( fogNear, fogFar, depth ); gl_FragColor = texture2D( map, vUv ); gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 ); gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor ); } &lt;/script&gt; &lt;div class=&quot;container&quot;&gt; &lt;canvas id=&quot;panel&quot; width=&quot;10&quot; height=&quot;1&quot;&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; // CSS: *{ margin:0; padding:0; } body { color:#fff; font:14px/1.3 Arial,sans-serif; background-image: url(../images/sky.jpg); } .container { height:1px; } // Javascript: // inner variables var canvas, ctx; var camera, scene, renderer, meshMaterial, mesh, geometry, i, f; var mouseX = 0, mouseY = 0; var startTime = new Date().getTime(); var windowHalfX = window.innerWidth / 2; var windowHalfY = window.innerHeight / 2; if (window.attachEvent) { window.attachEvent('onload', main_init); } else { if(window.onload) { var curronload = window.onload; var newonload = function() { curronload(); main_init(); }; window.onload = newonload; } else { window.onload = main_init; } } function main_init() { // creating canvas and context objects canvas = document.getElementById('panel'); var ctx = canvas.getContext('2d'); // preparing camera camera = new THREE.Camera(30, window.innerWidth / window.innerHeight, 1, 5000); camera.position.z = 6000; // preparing scene scene = new THREE.Scene(); // preparing geometry geometry = new THREE.Geometry(); // loading texture var texture = THREE.ImageUtils.loadTexture('../images/clouds.png'); texture.magFilter = THREE.LinearMipMapLinearFilter; texture.minFilter = THREE.LinearMipMapLinearFilter; // preparing fog var fog = new THREE.Fog(0x251d32, - 100, 5000); // preparing material meshMaterial = new THREE.MeshShaderMaterial({ uniforms: { 'map': {type: 't', value:2, texture: texture}, 'fogColor' : {type: 'c', value: fog.color}, 'fogNear' : {type: 'f', value: fog.near}, 'fogFar' : {type: 'f', value: fog.far}, }, vertexShader: document.getElementById('vs').textContent, fragmentShader: document.getElementById('fs').textContent, depthTest: false }); // preparing planeMesh var planeMesh = new THREE.Mesh(new THREE.PlaneGeometry(64, 64)); for (i = 0; i &lt; 10000; i++) { planeMesh.position.x = Math.random() * 1000 - 500; planeMesh.position.y = - Math.random() * Math.random() * 200 - 15; planeMesh.position.z = i; planeMesh.rotation.z = Math.random() * Math.PI; planeMesh.scale.x = planeMesh.scale.y = Math.random() * Math.random() * 1.5 + 0.5; THREE.GeometryUtils.merge(geometry, planeMesh); } mesh = new THREE.Mesh(geometry, meshMaterial); scene.addObject(mesh); mesh = new THREE.Mesh(geometry, meshMaterial); mesh.position.z = - 10000; scene.addObject(mesh); // preparing new renderer and drawing it renderer = new THREE.WebGLRenderer({ antialias: false }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // change positions by mouse document.addEventListener('mousemove', onMousemove, false); // change canvas size on resize window.addEventListener('resize', onResize, false); setInterval(drawScene, 30); // loop drawScene } function onMousemove(event) { mouseX = (event.clientX - windowHalfX) * 0.3; mouseY = (event.clientY - windowHalfY) * 0.2; } function onResize(event) { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function drawScene() { position = ((new Date().getTime() - startTime) * 0.1) % 10000; camera.position.x += mouseX * 0.01; camera.position.y += - mouseY * 0.01; camera.position.z = - position + 10000; renderer.render(scene, camera); } // ^ Please note I also use ThreeWebGL.js and ThreeExtras.js but these scripts are too large to paste here as they are APIS </code></pre>
3
2,738
Why are HTML links not loading until audio file has been played
<p>I am coding a website that has a navigation bar at the top of the page, containing normal, generic HTML5 link elements (using the &quot;a&quot; element):</p> <pre><code>&lt;table id=&quot;menuButtonTable&quot;&gt; &lt;tr&gt; &lt;td&gt; &lt;a href=&quot;/home&quot; class=&quot;menuButton&quot;&gt; Home &lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;a href=&quot;/play&quot; class=&quot;menuButton&quot;&gt; Play &lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;a href=&quot;/help&quot; class=&quot;menuButton&quot;&gt; Help &lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;a href=&quot;/contacts&quot; class=&quot;menuButton&quot;&gt; Contacts &lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I also am loading multiple audio files in javascript:</p> <pre><code>const masterVolume = 0.4; const breakingSound = new Audio(&quot;Sound-Effects/breaking.mp3&quot;); breakingSound.volume = masterVolume; const buildingSound = new Audio(&quot;Sound-Effects/building.mp3&quot;); buildingSound.volume = masterVolume; const choppingSound = new Audio(&quot;Sound-Effects/chopping.mp3&quot;); choppingSound.volume = masterVolume; const diggingSound = new Audio(&quot;Sound-Effects/digging.mp3&quot;); diggingSound.volume = masterVolume; const diggingSong = new Audio(&quot;Sound-Effects/digging-song.mp3&quot;); diggingSong.volume = masterVolume; const drinkingSound = new Audio(&quot;Sound-Effects/drinking.mp3&quot;); drinkingSound.volume = masterVolume; const eatingSound = new Audio(&quot;Sound-Effects/eating.mp3&quot;); eatingSound.volume = masterVolume; const footstepSound1 = new Audio(&quot;Sound-Effects/footstep-1.mp3&quot;); footstepSound1.volume = masterVolume; const footstepSound2 = new Audio(&quot;Sound-Effects/footstep-2.mp3&quot;); footstepSound2.volume = masterVolume; const jazzSong = new Audio(&quot;Sound-Effects/jazz-song.mp3&quot;); jazzSong.volume = masterVolume; const leavesSound = new Audio(&quot;Sound-Effects/leaves.mp3&quot;); leavesSound.volume = masterVolume; const themeSong = new Audio(&quot;Sound-Effects/oxygen-theme-song.mp3&quot;); themeSong.volume = masterVolume; const themeSong2 = new Audio(&quot;Sound-Effects/oxygen-theme-song-2.mp3&quot;); themeSong2.volume = masterVolume; const rainSong = new Audio(&quot;Sound-Effects/rain-song.mp3&quot;); rainSong.volume = masterVolume; const rainSound = new Audio(&quot;Sound-Effects/rain.mp3&quot;); rainSound.volume = masterVolume; const waterSound = new Audio(&quot;Sound-Effects/water.mp3&quot;); waterSound.volume = masterVolume; const windSound = new Audio(&quot;Sound-Effects/wind.mp3&quot;); windSound.volume = masterVolume; </code></pre> <p>For some reason, whenever I click on one of the links at the top of the page, they never load and I am just left with the swirling circle, showing that the page is trying to load, at the top left. However, the links do load after the audio 'windSound' has been played. I have absolutely no clue why this is happening, does anyone know how to fix this strange problem?</p> <p>Thanks</p> <ul> <li>primecubed</li> </ul>
3
1,297
Changing the language of the formatted_address called by google Places API autocomplete method
<p>The data that i have received using google Places API is giving me formatted_address field in my local language. I want it to be in English.</p> <p>I have enabled google Places Api and used autocomplete method to load suggestions. A simple html page to load the received data is created. I have tried setting the language option to "en" in script tag. </p> <p>HTML: </p> <pre><code>&lt;div id="info-table"&gt; Name: &lt;span id="place_name"&gt;&lt;/span&gt;&lt;br&gt; Place id: &lt;span id="place_id"&gt;&lt;/span&gt;&lt;br&gt; Address :&lt;span id="place_address"&gt;&lt;/span&gt;&lt;br&gt; Phone : &lt;span id="phone_no"&gt;&lt;/span&gt;&lt;br&gt; Openhours: &lt;span id="open_time"&gt;&lt;/span&gt;&lt;br&gt; Open Now : &lt;span id="open_now"&gt;&lt;/span&gt;&lt;br&gt; website : &lt;span id="website"&gt;&lt;/span&gt;&lt;br&gt; photo :&lt;br&gt; &lt;img id="photo" src="" style="display:none;" /&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt; &lt;span id="all-data"&gt;&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;!-- Replace the value of the key parameter with your own API key. --&gt; &lt;script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&amp;libraries=places&amp;callback=initMap&amp;language=en&amp;region=US"&gt; &lt;/script&gt; </code></pre> <p>JS:</p> <pre><code>function initMap() { var input = document.getElementById('pac-input'); var options = { language:'en', types: ['establishment'] }; var autocomplete = new google.maps.places.Autocomplete(input, options); autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address', 'formatted_phone_number', 'opening_hours', 'website', 'photos']); autocomplete.addListener('place_changed', placechange); function placechange() { var place = autocomplete.getPlace(); var photos = place.photos; $('#all-data').text(JSON.stringify(place)); $('#place_name').text(place.name); $('#place_id').text(place.place_id); $('#place_address').text(place.formatted_address); $('#phone_no').text(place.formatted_phone_number); $('#open_time').text(place.opening_hours.weekday_text[0]); $('#open_now').text(place.opening_hours.open_now); $('#photo').attr("src",photos[0].getUrl()); $('#photo').attr("style","width:50%;"); $('#website').text(place.website); } } </code></pre> <p>Current formatted_address:2nd Floor, 320 ටී බී ජයා මාවත, කොළඹ 01000<br> Expected formatted_address: 2nd Floor , 320 ,T.B.Jaya Avenue,Colombo 01000.</p> <p>The current response I'm getting:</p> <pre><code>{"formatted_address":"2nd Floor, 320 ටී බී ජයා මාවත, කොළඹ 01000, Sri Lanka","formatted_phone_number":"0112 683 751","geometry":{"location":{"lat":6.923615999999999,"lng":79.86028599999997},"viewport":{"south":6.922419719708497,"west":79.8594205697085,"north":6.925117680291502,"east":79.86211853029158}},"name":"hSenid Mobile Solutions","opening_hours":{"open_now":true,"periods":[{"close":{"day":1,"time":"1730","hours":17,"minutes":30},"open":{"day":1,"time":"0830","hours":8,"minutes":30}},{"close":{"day":2,"time":"1730","hours":17,"minutes":30},"open":{"day":2,"time":"0830","hours":8,"minutes":30}},{"close":{"day":3,"time":"1730","hours":17,"minutes":30},"open":{"day":3,"time":"0830","hours":8,"minutes":30}},{"close":{"day":4,"time":"1730","hours":17,"minutes":30},"open":{"day":4,"time":"0830","hours":8,"minutes":30}},{"close":{"day":5,"time":"1730","hours":17,"minutes":30},"open":{"day":5,"time":"0830","hours":8,"minutes":30}}],"weekday_text":["Monday: 8:30 AM – 5:30 PM","Tuesday: 8:30 AM – 5:30 PM","Wednesday: 8:30 AM – 5:30 PM","Thursday: 8:30 AM – 5:30 PM","Friday: 8:30 AM – 5:30 PM","Saturday: Closed","Sunday: Closed"]},"photos":[{"height":2176,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/100291523214478364695/photos\"&gt;Malinda Prasad&lt;/a&gt;"],"width":4608},{"height":4032,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/105380056766383259301/photos\"&gt;Sasindu Jayashma&lt;/a&gt;"],"width":2268},{"height":2184,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/116851599999613156839/photos\"&gt;Dinesha Karunathilake&lt;/a&gt;"],"width":4608},{"height":2448,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/100485539031416489634/photos\"&gt;Milinda Arambawela&lt;/a&gt;"],"width":3264},{"height":4032,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/105380056766383259301/photos\"&gt;Sasindu Jayashma&lt;/a&gt;"],"width":3024},{"height":960,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/114606659795691325467/photos\"&gt;hSenid Mobile Solutions&lt;/a&gt;"],"width":960},{"height":4032,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/105380056766383259301/photos\"&gt;Sasindu Jayashma&lt;/a&gt;"],"width":2268},{"height":300,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/114606659795691325467/photos\"&gt;hSenid Mobile Solutions&lt;/a&gt;"],"width":300},{"height":720,"html_attributions":["&lt;a href=\"https://maps.google.com/maps/contrib/114606659795691325467/photos\"&gt;hSenid Mobile Solutions&lt;/a&gt;"],"width":960}],"place_id":"ChIJO814yhNZ4joRzunigaOMo6A","website":"https://www.hsenidmobile.com/","html_attributions":[]} </code></pre>
3
2,180
Large array, stack overflow, and dynamically allocated
<p>I am wondering how could I create and initiate this large array without resorting to vector. Basically, I have been trying to create a large 1D array whose each element is a cell of a cubic with side L=NGRID cells. NGRID is read from a parameter file. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sstream&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;memory&gt; #define pow3(x) ((x)*(x)*(x)) #define at(ix,iy,iz) ((ix*NGRID*NGRID) + (iy*NGRID) + (iz)) std::string output_file="halo_snapshot_z0.txt"; // name of the output file std::ofstream myoutput; double SBOX; // size of the box int NGRID; // number of grid cells int main(int argc, char *argv[]) { std::ostringstream input_file; std::ostringstream para_file; input_file &lt;&lt; argv[1]; para_file &lt;&lt; argv[2]; std::string input_file_string = input_file.str(); std::string para_file_string = para_file.str(); FILE* pfile = std::fopen(para_file_string.c_str(),"r"); if (!pfile) { std::cout &lt;&lt; "Parameter file not found!" &lt;&lt; std::endl; } std::fscanf (pfile, "%lf", &amp;SBOX); std::cout &lt;&lt; SBOX &lt;&lt; std::endl; std::fscanf (pfile, "%d", &amp;NGRID); std::cout &lt;&lt; NGRID &lt;&lt; std::endl; double SGRID = SBOX/NGRID; // Initiate the halo density array int* densh; densh = (int*) malloc(pow3(NGRID) * sizeof(int)); std::uninitialized_fill_n(densh, pow3(NGRID), 0); // Read the halo catalogue std::ifstream ifs(input_file_string.c_str(),std::ifstream::in); // in C++, the string variable &lt;filename&gt; cannot be used as a parameter, instead one must use filename.c_str() std::string iline; while(std::getline(ifs, iline)) // Read one entire line from ifs { std::istringstream iss(iline); // Access the line as a stream // Take in only the first six columns long int id; long int host; int sub_no; double mass; int part_no; double x; // x coordinate in kpc double y; // y coordinate in kpc double z; // z coordinate in kpc double vx; double vy; double vz; double rvir; double rmax; float dummy1; float dummy2; float dummy3; float dummy4; float dummy5; float dummy6; float dummy7; float dummy8; float dummy9; float dummy10; float dummy11; float dummy12; float dummy13; float dummy14; float dummy15; float dummy16; float dummy17; float dummy18; float dummy19; float dummy20; float dummy21; float dummy22; float dummy23; int dummy24; float dummy25; float dummy26; float dummy27; float dummy28; float dummy29; float dummy30; iss &gt;&gt; id &gt;&gt; host &gt;&gt; sub_no &gt;&gt; mass &gt;&gt; part_no &gt;&gt; x &gt;&gt; y &gt;&gt; z &gt;&gt; vx &gt;&gt; vy &gt;&gt; vz &gt;&gt; rvir &gt;&gt; rmax &gt;&gt; dummy1 &gt;&gt; dummy2 &gt;&gt; dummy3 &gt;&gt; dummy4 &gt;&gt; dummy5 &gt;&gt; dummy6 &gt;&gt; dummy7 &gt;&gt; dummy8 &gt;&gt; dummy9 &gt;&gt; dummy10 &gt;&gt; dummy11 &gt;&gt; dummy12 &gt;&gt; dummy13 &gt;&gt; dummy14 &gt;&gt; dummy15 &gt;&gt; dummy16 &gt;&gt; dummy17 &gt;&gt; dummy18 &gt;&gt; dummy19 &gt;&gt; dummy20 &gt;&gt; dummy21 &gt;&gt; dummy22 &gt;&gt; dummy23 &gt;&gt; dummy24 &gt;&gt; dummy25 &gt;&gt; dummy26 &gt;&gt; dummy27 &gt;&gt; dummy28 &gt;&gt; dummy29 &gt;&gt; dummy30 ; // read the entire line // Select only host halos and assign them onto the grid if (host==0) { //NGP mass assignment float gx = x/SGRID-1.; float gy = y/SGRID-1.; float gz = z/SGRID-1.; int ix = (int)(gx+0.5); int iy = (int)(gy+0.5); int iz = (int)(gz+0.5); densh[at(ix,iy,iz)] += 1; } } myoutput.open (output_file.c_str(),std::ofstream::out); for (int i=0;i&lt;pow3(NGRID);++i) { myoutput &lt;&lt; densh[i] &lt;&lt; '\n'; } myoutput.close(); myoutput.clear(); return 0; } </code></pre> <p>This gives me segmentation fault when I try to work with NGRID=250. Thank you very much!</p> <p><strong>EDIT:</strong> edited to include the full code, sorry if it looks messy, thanks for your time!</p>
3
2,155
Webpack + eslint replace source change on linting
<p>Running on webpack dev server with a string replacement plugin that does a replacement based <a href="https://github.com/jamesandersen/string-replace-webpack-plugin/blob/master/loader.js#L19" rel="nofollow">on a function</a>. I am finding the value of the replacement overwritten my source file .</p> <p>My Dev server configuration is this:</p> <pre><code>const devServer = (options) =&gt; { return { devServer: { hot: true, inline: true, stats: 'errors-only', host: options.host, port: options.port, historyApiFallback: true }, plugins: [ new webpack.HotModuleReplacementPlugin({ multiStep: true }) ] } } </code></pre> <p>The string replacement plugin configuration is:</p> <pre><code> const constants = (data) =&gt; { return { module: { loaders: [ { test: /\.jsx?$/, loader: StringReplacePlugin.replace({ replacements:[ { pattern:/\`CONSTANT_(.*)\`/g, replacement:(match,p1,offset,string)=&gt;{ console.log('MATCH '+p1) const keys = p1.split('.') let current = data keys.forEach((key)=&gt;{ current = current[key] }) console.log('Replacing '+p1+' with '+current) return `'${current}'` } } ] }) } ] }, plugins: [ new StringReplacePlugin() ] } } </code></pre> <p>The entry/ouptut values are:</p> <pre><code>const base = { entry: { app: path.resolve(PATHS.app, './index.jsx') }, output: { path: PATHS.build, filename: 'app.js', publicPath: '/' }, resolve: { extensions: ['', '.js', '.jsx', '.json'] } } </code></pre> <p>Is there any reason why webpack dev server would be changing files on source?</p> <p><strong>EDIT: 1</strong> Added JS part:</p> <pre><code>const js = (paths) =&gt; { const cacheDir = (process.env.CACHE_DIRECTORY ? process.env.CACHE_DIRECTORY : 'true') return { module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loaders: [ `babel?cacheDirectory=${cacheDir}`, // presets on .babelrc 'eslint-loader?fix' ], include: paths } ] } } } </code></pre> <p><strong>Edit 2</strong> The cause seesm to be the eslint-loader?fix, when removed the appropriate behaviour is achieved. Now I am seeking how to prevent that</p>
3
1,325
C# Customising MailAddress.From field not working
<p>I am trying to send Emails from my custom address to users using C# and googles smtp service. My problem is that when the when the user receives the message it is displayed <code>admin@customDomain.co.uk &lt;myAddress@gmail.com&gt;</code> in the from section of the email.</p> <p>My problem is that I want the user to see <code>admin@customDomain.co.uk &lt;admin@customDomain.co.uk&gt;</code>. Is this possible using the google service? Or should I look at some other option? If so what?</p> <p>I have tried the answers on <a href="https://stackoverflow.com/questions/2737699/sending-emails-in-asp-net-with-specific-name-instead-of-sender-email">this</a> thread but non worked and I also found this <a href="https://gmail.googleblog.com/2009/07/send-mail-from-another-address-without.html" rel="nofollow noreferrer">google blog post</a> but I cant work out how it can solve my issue</p> <p><strong>My Code</strong></p> <pre><code> string SmtpAddress = "smtp.gmail.com"; int MyPort = 587; bool enableSSL = true; string MyPassword = "somePassword"; string MyUsername = "aUsername"; public string EmailFrom = "admin@customDomain.co.uk"; public string Subject = "Test Subject"; public void Send(string body, BL.Customer customer) { using (MailMessage message = new MailMessage()) { message.To.Add(new MailAddress(customer.EmailAddress)); if (!String.IsNullOrEmpty(customer.SCEmailAddress)) { //message.To.Add(new MailAddress(customer.SCEmailAddress)); } message.From = new MailAddress(EmailFrom, EmailFrom); message.Subject = Subject; message.Body = string.Format(body); message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = MyUsername, Password = MyPassword }; smtp.Credentials = credential; smtp.Host = SmtpAddress; smtp.Port = MyPort; smtp.EnableSsl = enableSSL; try { smtp.Send(message); } catch (SmtpException se) { throw se; } } } } </code></pre>
3
1,088
CodeIgniter News Tutorial - Parse Error
<p>I'm following the CodeIgniter tutorial (<a href="http://www.codeigniter.com/user_guide/tutorial/news_section.html" rel="nofollow">http://www.codeigniter.com/user_guide/tutorial/news_section.html</a>), when I get to '<a href="http://www.codeigniter.com/user_guide/tutorial/news_section.html#display-the-news" rel="nofollow">Display the news</a>' it isn't made clear where to add the second code block:</p> <pre><code>public function index() { $data['news'] = $this-&gt;news_model-&gt;get_news(); $data['title'] = 'News archive'; $this-&gt;load-&gt;view('templates/header', $data); $this-&gt;load-&gt;view('news/index', $data); $this-&gt;load-&gt;view('templates/footer'); } </code></pre> <p>the only way I can interpret the tutorial, is to add it to the News.php controller.</p> <pre><code>&lt;?php class News extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;model('news_model'); $this-&gt;load-&gt;helper('url_helper'); } public function index() { $data['news'] = $this-&gt;news_model-&gt;get_news(); } public function view($slug = NULL) { $data['news_item'] = $this-&gt;news_model-&gt;get_news($slug); if (empty($data['news_item'])) { show_404(); } $data['title'] = $data['news_item']['title']; $this-&gt;load-&gt;view('templates/header', $data); $this-&gt;load-&gt;view('news/view', $data); $this-&gt;load-&gt;view('templates/footer'); } } </code></pre> <p>when I add it at the end of application/controllers/News.php I get a parse error:</p> <pre><code>Parse error: parse error in /server/application/controllers/News.php on line 33 A PHP Error was encountered Severity: Parsing Error Message: parse error Filename: controllers/News.php Line Number: 33 Backtrace: </code></pre> <p>if I include it within the News class, I get two PHP errors &amp; a fatal error:</p> <pre><code>Fatal error: Cannot redeclare News::index() in /server/application/controllers/News.php on line 32 A PHP Error was encountered Severity: Warning Message: Cannot modify header information - headers already sent by (output started at /server/application/controllers/News.php:32) Filename: core/Common.php Line Number: 573 Backtrace: A PHP Error was encountered Severity: Compile Error Message: Cannot redeclare News::index() Filename: controllers/News.php Line Number: 32 Backtrace: </code></pre> <p>Not sure what else to try?</p> <p>Thanks in advance.</p>
3
1,169
NodeJS rest api which return response similar like Java Map e.g. Map<String,List<Class>>
<p>I am having 2 tables <strong>product_categories</strong> and <strong>product_sub_categories</strong> and these table columns are as follows:<br> <strong>product_categories:</strong><br> category_id category_name created_by created_date updated_by updated_date <strong>product_sub_categories:</strong><br> sub_category_id category_id sub_category_name created_by created_date updated_by updated_date</p> <p>I am able to fetch product categories and sub_categories like:<br></p> <pre><code>//show all Category route.get('/getAllCategory',(req, res) =&gt; { let sql = &quot;SELECT * FROM product_categories&quot;; let query = conn.query(sql, (err, results) =&gt; { if(err) throw err; res.send(JSON.stringify({&quot;status&quot;: 200, &quot;error&quot;: null, &quot;response&quot;: results})); }); }); //show all SubCategory route.get('/getAllSubCategory',(req, res) =&gt; { let sql = &quot;SELECT * FROM product_sub_categories&quot;; let query = conn.query(sql, (err, results) =&gt; { if(err) throw err; res.send(JSON.stringify({&quot;status&quot;: 200, &quot;error&quot;: null, &quot;response&quot;: results})); }); }); </code></pre> <p><strong>The response of getAllCategory:<br></strong></p> <pre><code>{ &quot;status&quot;: 200, &quot;error&quot;: null, &quot;response&quot;: [ { &quot;category_id&quot;: 1, &quot;category_name&quot;: &quot;Baby Care&quot;, &quot;created_by&quot;: &quot;admin&quot;, &quot;created_date&quot;: &quot;2020-05-31T09:39:06.000Z&quot;, &quot;updated_by&quot;: &quot;admin&quot;, &quot;updated_date&quot;: &quot;2020-05-31T09:39:06.000Z&quot; }, { &quot;category_id&quot;: 2, &quot;category_name&quot;: &quot;Personal Care&quot;, &quot;created_by&quot;: &quot;admin&quot;, &quot;created_date&quot;: &quot;2020-05-31T09:43:09.000Z&quot;, &quot;updated_by&quot;: &quot;admin&quot;, &quot;updated_date&quot;: &quot;2020-05-31T09:43:09.000Z&quot; } ] } </code></pre> <p><strong>The response of getAllSubCategory:<br></strong></p> <pre><code>{ &quot;status&quot;: 200, &quot;error&quot;: null, &quot;response&quot;: [ { &quot;sub_category_id&quot;: 35, &quot;category_id&quot;: 1, &quot;sub_category_name&quot;: &quot;Baby Food&quot;, &quot;created_by&quot;: &quot;admin&quot;, &quot;created_date&quot;: &quot;2020-06-09T16:54:15.000Z&quot;, &quot;updated_by&quot;: &quot;admin&quot;, &quot;updated_date&quot;: &quot;2020-06-09T16:54:15.000Z&quot; }, { &quot;sub_category_id&quot;: 36, &quot;category_id&quot;: 1, &quot;sub_category_name&quot;: &quot;Diapers &amp;amp; Wipes&quot;, &quot;created_by&quot;: &quot;admin&quot;, &quot;created_date&quot;: &quot;2020-06-09T16:55:05.000Z&quot;, &quot;updated_by&quot;: &quot;admin&quot;, &quot;updated_date&quot;: &quot;2020-06-09T16:55:05.000Z&quot; }, { &quot;sub_category_id&quot;: 27, &quot;category_id&quot;: 2, &quot;sub_category_name&quot;: &quot;Skin Care&quot;, &quot;created_by&quot;: &quot;admin&quot;, &quot;created_date&quot;: &quot;2020-06-09T16:54:15.000Z&quot;, &quot;updated_by&quot;: &quot;admin&quot;, &quot;updated_date&quot;: &quot;2020-06-09T16:54:15.000Z&quot; }, { &quot;sub_category_id&quot;: 28, &quot;category_id&quot;: 2, &quot;sub_category_name&quot;: &quot;Hair Care&quot;, &quot;created_by&quot;: &quot;admin&quot;, &quot;created_date&quot;: &quot;2020-06-09T16:55:05.000Z&quot;, &quot;updated_by&quot;: &quot;admin&quot;, &quot;updated_date&quot;: &quot;2020-06-09T16:55:05.000Z&quot; } ] } </code></pre> <p>But I want to merge these into one so that I can get response like:<br> { &quot;CategoryName1&quot;:[ listOfSubCategory_ofCategoryName1],<br> &quot;CategoryName2&quot;:[ listOfSubCategory_ofCategoryName2]}<br> Sample Example:<br></p> <pre><code>{     &quot;Baby Care&quot;: [         {             &quot;sub_category_id&quot;: &quot;35&quot;,             &quot;sub_category_name&quot;: &quot;Baby Food&quot;         },         {             &quot;sub_category_id&quot;: &quot;36&quot;,             &quot;sub_category_name&quot;: &quot;Diapers &amp;amp; Wipes&quot;         }     ],     &quot;Personal Care&quot;: [         {             &quot;sub_category_id&quot;: &quot;27&quot;,             &quot;sub_category_name&quot;: &quot;Skin Care&quot;         },         {             &quot;sub_category_id&quot;: &quot;28&quot;,             &quot;sub_category_name&quot;: &quot;Hair Care&quot;         }     ] } </code></pre> <p>Any suggestions will be greatly appreciated.</p>
3
2,632
How to convert GA API JSON to Pandas DataFrame
<p>I'm developing a connector Google Analytics to MS SQL Server and in order to load the GA info to a DB Table the API response should be normalized. I thought pd.Dataframe is not a bad idea. </p> <p>API Responce v3</p> <pre><code>{'columnHeaders': [{'columnType': 'DIMENSION', 'dataType': 'STRING', 'name': 'ga:yearMonth'}, {'columnType': 'DIMENSION', 'dataType': 'STRING', 'name': 'ga:year'}, {'columnType': 'METRIC', 'dataType': 'INTEGER', 'name': 'ga:users'}, {'columnType': 'METRIC', 'dataType': 'INTEGER', 'name': 'ga:sessions'}], 'containsSampledData': False, 'id': 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:*****&amp;dimensions=ga:yearMonth,ga:year&amp;metrics=ga:users,ga:sessions&amp;start-date=2019-01-01&amp;end-date=2019-01-31&amp;start-index=1', 'itemsPerPage': 1000, 'kind': 'analytics#gaData', 'profileInfo': {'accountId': '****', 'internalWebPropertyId': '***', 'profileId': '***', 'profileName': 'All Web Site Data', 'tableId': 'ga:178030957', 'webPropertyId': 'UA-****-1'}, 'query': {'dimensions': 'ga:yearMonth,ga:year', 'end-date': '2019-01-31', 'ids': 'ga:****', 'max-results': 1000, 'metrics': ['ga:users', 'ga:sessions'], 'start-date': '2019-01-01', 'start-index': 1}, 'rows': [['201901', '2019', '3677', '4501']], 'selfLink': 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:****&amp;dimensions=ga:yearMonth,ga:year&amp;metrics=ga:users,ga:sessions&amp;start-date=2019-01-01&amp;end-date=2019-01-31&amp;start-index=1', 'totalResults': 1, 'totalsForAllResults': {'ga:sessions': '4501', 'ga:users': '3677'}} </code></pre> <p>I want to include in df the following params: query info, profileInfo and rows.</p> <p>So far I've tried accessing json through json_normalize function, but it doesn't convert the response properly :( </p> <pre class="lang-py prettyprint-override"><code> df_test=json_normalize(traffic_results) </code></pre> <p>It produces df with nested dicts</p> <p>Then I've tried to pass record_path and meta info:</p> <pre class="lang-py prettyprint-override"><code>df_example=json_normalize(traffic_results, record_path=['rows'], meta=[['query', 'dimensions'], ['query', 'metrics']]) </code></pre> <p>Get rows and then dimensions and metrics, but it produces an error: </p> <p>ValueError: Length of values does not match length of index.</p> <p>But when I pass these args: </p> <pre class="lang-py prettyprint-override"><code>response_ga_report=json_normalize(traffic_results, record_path=['rows'], meta=[['query' , 'ids'], ['query' , 'dimensions']]) </code></pre> <p>It works ok:</p> <pre class="lang-py prettyprint-override"><code> 0 1 2 3 query.ids query.dimensions 0 201901 2019 3677 4501 ga:178030957 ga:yearMonth,ga:year </code></pre> <p>I'm deeply stuck, have no idea how it can be converted. It's not mandatory to convert the response in DF.</p>
3
1,455
Binding instances during Caliper benchmarks
<p>I've recently been tasked with benchmarking some features of our API, and I've been using Caliper to do so. It seems fairly straightforward and is actually quite powerful, I've been following the tutorials here:</p> <p><a href="https://stackoverflow.com/questions/21341505/how-to-use-caliper-for-benchmarking">How to use caliper</a></p> <p><a href="https://www.youtube.com/watch?feature=player_embedded&amp;v=Rbx0HUCnF24" rel="nofollow noreferrer">Tutorial from the creator</a></p> <p>I'm working with Guice in our current app, so when I try to run the benchmark, I make sure to inject the services I need</p> <p>Provided below is my code. I've tried setting the variables with their own <code>@injected</code> annotation, I've tried initiating them directly (although there's too many dependencies to deal with, and I'd have to initiate them as well). <code>@Parms</code> annotation won't work because I need to have a string type to iterate through (the parms only takes strings, there's documentation of what to do if it's another type, but it needs a <code>.toString</code> type method)</p> <pre><code>package com.~~~.~~~.api.benchmark; import com.~~~.ds.mongo.orm.user.User; import com.~~~.~~~.api.exceptions.auth.AccessDeniedException; import com.~~~.~~~.api.service.authorization.UserService; import com.~~~.~~~.api.service.campaign.CampaignMetadataService; import com.google.caliper.BeforeExperiment; import com.google.caliper.Benchmark; import com.google.caliper.Param; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class CampaignBenchmark { // === SERVICE INJECTIONS @Inject private CampaignMetadataService campaignMetadataService; @Inject private UserService userService; // ============================================= // === BENCHMARK PARMS @Param({ "7ca8c319", "49191829" }) String userId; @Param({ "485", "500" }) String hashAdvertiserId; // ============================================= // === TESTING PARMS private User user; // ============================================= // === SETUP @Inject public CampaignBenchmark(){ Injector injector = Guice.createInjector(); this.userService = injector.getInstance(UserService.class); this.campaignMetadataService = injector.getInstance(CampaignMetadataService.class); } @BeforeExperiment void setUp(){ this.user = userService.getUserByHashedId(userId); } // ============================================= // === BENCHMARKS @Benchmark int fetchAllCampaign(int reps) throws AccessDeniedException { VideoIqUser user = this.user; String hashAdvertiserId = this.hashAdvertiserId; int dummy = 0; for(int i=0 ; i&lt;reps ; i++){ dummy |= campaignMetadataService.fetchAllCampaigns(user, hashAdvertiserId).size(); } return dummy; } } </code></pre> <p>When we try to run it with</p> <pre><code>mvn exec:java -Dexec.mainClass="com.google.caliper.runner.CaliperMain" -Dexec.args="com.~~~.~~~.api.benchmark.CampaignBenchmark" </code></pre> <p>We get the following</p> <pre><code>WARNING: All illegal access operations will be denied in a future release Experiment selection: Benchmark Methods: [fetchAllCampaign] Instruments: [allocation, runtime] User parameters: {hashAdvertiserId=[485, 500], userId=[7ca8c319, 49191829]} Virtual machines: [default] Selection type: Full cartesian product This selection yields 16 experiments. Could not create an instance of the benchmark class following reasons: 1) Explicit bindings are required and com.~~~.~~~.api.service.campaign.CampaignMetadataService is not explicitly bound. 2) Explicit bindings are required and com.~~~.~~~.api.service.authorization.UserService is not explicitly bound. </code></pre> <p>The question is: at what point should I be doing injections, and how do I go about that? Should I have a wrapper class setup?</p> <p><strong>Quick Update</strong></p> <p>I forgot to mention that is part of a DropWizard (0.7.1) application. We use resources and inject them into the environment</p> <p>Ex:</p> <pre><code>environment.jersey().register(injector.getInstance(CampaignManagementResource.class)); </code></pre> <p>These resources contain the services needed to run them, and they are included as @Inject, though we never actually specify a binding anywhere else.</p> <pre><code>@Inject private CampaignMetadataService apiCampaignMetadataService; </code></pre> <p>Is there something I should adjust for DropWizard, or should I just mock up the services?</p>
3
1,569
How to bind data attribute instead of id?
<p>Use bootstrap 3 carousel - <a href="http://jsfiddle.net/cxv1osq0/" rel="nofollow noreferrer">Fiddle</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>/* for testing only */ .item img { width: 100%; height: auto }</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;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;div data-id="carousel-example-generic" class="carousel slide" data-ride="carousel"&gt; &lt;!-- Indicators --&gt; &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="1"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="2"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;!-- Wrapper for slides --&gt; &lt;div class="carousel-inner" role="listbox"&gt; &lt;div class="item active"&gt; &lt;img src="http://placehold.it/450x350" alt="Slide 1"&gt; &lt;div class="carousel-caption"&gt; Caption Slide 1 &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src="http://placehold.it/450x350" alt="Slide 2"&gt; &lt;div class="carousel-caption"&gt; Caption Slide 2 &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img src="http://placehold.it/450x350" alt="Slide 3"&gt; &lt;div class="carousel-caption"&gt; Caption Slide 3 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Controls --&gt; &lt;a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"&gt; &lt;span class="glyphicon glyphicon-chevron-left" aria-hidden="true"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Previous&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"&gt; &lt;span class="glyphicon glyphicon-chevron-right" aria-hidden="true"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Next&lt;/span&gt; &lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>In <a href="http://getbootstrap.com/docs/3.3/javascript/#carousel" rel="nofollow noreferrer">bootstrap documentation</a> uses the <code>id</code> for the <code>carousel</code></p> <pre><code>&lt;!-- Carousel --&gt; &lt;div id="carousel-example-generic" class="carousel slide" data-ride="carousel"&gt; &lt;!-- Carousel Indicators --&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="1"&gt;&lt;/li&gt; &lt;!-- Carousel Controls --&gt; &lt;a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"&gt; </code></pre> <p>I would like to use instead of <code>id</code> the <code>data attribute(data-id)</code> </p> <pre><code>&lt;!-- Carousel --&gt; &lt;div data-id="carousel-example-generic" class="carousel slide" data-ride="carousel"&gt; </code></pre> <p>If you use the data attribute - then pagination and navigation does not work</p> <p>How to bind the data attribute to the pagination and navigation of the slider?</p> <p>Thank you</p> <p>I will be glad to any help</p>
3
1,514
Speech Recognition stops listening immediately
<p>I want to listen the first word from the user. When speech recognition starts I hear the bip-sound, but immediately I hear the stop sound. I observed that onRMSchanged is the only method where something is happening. </p> <p>This is how I use the SpeechRecognizer. I am connected to the internet when I run the application.</p> <pre><code> Intent speechintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechintent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS , 1000); speechintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); speechintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en"); SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Inference.getmContext()); speechRecognizer.setRecognitionListener(new RecognitionListener() { @Override public void onReadyForSpeech(Bundle params) { } @Override public void onBeginningOfSpeech() { Log.i("beg", "beg"); } @Override public void onRmsChanged(float rmsdB) { Log.i("on rms changed", "rms changed"); } @Override public void onBufferReceived(byte[] buffer) { Log.i("ANSWER","END"); } @Override public void onEndOfSpeech() { Log.i("ANSWER","END"); } @Override public void onError(int error) { } @Override public void onResults(Bundle results) { Log.i("ANSWER",results.getString(RecognizerIntent.EXTRA_RESULTS)); ArrayList&lt;String&gt; result = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); } @Override public void onPartialResults(Bundle partialResults) { Log.i("ANSWER",partialResults.getString(RecognizerIntent.EXTRA_RESULTS)); } @Override public void onEvent(int eventType, Bundle params) { } }); speechRecognizer.startListening(speechintent); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { speechRecognizer.stopListening(); } }, 1000); </code></pre> <p>I do not know why it doesn't let me speak.</p> <p>UPDATE:</p> <p>This is the order it goes through the methods:</p> <pre><code>onRmsChanged onReadyForSpeech onError </code></pre> <p>onError I get the error code 2, that means Network Error, but I already set the Google Text To speech, I put <code>INTERNET</code> and <code>RECORD_AUDIO</code> permissions in Manifest and I am connected to the internet. I do not understand what is wrong?</p>
3
1,289
Preventing td from getting smaller when content is empty
<p>I have the following table structure. I have a table inside a table here.</p> <p><a href="https://i.stack.imgur.com/NCb3V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NCb3V.png" alt="enter image description here"></a></p> <p>My issue is, if the td doesnt contain any text, the full-height gets removed for some reason:</p> <p><a href="https://i.stack.imgur.com/TxgwF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TxgwF.png" alt="enter image description here"></a></p> <p>This is my HTML: (mixed with some Razor which isnt really relevant here)</p> <pre><code>&lt;td style="padding:0;margin:0;"class="border border-dark border-dark"&gt; &lt;table class=" table-borderless justify-content-center " cellspacing="20" style="height:100%!important;padding:0;margin:0;"&gt; &lt;tr style="height:100%; text-align:center;font-size:10px;"class="flex-none"&gt; if (condition) { &lt;td style="width:@Percent%; height:100%;" onclick="document.getElementById('EventId_HiddenInput').value='@Model.Events.SingleOrDefault(r =&gt; r.EventId == id).EventId';" class="FillModalWithEventData bg-primary flex-md-fill"&gt; &lt;a onclick="document.getElementById('EventId_HiddenInput').value='@Model.Events.SingleOrDefault(r =&gt; r.EventId == id).EventId';" class="FillModalWithEventData"&gt;@Model.Events.SingleOrDefault(r =&gt; r.EventId == id).Company.ToString()&lt;/a&gt; &lt;/td&gt; } else { &lt;td style="width:@Percent%;height:100%; " onclick="document.getElementById('EventId_HiddenInput').value='@Model.Events.SingleOrDefault(r =&gt; r.EventId == id).EventId';" class="FillModalWithEventData bg-primary "&gt; &lt;a onclick="document.getElementById('EventId_HiddenInput').value='@Model.Events.SingleOrDefault(r =&gt; r.EventId == id).EventId';" class="FillModalWithEventData"&gt;filler&lt;/a&gt; &lt;/td&gt; } &lt;td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; </code></pre> <p>How can I prevent it from shrinking and keep it at full height if td is empty?</p>
3
1,420
What does Relay use to decide which outputFields to include in a mutation response?
<p>I am creating my first React/Relay application by modifying the TODO example. I am to the point where I am adding my own mutation for an object Distributor that has a parameter bookCount. The mutation is called AddBook and simply increases book count by 1. At this point, the mutation executes without error, optimistically increases the bookCount by 1 correctly, but then reverts the model change when it receives the response from the server. I believe this to be because the response from the server mysteriously does not contain any of my specified outputFields.</p> <p>Here is my mutation:</p> <pre><code>var GraphQLAddBookMutation = mutationWithClientMutationId({ name: 'AddBook', inputFields: { }, outputFields: { distributor: { type: GraphQlDistributor, resolve: () =&gt; getDistributor(), }, }, mutateAndGetPayload: () =&gt; { console.log("Trying to mutate."); addBook(); return {}; }, }); </code></pre> <p>It contains the field 'distributor' in outputFields but no 'distributor' data is included in the graphql response.</p> <p>The graphql response is:</p> <pre><code>{ "data": { "addBook": { "clientMutationId": "0" } } } </code></pre> <p>I have verified that the mutateAndGetPayload function DOES get called but the distributor resolve function DOES NOT get called. </p> <p>I would have expected every field in outputFields to be included in the graphql response, and every resolve function within outputFields to be called to populate the appropriate parameters in the response but this is not the case</p> <p>This is particularly confusing to me because the generated schema.json DOES include any outputFields that I specify in the AddBookPayload:</p> <pre><code>{ "kind": "OBJECT", "name": "AddBookPayload", "description": null, "fields": [ { "name": "distributor", "description": null, "args": [], "type": { "kind": "OBJECT", "name": "Distributor", "ofType": null }, "isDeprecated": false, "deprecationReason": null }, { "name": "clientMutationId", "description": null, "args": [], "type": { "kind": "NON_NULL", "name": null, "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } }, "isDeprecated": false, "deprecationReason": null } ], "inputFields": null, "interfaces": [], "enumValues": null, "possibleTypes": null }, </code></pre>
3
1,083
Spark's example throws FileNotFoundException in client mode
<p>I have: Ubuntu 14.04, Hadoop 2.7.7, Spark 2.2.0.</p> <p>I just installed everything.</p> <p>When I try to run the the Spark's example:</p> <pre><code>bin/spark-submit --deploy-mode client \ --class org.apache.spark.examples.SparkPi \ examples/jars/spark-examples_2.11-2.2.0.jar 10 </code></pre> <p>I get the following error:</p> <blockquote> <p>INFO yarn.Client: client token: N/A diagnostics: Application application_1552490646290_0007 failed 2 times due to AM Container for appattempt_1552490646290_0007_000002 exited with exitCode: -1000 For more detailed output, check application tracking page:<a href="http://ip-123-45-67-89:8088/cluster/app/application_1552490646290_0007" rel="nofollow noreferrer">http://ip-123-45-67-89:8088/cluster/app/application_1552490646290_0007</a> Then, click on links to logs of each attempt. Diagnostics: File file:/tmp/spark-f5879f52-6777-481a-8ecf-bbb55e376901/__spark_libs__6948713644593068670.zip does not exist java.io.FileNotFoundException: File file:/tmp/spark-f5879f52-6777-481a-8ecf-bbb55e376901/__spark_libs__6948713644593068670.zip does not exist</p> </blockquote> <pre><code> at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:611) at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:824) at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:601) at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:428) at org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:253) at org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:63) at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:361) at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:359) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:421) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1762) at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:358) at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:62) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:473) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:622) at java.lang.Thread.run(Thread.java:748) </code></pre> <p>I get the same error both in client mode and cluster mode.</p>
3
1,167
in excel empty cells of non empty rows are neglected using java , POI jars
<p><strong>Excel To Json Conversion using JAVA, POI</strong></p> <blockquote> <blockquote> <p>Issue: Empty cells in Non Empty rows are neglected.</p> <blockquote> <p>I am trying to convert an excel file through java to Json.<a href="https://i.stack.imgur.com/VFtyE.png" rel="nofollow noreferrer">A2 and B2 cells are empty but these cells are negleted i want even these cells to be counted and return an empty string</a></p> </blockquote> </blockquote> </blockquote> <p><a href="https://i.stack.imgur.com/kUs4w.png" rel="nofollow noreferrer">output obtained, the 2nd row starts from C2 by neglecting A2 and B2 which has empty values</a></p> <p>public static String ExcelToJsonConverter(String filePath) throws Exception {</p> <pre><code>try { FileInputStream inp = new FileInputStream(filePath); Workbook workbook = WorkbookFactory.create(inp); Sheet sheet = workbook.getSheetAt(0); JSONArray rows = new JSONArray(); int coun = 0; for (Iterator &lt; Row &gt; rowsIT = sheet.rowIterator(); rowsIT.hasNext();) { Row row = rowsIT.next(); JSONObject jRow = new JSONObject(); JSONArray cells = new JSONArray(); for (Iterator &lt; Cell &gt; cellsIT = row.cellIterator(); cellsIT.hasNext();) { coun++; Cell cell = cellsIT.next(); String val = ""; if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { System.out.println("Formula is " + cell.getCellFormula()); switch (cell.getCachedFormulaResultType()) { case Cell.CELL_TYPE_NUMERIC: System.out.println("Last evaluated as: " + cell.getNumericCellValue()); val = Double.toString(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\""); val = cell.getStringCellValue(); break; } } else if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { val = " "; } else { val = formatter.formatCellValue(cell); } enter code here cells.put(val); } jRow.put("", cells); rows.put(jRow); } json.put("", rows); } catch (Exception e) { //throw new BsfConstraintViolationException("Please Upload a valid file."+e.getMessage()); throw new BsfConstraintViolationException("Please Upload a valid file using Download Default BOQ option"); } String formatJson = json.toString().replace("\"\":", ""); formatJson = formatJson.toString().replace("{", ""); formatJson = formatJson.toString().replace("}", ""); formatJson = formatJson.substring(1, formatJson.length() - 1); return formatJson; </code></pre> <p>}</p> <p>Advance Thanks to all</p>
3
1,299
CoreOS cloud config not creating user
<p>The template does not generate the bamboo user that I have set up in the cloud config. I ssh into my cluster and see cat /etc/passwd but I don't see that user. What might be going wrong?</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> { "AWSTemplateFormatVersion": "2010-09-09", "Description": "CoreOS on EC2: http://coreos.com/docs/running-coreos/cloud-providers/ec2/", "Mappings" : { "RegionMap" : { "us-west-2" : { "AMI" : "ami-06af7f66" } } }, "Parameters": { "InstanceType" : { "Description" : "EC2 HVM instance type (m3.medium, etc).", "Type" : "String", "Default" : "t2.small", "AllowedValues" : [ "t2.micro", "m3.medium", "i2.4xlarge", "i2.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge","r3.4xlarge", "r3.8xlarge", "t2.micro", "t2.small", "t2.medium" ], "ConstraintDescription" : "Must be a valid EC2 HVM instance type." }, "myVPC": { "Type": "AWS::EC2::VPC::Id", "Description": "The VPC Id where the instances will be deployed into." }, "SecurityGroupId":{ "Type": "List&lt;AWS::EC2::SecurityGroup::Id&gt;", "Description": "Security group to launch instances into." }, "SubnetId":{ "Type": "List&lt;AWS::EC2::Subnet::Id&gt;", "Description": "VPC group to launch instances into." }, "ClusterSize": { "Default": "3", "MinValue": "3", "MaxValue": "12", "Description": "Number of nodes in cluster (3-12).", "Type": "Number" }, "DiscoveryURL": { "Description": "An unique etcd cluster discovery URL. Grab a new token from https://discovery.etcd.io/new?size=&lt;your cluster size&gt;", "Type": "String" }, "AdvertisedIPAddress": { "Description": "Use 'private' if your etcd cluster is within one region or 'public' if it spans regions or cloud providers.", "Default": "private", "AllowedValues": ["private", "public"], "Type": "String" }, "KeyPair" : { "Description" : "The name of an EC2 Key Pair to allow SSH access to the instance.", "Type" : "AWS::EC2::KeyPair::KeyName" } }, "Resources": { "CoreOSServerAutoScale": { "Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": { "LaunchConfigurationName": {"Ref": "CoreOSServerLaunchConfig"}, "VPCZoneIdentifier": {"Ref":"SubnetId"}, "MinSize": "3", "MaxSize": "12", "DesiredCapacity": {"Ref": "ClusterSize"}, "Tags": [ {"Key": "Name", "Value": { "Ref" : "AWS::StackName" }, "PropagateAtLaunch": true} ] } }, "CoreOSServerLaunchConfig": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Properties": { "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "InstanceType": {"Ref": "InstanceType"}, "KeyName": {"Ref": "KeyPair"}, "SecurityGroups": {"Ref": "SecurityGroupId"}, "UserData" : { "Fn::Base64": { "Fn::Join": [ "", [ "#cloud-config\n\n", " users:\n", " - name: bamboo\n", " groups:\n", " - sudo\n", " - docker\n", " - fleet\n", " - systemd\n", " - wheel\n", " - bamboo\n", " ssh-authorized-keys:\n", " - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKT3QjGuTD4sdBfKZZm1cOz2gXBH546vGizsDGf3LEQC63QduU1CPQBvTG742H5yVix7y+qvZPTYlvQ1ysK6ezhbGeu+lT0WoI8YT4x2Pqe/F40WGn/SMv3ckELQhKH3gp9HC1z/ITxYVgTksKGGXgNO6G8w8J+XaC1hyYntyOz531GAly9szCxtPQJQCz1fS3fdjSPEM+7TyuwH240S/Aa0R0XGUt24xH4zyifmUjrvGq4AaHIFUyWO3XnEc/3kdA2uUQlV/2o7z9xE0WhYPWm2oReHXNuoOCQutTCYwNKaTI+Y/vGtGxsCmIQWVoY4Afg2nL0MQ1Mnfw3DddQJvB cmbuild@bamboo_agent_fleetctl \n", "coreos:\n", " etcd2:\n", " discovery: ", { "Ref": "DiscoveryURL" }, "\n", " advertise-client-urls: http://$", { "Ref": "AdvertisedIPAddress" }, "_ipv4:2379\n", " initial-advertise-peer-urls: http://$", { "Ref": "AdvertisedIPAddress" }, "_ipv4:2380\n", " listen-client-urls: http://0.0.0.0:2379,http://0.0.0.0:4001\n", " listen-peer-urls: http://$", { "Ref": "AdvertisedIPAddress" }, "_ipv4:2380\n", " units:\n", " - name: etcd2.service\n", " command: start\n", " - name: fleet.service\n", " command: start\n" ] ] } } } } } }</code></pre> </div> </div> </p> <p>The cluster is generated and works well but I don't see that user. Is there a place I can see logs for why the user generation did not occur?</p>
3
3,332
sensorLandscape activity display very slowly when first run after first installer
<pre><code>&lt;activity android:name=".WelcomeActivity" android:configChanges="orientation|keyboardHidden|screenSize|screenLayout" android:launchMode="singleTop" android:screenOrientation="sensorLandscape" android:theme="@style/WelcomeStyle" 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;/activity&gt; import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class WelcomeActivity extends FragmentActivity { private static final String TAG = "WelcomeActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); } } &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rootlayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/welcom_background"&gt; &lt;FrameLayout android:id="@+id/bootImg_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:layoutAnimation="@anim/ads_show_anim" android:visibility="gone"&gt; &lt;ImageView android:id="@+id/bootImage" android:layout_width="match_parent" android:layout_height="match_parent" android:adjustViewBounds="true" android:scaleType="centerCrop" /&gt; &lt;TextView android:id="@+id/adsCountDownTime" android:layout_width="40dp" android:layout_height="30dp" android:layout_gravity="right" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:gravity="center" android:text="@string/ads_accountime" android:textColor="@color/color_white" android:textSize="25sp" /&gt; &lt;TextView android:id="@+id/channelApkDwnButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center_horizontal" android:layout_marginBottom="50dp" android:gravity="center" android:visibility="gone" /&gt; &lt;/FrameLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>When my app's first activity set orientation with 'sensorLandscape', my app first running is very slow after installer. Who can tell me why and how fix it? Add one condition: my app's method more than 65k. When I set android:screenOrientation="portrait", the welcome activity's view will be display immediately after first installer.</p>
3
1,220
How to place buttons correctly in a layout - android
<p>In my android app I have three buttons below. The problem I have is that these buttons are too close together and if I try to move one of them away then they all follow. Maybe because I state which button should go below who but I want to know if there's a way in my xml code to create a gap between these buttons?</p> <p><a href="https://i.stack.imgur.com/A3CT6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A3CT6.png" alt="enter image description here"></a></p> <p>Code:</p> <pre><code>&lt;RelativeLayout 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" android:orientation="vertical" tools:context=".MainActivity" android:background="@drawable/brick_wall"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tic Tac Toe " android:layout_centerHorizontal="true" android:paddingTop="50dp" app:fontFamily="@font/balloon_extra_bold" android:textSize="50sp" android:textColor="@color/colorPrimaryLight" /&gt; &lt;Button android:id="@+id/button_players1" android:layout_width="143dp" android:layout_height="30dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="1 Player" android:textColor="@color/black" android:textSize="20sp" /&gt; &lt;Button android:id="@+id/button_players2" android:layout_width="145dp" android:layout_height="30dp" android:layout_below="@id/button_players1" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="2 Players" android:textColor="@color/black" android:textSize="20sp" /&gt; &lt;Button android:id="@+id/button_how_to_play" android:layout_width="148dp" android:layout_height="30dp" android:layout_below="@id/button_players2" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="How to Play" android:textColor="@color/black" android:textSize="20sp" /&gt; &lt;/RelativeLayout&gt; </code></pre>
3
1,220
Nested cfloops with less records than outer loop cause "array index out of range" error
<p>I'm very curious why this is happening. I've run into it twice now, and after a ton of googling/so'ing, I haven't found any reason I actually understand. The gist of it:</p> <p>Query 1: selectContent (6 records; no blanks/nulls etc)</p> <p>Query 2: selectPricing (5 records; no blanks/nulls etc)</p> <p>Output: </p> <pre><code>&lt;cfloop query="selectContent"&gt; &lt;section&gt; #selectContent.h2# &lt;cfif selectContent.id eq 3&gt; &lt;cfloop query="selectPricing" group="groupCol"&gt; &lt;table class="pricing"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;#description#&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;cfloop&gt; &lt;tr&gt; &lt;td&gt;#selectPricing.description#&lt;/td&gt; &lt;td&gt;#selectPricing.price#&lt;/td&gt; &lt;/tr&gt; &lt;/cfloop&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/cfloop&gt; &lt;/cfif&gt; #selectContent.content# &lt;/section&gt; &lt;/cfloop&gt; </code></pre> <p>This will give the following error: <em>Array index out of range: 5</em></p> <p>The error only occurs when the second query has less records than the first. Essentially it feels like that first cfloop takes over the loop iteration from that second one and this causes the issue, but also only if you have that third grouped cfloop in there. The entire inner cfloop runs, as is there in the source.</p> <p>I've come up with two ways to resolve this:</p> <ul> <li>do this with cfoutput/group, but that's relatively ugly as it means lots of closing of cfoutputs from other parts of the page. </li> <li>stick a cfbreak on that third cfloop if the currentRow matches the recordcount.</li> </ul> <p><strong>So, two questions:</strong> </p> <ul> <li><p>Why is this even happening? </p></li> <li><p>Should I be using a totally different approach here (the fact that googling/so'ing isn't finding others with this issue certainly seems to imply that...)?</p></li> </ul> <p><strong>EDIT</strong> I've filed this as a Coldfusion bug based on Adam Cameron's feedback below. <a href="https://bugbase.adobe.com/index.cfm?event=bug&amp;id=3820049">Bug #3820049</a> </p>
3
1,164
Spring boot Controller json response has a field name "empty"
<p>I have a GET endpoint in my application supposed to return :</p> <pre><code>{ &quot;gameId&quot;: &quot;41a483c4-6220-424a-a931-d9114a4f6748&quot;, &quot;pits&quot;: [ { &quot;id&quot;: 1, &quot;stones&quot;: 6 }, { &quot;id&quot;: 2, &quot;stones&quot;: 6 }, { &quot;id&quot;: 3, &quot;stones&quot;: 6 }, { &quot;id&quot;: 4, &quot;stones&quot;: 6 }, { &quot;id&quot;: 5, &quot;stones&quot;: 6 }, { &quot;id&quot;: 6, &quot;stones&quot;: 6 }, { &quot;id&quot;: 7, &quot;stones&quot;: 0 }, { &quot;id&quot;: 8, &quot;stones&quot;: 6 }, { &quot;id&quot;: 9, &quot;stones&quot;: 6 }, { &quot;id&quot;: 10, &quot;stones&quot;: 6 }, { &quot;id&quot;: 11, &quot;stones&quot;: 6 }, { &quot;id&quot;: 12, &quot;stones&quot;: 6 }, { &quot;id&quot;: 13, &quot;stones&quot;: 6 }, { &quot;id&quot;: 14, &quot;stones&quot;: 0 } ], &quot;playerTurn&quot;: null, &quot;currentPitIndex&quot;: 0 } </code></pre> <p>but instead it returns:</p> <pre><code>{ &quot;id&quot;: &quot;25f09303-b797-418f-a7e7-db0e5fa8631b&quot;, &quot;pits&quot;: [ { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 0, &quot;empty&quot;: true }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 6, &quot;empty&quot;: false }, { &quot;stones&quot;: 0, &quot;empty&quot;: true } ], &quot;playerTurn&quot;: null, &quot;currentPitIndex&quot;: null } </code></pre> <p>I am wondering what is &quot;empty&quot;?! and where is &quot;id&quot;!</p> <p>would be much appreciated for any suggestion and help. thank you</p>
3
1,864
Set initial values in form passing parameters (kwargs) with view
<p>I want to prefill a form with values taken in a table. First I pass the PK relative to the line where I wan't to get values and build the kwargs list:</p> <p><strong>views.py</strong></p> <pre><code>def NavetteToFicheCreateView(request, pk): navette = Navette.objects.get(id=pk) ref = navette.id attribute_set = navette.famille.pk cost = navette.cost qty = navette.qty etat = navette.etat etat_ebay = navette.etat.etat_ebay ean = get_last_ean() form = NavetteToFicheForm( request.POST, ref=ref, attribute_set=attribute_set, cost=cost, qty=qty, etat=etat, etat_ebay=etat_ebay, ean=ean, ) [...] </code></pre> <p>then I retrieve the kwargs in the <strong>form.py</strong> and setup my initial values</p> <p>class NavetteToFicheForm(forms.ModelForm):</p> <pre><code>def __init__(self, *args, **kwargs): self.ref = kwargs.pop('ref', 'noref') self.attribute_set = kwargs.pop('attribute_set', 9999) self.cost = kwargs.pop('cost', 0) self.qty = kwargs.pop('qty', 0) self.etat = kwargs.pop('etat', 0) self.etat_ebay = kwargs.pop('etat_ebay', 9999) self.ean = kwargs.pop('ean', 9999) super(NavetteToFicheForm, self).__init__(*args, **kwargs) self.fields['ref'].initial = self.ref self.fields['attribute_set'].initial = self.attribute_set self.fields['cost'].initial = self.cost self.fields['qty'].initial = self.qty self.fields['etat'].initial = self.etat self.fields['etat_ebay'].initial = self.etat_ebay self.fields['ean'].initial = self.ean [...] </code></pre> <p>My problem : some fields like &quot;ref&quot; or &quot;attribute_set&quot; are foreignKeys and are not transmitted when i display the form.</p> <p>For checking my values :</p> <pre><code>print(self.ref) print(self.attribute_set) </code></pre> <p><strong>output</strong></p> <pre><code>34 2 noref 9999 </code></pre> <p>questions :</p> <ol> <li><p>Why does the &quot;print&quot; displays 2 couples of values ? This looks like as if the &quot;noref&quot; and &quot;999&quot; are taken in account.</p> </li> <li><p>Why if i set manually 34 and 2 values, it works ?</p> <p>self.fields['ref'].initial = 34 self.fields['attribute_set'].initial = 2</p> </li> </ol> <p>There's maybe a better way of doing this but I don't know it yet .</p>
3
1,025
Self overwriting object tab
<p>I'd like to ask you for help. At my current Java programming skills, that are rather basic this problem is magic for me. Let me explain first what was my intention: I wanted to load data from database to object tab called airportList, and this is tab of Airport objects initialized here:</p> <pre><code> public void init() { System.out.println("Applet inicialization ..."); mysqllink = new MySQLlink(); try { mysqllink.getConnection(); } catch (SQLException e) { System.out.println("Not connected!"); e.printStackTrace(); } allAirportAmount = mysqllink.getNumerOfRows(tabela_lotnisk); allAirlineAmount = mysqllink.getNumerOfRows(tabela_linii); allAirplanesAmount = mysqllink.getNumerOfRows(tabela_samolotow); allConnectionsAmount = mysqllink.getNumerOfRows(tabela_tras); airportList = new Airport[allAirportAmount]; //Airport object tab airportList2 = new String[allAirportAmount]; //as a test i put only Airport name from database over here to String tab airlineList = new String[allAirlineAmount]; airplaneList = new String[allAirplanesAmount]; FlightConnectionFrame frame = new FlightConnectionFrame(); //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(frameWidth,frameHeight); frame.setVisible(true); add(frame); } public static MySQLlink mysqllink = new MySQLlink(); public static int allAirportAmount; public static int allAirlineAmount; public static int allAirplanesAmount; public static int allConnectionsAmount; public static Airport airportList[]; // declaration over here public static String airportList2[]; // and here as a test public static String airlineList[]; public static String airplaneList[]; </code></pre> <p>Ok, and as you can see I have 2x tables, the airportList of Airport objects and airportList2 of String type. In the next piece of code I load data from database into those two tabs at the same time:</p> <pre><code>public void viewAirportList() { String query = "select id_lotniska, nazwa, lokalizacja, oplaty_lotniskowe from " + databaseName + "." + tabela_lotnisk; Statement stmt = null; try { stmt = databaseConnection.createStatement(); ResultSet rs = stmt.executeQuery(query); int j = 0; while (rs.next()) { int id_l = rs.getInt("id_lotniska"); String name = rs.getString("nazwa"); String loc = rs.getString("lokalizacja"); double tax = rs.getDouble("oplaty_lotniskowe"); flight_connections.FCApletCore.airportList[j] = new Airport(id_l, name, loc, tax); // this is where the Airport object is created and put into the AirportList tab flight_connections.FCApletCore.airportList2[j] = name; // here, as a test - i put only String value of name to AirportList2 tab j++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } </code></pre> <p>This is how Airport class looks like:</p> <pre><code>public class Airport { public Airport(int i, String n, String l, double o) { airport_id = i; airport_name = n; airport_localization = l; airport_tax = o; System.out.println(" &gt; new object created:" + airport_name); } public int getAirportId(){return airport_id;} public String getAirportName(){return airport_name;} public String getAirportLocalization(){return airport_localization;} public double getAirportTax(){return airport_tax;} public static int airport_id; public static String airport_name; public static String airport_localization; public static double airport_tax; </code></pre> <p>}</p> <p>And using 2x FOR's to get what's inside of both tabs in console:</p> <pre><code>System.out.println("*** Airport objects tab: airportList ***"); for (int i=0; i&lt;flight_connections.FCApletCore.allAirportAmount; i++) { System.out.println("airportList[" + i + "]: " + flight_connections.FCApletCore.airportList[i].getAirportName()); } System.out.println("*** String values tab: airportList2 ***"); for (int i=0; i&lt;flight_connections.FCApletCore.allAirportAmount; i++) { System.out.println("airportList2[" + i + "]: " + flight_connections.FCApletCore.airportList2[i]); } </code></pre> <p>result is:</p> <pre><code>Applet inicialization ... Connecting database... Database connected! loading number of records from database table: lotniska ... loading number of records from database table: linie ... loading number of records from database table: samoloty ... loading number of records from database table: trasy ... &gt; new object created:Port Lotniczy Balice &gt; new object created:Port lotniczy Paryż Charles de Gaulle &gt; new object created:Port Lotniczy Heathrow &gt; new object created:Port Lotniczy O'Hare &gt; new object created:Port Lotniczy Dubaj &gt; new object created:Port lotniczy Berlin-Brandenburg &gt; new object created:Port lotniczy San Francisco &gt; new object created:Port lotniczy Tokio-Haneda *** Airport objects tab: airportList *** airportList[0]: Port lotniczy Tokio-Haneda airportList[1]: Port lotniczy Tokio-Haneda airportList[2]: Port lotniczy Tokio-Haneda airportList[3]: Port lotniczy Tokio-Haneda airportList[4]: Port lotniczy Tokio-Haneda airportList[5]: Port lotniczy Tokio-Haneda airportList[6]: Port lotniczy Tokio-Haneda airportList[7]: Port lotniczy Tokio-Haneda *** String values tab: airportList2 *** airportList2[0]: Port Lotniczy Balice airportList2[1]: Port lotniczy Paryż Charles de Gaulle airportList2[2]: Port Lotniczy Heathrow airportList2[3]: Port Lotniczy O'Hare airportList2[4]: Port Lotniczy Dubaj airportList2[5]: Port lotniczy Berlin-Brandenburg airportList2[6]: Port lotniczy San Francisco airportList2[7]: Port lotniczy Tokio-Haneda </code></pre> <p>And if you take a look at this, the String tab is OK, and the Airport tab is not since it's loaded only with one - the last of the records from database and both of the tabs are loaded in the two lines of code next to each other, I do not have any code that can somehow change the values of the first tab. To test if the Airport objects are created correctly I added <code>System.out.println</code> with name of object created, and that you can see in results as a correct values. I'll add that I'm running this as the applet, what <code>init()</code> can suggest. </p> <p>I changed code a little bit to English names but the database values and tables names are Polish, like in the console you can see "Port lotniczy" what means Airport.</p>
3
2,475