input
stringlengths
51
42.3k
output
stringlengths
18
55k
How does a Java if statement work when it has an assignment and an equality check OR - d together? <p>Why does this if statement, with an assignment and equality check, evaluate to false?</p> <pre><code>public static void test() { boolean test1 = true; if (test1 = false || test1 == false) { System.out.println("Yes"); } else { System.out.println("No"); } } </code></pre> <p>Why is this printing <code>No</code>?</p>
<p>Because of <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html">operator precedence</a>. It is equivalent to this:</p> <pre><code>boolean test1 = true; if (test1 = (false || test1 == false)) { ... } </code></pre> <p>The part in brackets evaluates to <code>false</code>.</p>
javascript only work in 1 data <p>I'm trying to get button hidden using javascript. here the javascript code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt; var btn = document.getElementById("view1"); var a="&lt;?php echo $data[0]-&gt;status==1;?&gt;"; if(!a==0){ btn.style.display = 'none'; } &lt;/script&gt; &lt;script&gt; var btn = document.getElementById("view2"); var a="&lt;?php echo $data[0]-&gt;status;?&gt;"; if(!a==0){ btn.style.display = 'none'; } &lt;/script&gt;</code></pre> </div> </div> </p> <p><a href="http://i.stack.imgur.com/lT2pw.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/lT2pw.jpg" alt="enter image description here"></a></p> <p>but actually only 1 data javascript worked</p>
<p>You can't have multiple elements with the same ID in one HTML document. IDs (identifiers) are supposed to be unique. Look into <code>name</code> or <code>class</code> and selecting multiple elements using <code>document.getElementsByName</code> or <code>document.getElementsByClassName</code>.<br> Alternatively, if your HTML is generated from PHP as well, display / hide the buttons in the HTML directly.</p>
Setting up Boost 1.62 in CLion windows <p>I have been trying to set up boost 1.62 in CLion for past two days now. I have seen almost all the stack question but still couldn't do it.</p> <p>My CMakeList.txt looks like this:</p> <pre><code>cmake_minimum_required(VERSION 3.6) project(DeSNN_CPP) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") SET (BOOST_ROOT "C:/Program Files/boost/boost_1_62_0") SET (BOOST_INCLUDEDIR "/opt/boost/boost-1.57.0/boost") SET (BOOST_LIBRARYDIR "/opt/boost/boost-1.57.0/boost") SET (BOOST_MIN_VERSION "1.62.0") set (Boost_NO_BOOST_CMAKE ON) FIND_PACKAGE(Boost ${BOOST_MIN_VERSION} REQUIRED) if (NOT Boost_FOUND) message(FATAL_ERROR "Fatal error: Boost (version &gt;= 1.62) required.") else() message(WARNING "Setting up BOOST") message(WARNING " Includes - ${Boost_INCLUDE_DIRS}") message(WARNING " Library - ${Boost_LIBRARY_DIRS}") include_directories(${Boost_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) endif (NOT Boost_FOUND) set(SOURCE_FILES main.cpp) add_executable(DeSNN_CPP ${SOURCE_FILES}) </code></pre> <p>WARNING because my cmake doesn't given output for STATUS.</p> <p>This seems to locate the boost directory, and I can import all the header file. CMAKE outputs the following</p> <pre><code>Warning:start running cmake... Warning:Setting up BOOST Warning:Includes - C:/Program Files/boost/boost_1_62_0 Warning:Library - </code></pre> <p><code>Warning:Library</code> doesn't seem to be showing up. When I type <code>FIND_PACKAGE(Boost ${BOOST_MIN_VERSION} REQUIRED filesystem)</code> I get the following error</p> <pre><code>Error:Unable to find the requested Boost libraries. Boost version: 1.62.0 Boost include path: C:/Program Files/boost/boost_1_62_0 Could not find the following Boost libraries: boost_filesystem No Boost libraries were found. You may need to set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost. </code></pre> <p>If I try to include a header file and run it I get a very big error.</p> <pre><code>C:\Users\aksha\.CLion2016.2\system\cygwin_cmake\bin\cmake.exe --build "C:\Users\aksha\.CLion2016.2\system\cmake\generated\DeSNN CPP-4334ec6a\4334ec6a\Debug" --target DeSNN_CPP -- -j 4 [ 25%] Linking CXX executable DeSNN_CPP.exe CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `__static_initialization_and_destruction_0': C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:221: undefined reference to `boost::system::generic_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:221:(.text+0x1ba): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::system::generic_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:222: undefined reference to `boost::system::generic_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:222:(.text+0x1c6): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::system::generic_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:223: undefined reference to `boost::system::system_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:223:(.text+0x1d2): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::system::system_category()' CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `boost::filesystem::path_traits::convert(wchar_t const*, wchar_t const*, std::string&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:938: undefined reference to `boost::filesystem::path::codecvt()' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:938:(.text$_ZN5boost10filesystem11path_traits7convertEPKwS3_RSs[_ZN5boost10filesystem11path_traits7convertEPKwS3_RSs]+0x15): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::path::codecvt()' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:938: undefined reference to `boost::filesystem::path_traits::convert(wchar_t const*, wchar_t const*, std::string&amp;, std::codecvt&lt;wchar_t, char, _mbstate_t&gt; const&amp;)' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:938:(.text$_ZN5boost10filesystem11path_traits7convertEPKwS3_RSs[_ZN5boost10filesystem11path_traits7convertEPKwS3_RSs]+0x32): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::path_traits::convert(wchar_t const*, wchar_t const*, std::string&amp;, std::codecvt&lt;wchar_t, char, _mbstate_t&gt; const&amp;)' CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `boost::filesystem::path_traits::convert(char const*, std::basic_string&lt;wchar_t, std::char_traits&lt;wchar_t&gt;, std::allocator&lt;wchar_t&gt; &gt;&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:946: undefined reference to `boost::filesystem::path::codecvt()' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:946:(.text$_ZN5boost10filesystem11path_traits7convertEPKcRSbIwSt11char_traitsIwESaIwEE[_ZN5boost10filesystem11path_traits7convertEPKcRSbIwSt11char_traitsIwESaIwEE]+0x37): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::path::codecvt()' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:946: undefined reference to `boost::filesystem::path_traits::convert(char const*, char const*, std::basic_string&lt;wchar_t, std::char_traits&lt;wchar_t&gt;, std::allocator&lt;wchar_t&gt; &gt;&amp;, std::codecvt&lt;wchar_t, char, _mbstate_t&gt; const&amp;)' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:946:(.text$_ZN5boost10filesystem11path_traits7convertEPKcRSbIwSt11char_traitsIwESaIwEE[_ZN5boost10filesystem11path_traits7convertEPKcRSbIwSt11char_traitsIwESaIwEE]+0x52): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::path_traits::convert(char const*, char const*, std::basic_string&lt;wchar_t, std::char_traits&lt;wchar_t&gt;, std::allocator&lt;wchar_t&gt; &gt;&amp;, std::codecvt&lt;wchar_t, char, _mbstate_t&gt; const&amp;)' CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `boost::filesystem::exists(boost::filesystem::path const&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:446: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&amp;, boost::system::error_code*)' C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:446:(.text$_ZN5boost10filesystem6existsERKNS0_4pathE[_ZN5boost10filesystem6existsERKNS0_4pathE]+0x1e): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::detail::status(boost::filesystem::path const&amp;, boost::system::error_code*)' CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `boost::filesystem::is_directory(boost::filesystem::path const&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:451: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&amp;, boost::system::error_code*)' C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:451:(.text$_ZN5boost10filesystem12is_directoryERKNS0_4pathE[_ZN5boost10filesystem12is_directoryERKNS0_4pathE]+0x1e): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::detail::status(boost::filesystem::path const&amp;, boost::system::error_code*)' CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `boost::filesystem::is_regular_file(boost::filesystem::path const&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:456: undefined reference to `boost::filesystem::detail::status(boost::filesystem::path const&amp;, boost::system::error_code*)' C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:456:(.text$_ZN5boost10filesystem15is_regular_fileERKNS0_4pathE[_ZN5boost10filesystem15is_regular_fileERKNS0_4pathE]+0x1e): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::filesystem::detail::status(boost::filesystem::path const&amp;, boost::system::error_code*)' CMakeFiles/DeSNN_CPP.dir/main.cpp.o: In function `boost::filesystem::file_size(boost::filesystem::path const&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:614: undefined reference to `boost::filesystem::detail::file_size(boost::filesystem::path const&amp;, boost::system::error_code*)' C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:614:(.text$_ZN5boost10filesystem9file_sizeERKNS0_4pathE[_ZN5boost10filesystem9file_sizeERKNS0_4pathE]+0x16): additional relocation overflows omitted from the output CMakeFiles/DeSNN_CPP.dir/FileReader.cpp.o: In function `FileReader::list_dir()': /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/DeSNN CPP/FileReader.cpp:41: undefined reference to `boost::filesystem::path::filename() const' CMakeFiles/DeSNN_CPP.dir/FileReader.cpp.o: In function `__static_initialization_and_destruction_0': C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:221: undefined reference to `boost::system::generic_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:222: undefined reference to `boost::system::generic_category()' C:/Program Files/boost/boost_1_62_0/boost/system/error_code.hpp:223: undefined reference to `boost::system::system_category()' CMakeFiles/DeSNN_CPP.dir/FileReader.cpp.o: In function `boost::filesystem::path_traits::convert(char const*, char const*, std::basic_string&lt;wchar_t, std::char_traits&lt;wchar_t&gt;, std::allocator&lt;wchar_t&gt; &gt;&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:930: undefined reference to `boost::filesystem::path::codecvt()' C:/Program Files/boost/boost_1_62_0/boost/filesystem/path.hpp:930: undefined reference to `boost::filesystem::path_traits::convert(char const*, char const*, std::basic_string&lt;wchar_t, std::char_traits&lt;wchar_t&gt;, std::allocator&lt;wchar_t&gt; &gt;&amp;, std::codecvt&lt;wchar_t, char, _mbstate_t&gt; const&amp;)' CMakeFiles/DeSNN_CPP.dir/FileReader.cpp.o: In function `boost::filesystem::detail::dir_itr_imp::~dir_itr_imp()': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:872: undefined reference to `boost::filesystem::detail::dir_itr_close(void*&amp;)' CMakeFiles/DeSNN_CPP.dir/FileReader.cpp.o: In function `boost::filesystem::directory_iterator::directory_iterator(boost::filesystem::path const&amp;)': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:903: undefined reference to `boost::filesystem::detail::directory_iterator_construct(boost::filesystem::directory_iterator&amp;, boost::filesystem::path const&amp;, boost::system::error_code*)' CMakeFiles/DeSNN_CPP.dir/FileReader.cpp.o: In function `boost::filesystem::directory_iterator::increment()': C:/Program Files/boost/boost_1_62_0/boost/filesystem/operations.hpp:939: undefined reference to `boost::filesystem::detail::directory_iterator_increment(boost::filesystem::directory_iterator&amp;, boost::system::error_code*)' collect2: error: ld returned 1 exit status make[3]: *** [CMakeFiles/DeSNN_CPP.dir/build.make:147: DeSNN_CPP.exe] Error 1 make[2]: *** [CMakeFiles/Makefile2:68: CMakeFiles/DeSNN_CPP.dir/all] Error 2 make[1]: *** [CMakeFiles/Makefile2:80: CMakeFiles/DeSNN_CPP.dir/rule] Error 2 make: *** [Makefile:118: DeSNN_CPP] Error 2 </code></pre> <p>I have no idea what's going on here. Any idea on how to overcome this problem?</p> <p><strong>Update</strong></p> <p>I managed to get the following done, but still can't find the libs</p> <pre><code>Warning:start running cmake... Warning:Setting up BOOST Warning:Includes - C:/Users/aksha/Desktop/boost_1_62_0 Warning:Library - C:/Users/aksha/Desktop/boost_1_62_0/stage/lib </code></pre>
<p>You told it where to look for library files, but didn't tell it which ones to look for.</p> <p>You need to add </p> <pre><code>target_link_libraries(DeSNN_CPP ...list of boost libraries...) </code></pre> <p>to your CMakeLists.txt file</p>
Javascript load multiple csv and create global reachable array <p>I need to load a lot of csv files. Yet Im loading with this function.</p> <pre><code>$.ajax({ url: 'my.csv', dataType: 'text', }).done(successFunction); </code></pre> <p>Then I run successFunction, with that I create array and with same code as above, but with different name of function I create another array and so on. Thats o lot of same code. What is the simpliest way to load multiple csv and return array?</p> <p><strong>Important</strong> I need to sometimes create 2 dimensional array another time 5 etc. So function must include parameter for that. </p> <p>For creating array im using function like this:</p> <pre><code>function successFunction(data) { var promenna = data.replace(/\n/g,";").split(";"); var result = []; for (var i = 0; i &lt; promenna.length; i+=2) { var line = []; line.push(promenna[i]); line.push(promenna[i+1]); result.push(line); } for (var i = 0; i &lt; result.length; i += 1){ $("#tyden" + i + "").append(result[i][0]); $("#tyden" + i + "kolik").append(result[i][1]); } } </code></pre> <p>But for another file I repeating basicly the same code. I don't know how to use one function for all files. </p>
<p>First off, I disrecommend using your own CSV parser. This problem has been solved, use <a href="https://github.com/gkindel/CSV-JS" rel="nofollow">a library</a>.</p> <p>The other part of the problem is <em>"I need to load many files via HTTP with jQuery"</em>, and that's easy.</p> <ol> <li>Prepare a list of file urls.</li> <li>Turn that into a list of requests. <ul> <li>You can use jQuery's <code>.then()</code> to transform the incoming data on the fly.</li> <li>In this case, passing it through the CSV parser would be the transformation.</li> <li>You can use jQuery's <code>.done()</code> to handle responses individually, as they come in.</li> </ul></li> <li>Optional: Wait for the requests to complete. <ul> <li>You can use jQuery's <code>.when()</code> to wait on multiple async operations.</li> <li>You can use jQuery's <code>.done()</code> to handle responses collectively.</li> </ul></li> </ol> <p>So:</p> <pre><code>var files = ['csv1.txt', 'csv2.txt', 'csv3.txt', 'csvN.txt']; var requests = $.map(files, function (i, url) { return $.get(url).then(CSV.parse); }); $.when.apply($, requests) .done(function (csvObjects) { // everything has loaded successfully $.each(csvObjects, function (i, csv) { // do something with each file }); }) .fail(function (jqXhr, status, error) { // something went wrong, handle the error }); </code></pre> <p>Necessary reading: <a href="https://api.jquery.com/category/deferred-object/" rel="nofollow">https://api.jquery.com/category/deferred-object/</a></p>
insert into database from angularjs using c# <p>i am creating a web app in which i need to insert into the table from my web app i am using angularjs for speeding up my app but i am not able to fire the insert query properly</p> <p>here is my code</p> <pre><code>&lt;body &gt; &lt;div ng-app="myApp" ng-controller="customersCtrl"&gt; &lt;input type="text" ng-model="tid" /&gt; &lt;input type="text" ng-model="userid" /&gt; &lt;input type="text" ng-model="pass" /&gt; &lt;input type="text" ng-model="name" /&gt; &lt;input type="text" ng-model="designation" /&gt; &lt;input type="text" ng-model="team" /&gt; &lt;input type="button" ng-click="insadmin()" value="Insert" /&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; var app = angular.module('myApp', []); app.controller('customersCtrl', function ($scope, $http) { $scope.insadmin = function () { $scope.names = ''; $http.get('/csuv5.asmx/tadmin', { params: { tid: $scope.tid, userid: $scope.userid, pass: $scope.pass, name: $scope.name, designation: $scope.designation, team:$scope.team } }) .then(function (response) { $scope.sonvinrpm = response.data.page; console.log(response.data.page); }); } }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p>sources of angularjs and bootstrap</p> <pre><code>&lt;!-- Latest compiled and minified CSS --&gt; &lt;link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /&gt; &lt;!-- jQuery library --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Latest compiled JavaScript --&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"&gt;&lt;/script&gt; &lt;link href="glyphicons.css" rel="stylesheet" type="text/css"&gt; &lt;link href="animations.css" rel="stylesheet" type="text/css"&gt; &lt;link href="css/erp-css.css" rel="stylesheet" /&gt; </code></pre> <p>and i am using webservice for inserting the data here is my webservice</p> <pre><code>[WebMethod] [ScriptMethod(UseHttpGet = true)] public void tadmin(string tid, string userid, string pass, string name, string designation, string team) { List&lt;object&gt; daterange = new List&lt;object&gt;(); SqlCommand cmd = new SqlCommand("insert into admin(tid,userid,pass,name,designation,team) values '" + tid + "','" + userid + "','" + pass + "','" + name + "','" + designation + "','" + team + "'", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } </code></pre> <p>i checked webservice it is working fine i need to find out what is wrong in my code</p> <p>any idea?</p>
<p>Try this:</p> <pre><code>public void tadmin(string tid, string auserid, string bpass, string cname, string ddesignation, string eteam) { SqlCommand cmd = new SqlCommand("insert into admin(tid,userid,pass,name,designation,team) values(@tid,@userid,@pass,@name,@designation,@team)", con); cmd.Parameters.AddWithValue("@tid", tid); cmd.Parameters.AddWithValue("@userid", auserid); cmd.Parameters.AddWithValue("@pass", bpass); cmd.Parameters.AddWithValue("@name", cname); cmd.Parameters.AddWithValue("@designation", ddesignation); cmd.Parameters.AddWithValue("@team", eteam); con.Open(); cmd.ExecuteNonQuery(); Context.Response.Write("success"); con.Close(); } </code></pre>
How is handled auto fill form in Vaadin Framwork <p>I need to fix error in form. when user enters a birth number. It based on this information fills textfields for sex/ date birth. It is created in Vaadin. Did i miss something. How does it know what is entered and how does it parse ? Is it doing parsing? </p>
<p>My bad, i should have to check method for pre - validation first. At the time i asked this, i didn´t know how it is being implemented. Simple parser was used but one check method prevented that from execution. Thanks though.</p>
use notifyDataSetChanged(); after updating SQLite from other activity and inside the same activity <p>Good day,<br> Summary : I am making a sample memo app with SQLite as its database. </p> <p><strong>MainActivity</strong> </p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); lv = (ListView)findViewById(R.id.memo_list_view); Cursor c = SplashActivity.db.rawQuery("SELECT * FROM memos", null); if(c.getCount()!=0) { while(c.moveToNext()) { memoDetails = new MemoDetails(); memoDetails.setmMemoId(c.getString(0)); memoDetails.setmMemoTitle(c.getString(1)); memoDetails.setmCreatedDate(c.getString(3)); memoDetails.setmAlarmedDate(c.getString(4)); memos.add(memoDetails); } c.close(); customAdapter = new CustomAdapter(this, memos); lv.setAdapter(customAdapter); } @Override protected void onResume() { super.onResume(); customAdapter.notifyDataSetChanged(); } </code></pre> <p>Then this is the activity where I add my memo </p> <p><strong>AddMemoActivity</strong> (this is the listener I use) </p> <pre><code> saveMemo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v1) { if(memoTitle.getText().toString().trim().length() == 0 || memoContent.getText().toString().trim().length() == 0) { showMessage("Error", "Please Enter All Values"); } else { SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss"); String currentDateandTime = sdf.format(new Date()); SplashActivity.db.execSQL("INSERT INTO memos VALUES(null,'" + memoTitle.getText() + "','" + memoContent.getText() + "','" + currentDateandTime + "','" + currentDateandTime + "','0');"); showMessage("Success", "Memo is Saved."); } } }); </code></pre> <p>On this "Adding Memo" part, my problem is when I leave my <strong>AddMemoActivity</strong> and return to my <strong>MainActivty</strong>, it doesn't update my listview. </p> <p>Second is my delete part, </p> <p><strong>MainActivity</strong> </p> <pre><code> findViewById(R.id.del_memo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v1) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: String deleteIds = null; for (MemoDetails p : customAdapter.getBox()) { if (p.mCheckBox){ if(deleteIds == null) { deleteIds = p.getmMemoId(); } else { deleteIds += ", " + p.getmMemoId(); } } } SplashActivity.db.execSQL("DELETE FROM memos WHERE id IN ('"+deleteIds+"')"); customAdapter.notifyDataSetChanged(); Toast.makeText(getApplicationContext(), deleteIds, Toast.LENGTH_LONG).show(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(MemoListActivity.this); builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } }); </code></pre> <p>As you can see, I already added <strong>customAdapter.notifyDataSetChanged();</strong> after deletion but still no update. </p> <p>Thanks in advanced.</p>
<p>Listview doesnt update by updating DB. You need to update the list you gave the adapter and then call notifyDataChange().</p> <p>So update the list you gave the listview's udapter everytime you change the DB data.</p> <p>Just update the <code>memos</code> list then call notify data change.</p>
Setting font in Android <p>In android Using <code>setTypeface</code> method we can set the font to the control of our wish programmatically, but i want to know is there a way we can avoid this and set the font in layout XML file itself?</p> <p>I Just want to specify the path of the file &amp; font should get updated automatically.</p>
<p>You can use <a href="https://github.com/chrisjenx/Calligraphy" rel="nofollow">Calligraphy</a> library where you can specify font in XML itself.</p> <pre><code>&lt;TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" fontPath="fonts/Roboto-Bold.ttf"/&gt; </code></pre>
Nonstatic Member Reference with "std::cout" in Header <p>I'm sort of new to C++, and I've been making my way through a bit in my own project. I ran into an error with this header and .cpp file</p> <hr> <pre><code>// main.cpp #include &lt;iostream&gt; #include "Header.h" int main() { MyClass::TestFunction(); //'MyClass::TestFunction': illegal call of non-static member function } </code></pre> <hr> <pre><code>// header.h #ifndef HEADER_H #define HEADER_H #include &lt;iostream&gt; class MyClass { public: void TestFunction() { std::cout &lt;&lt; "Hello World\n"; //Where I beleive the issue is } }; #endif </code></pre> <hr> <p>Now I <em>think</em> the issue comes from <code>std::cout</code> not being static and the declaration in <code>main.cpp</code> needs it to be static, but I'm not sure how to make it static so that <code>main.cpp</code> works correctly. If anyone could give me a tip as to how I can make things like this work later on down the road, that would be awesome :)</p>
<blockquote> <p>the issue comes from std::cout not being static and the declaration in main.cpp needs it to be static</p> </blockquote> <p>You either have to make your function static OR to intanciate an object of your class and hen call its function :</p> <p>main.cpp</p> <pre><code>int main() { MyClass pony; pony.TestFunction(); } </code></pre> <p>OR</p> <p>header.h</p> <pre><code>class MyClass { public: static void TestFunction() { std::cout &lt;&lt; "Hello World\n"; //@Gill Bates } }; </code></pre>
Sending push notifications's token to the server. Alamofire error <p>I'm trying to send token which I got in <code>didRegisterForRemoteNotificationsWithDeviceToken</code> to the server. But I got an error while sending: <code>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation._SwiftNSData)</code>. For requests I use <code>Alamofire</code> framework. My code:</p> <pre><code>func signUp(withToken token: Data, completion: (Error) -&gt; Void) { let parameters: Parameters = ["registration_id": token] print("token = \(token)") Alamofire.request(baseUrl + signUpPath, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: {response in }) } </code></pre> <p><code>Print</code> shows me: <code>token = 32 bytes</code>. Any suggestions? Maybe I need some additional steps with <code>Data</code> type before send it to the server?</p> <p><strong>UPDATE</strong></p> <p>I have tried to convert token to <code>NSString</code> type but got <code>nil</code></p> <pre><code>let tokenNSString: NSString? = NSString(data: token, encoding: String.Encoding.utf8.rawValue) print("nsstrgin from token = \(tokenNSString)") </code></pre>
<p>The <code>deviceToken</code> you are getting inside your project's appDelegate <code>didRegisterForRemoteNotificationsWithDeviceToken</code> is an <code>NSData</code> object. To extract the actual token String from that <code>NSData</code> object use this following code.</p> <pre><code> let tokenChars = UnsafePointer&lt;CChar&gt;(deviceToken.bytes) var tokenString: String = "" for i in 0..&lt;deviceToken.length { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } print("This is My Device Token for Push notification -", tokenString) </code></pre> <p>Now, <code>tokenString</code> is your actual token which you are looking for. Try to send this to your server along with any key.</p> <p>BTW I am using Xcode 7.3.1 with Swift 2.2. Please feel free to modify this as per your requirements.</p> <p>Thanks, Hope this helped.</p>
ImportError: No module named 'bs4' in django only <p>The same question has been asked a number of times but I couldn't find the solution.</p> <p>After I install a package using pip, I am able to import it in python console or python file and it works as expected. The same package when I try to include in django, it gives <code>import error</code>. Do I need to modify <code>settings.py</code> file or any requirement that I need to add? I am driving django with the help of virtual env. </p> <p>Eg: I am using <code>BeautifulSoup</code> and I am trying to import <code>from bs4 import BeautifulSoup</code> and I am getting error <code>ImportError: No module named 'bs4'</code></p> <p>This error only comes in django. I am not able to figure out why this is happening.</p> <p>Screenshot attached for reference.</p> <p><strong>1. python console - shows no error</strong></p> <p><a href="http://i.stack.imgur.com/exmvN.png" rel="nofollow"><img src="http://i.stack.imgur.com/exmvN.png" alt="python2 and python3 console"></a></p> <p><strong>2. django console- import error</strong></p> <p><a href="http://i.stack.imgur.com/j0IMN.png" rel="nofollow"><img src="http://i.stack.imgur.com/j0IMN.png" alt="django console"></a></p> <p><em>I am sorry as it is difficult to read the console but any other thing that I can include which will help me make myself more clear will be appreciated.</em> </p>
<p>You don't show either the code of your site or the command you ran (and the URL you entered, if any) to trigger this issue. There's almost certainly some difference between the Python environment on the command line and that operating in Django.</p> <p>Are you using virtual environments? If so, dependencies should be separately added to each environment. Were you operating from a different working directory? Python usually has the current directory somewhere in <code>sys.path</code>, so if you changed directories it's possible you made <code>bs4</code> unavailable that way.</p> <p>At the interactive Python prompt, try</p> <pre><code>import bs4 bs4.__file__ </code></pre> <p>That will tell you where <code>bs4</code> is being imported from, and might therefore give you a clue as to why it's not available to Django.</p>
Android XML layout messed up? <p><a href="http://pastebin.com/T0HgiRTA" rel="nofollow">XML Link</a></p> <p>I am designing an app with multiple buttons, but it isn't working properly. </p> <p><strong>This is how it shows in Android studio</strong> <a href="http://i.stack.imgur.com/lkf5P.png" rel="nofollow"><img src="http://i.stack.imgur.com/lkf5P.png" alt="How it shows in the Android studio"></a></p> <p><strong>This is how it shows in the emulator</strong> <a href="http://i.stack.imgur.com/tSd87.png" rel="nofollow"><img src="http://i.stack.imgur.com/tSd87.png" alt="enter image description here"></a></p>
<p>Possible reason for this could be you have multiple layout files for various screen density / screen dimensions / android version.</p> <p>Check your layout folder and ensure there is not multiple lauout files in multiple folders ;)</p>
Correct header for copying HTML on the clipboard <p>I have a complete HTML document and need to copy it on the clipboard so that it can be pasted into Microsoft Word and other applications. Now I figured out that the obvious way doesn't work and I need to add a special header before the HTML content. Unfortunately all samples seem to show invalid header data so that I can't learn from it. And all I can find is cryptic sample code that handles all sorts of complicated use cases, still that doesn't help me. And there isn't a readable explanation of the header numbers anywhere.</p> <p>So here's a sample HTML document that I have as string in .NET:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Col 1&lt;/td&gt; &lt;td&gt;Col 2&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If this fragment thing is really required, I might add those comments in my document just inside the <code>&lt;body&gt;</code> element.</p> <p>The header is supposed to look somehow like this:</p> <pre><code>Version:0.9 StartHTML:1 EndHTML:2 StartFragment:3 EndFragment:4 StartSelection:3 EndSelection:4 </code></pre> <p>What are the correct numbers for 1, 2, 3, and 4? How are they calculated, considering UTF-8 encoding and all that's required? Please provide a plain text description or algorithm, or simple C# code for only this simple case, nothing fancy with bells and whistles. I can adapt from there.</p>
<p>Okay, so I figured out that the fragment thing is not required. The header has the following numbers:</p> <ul> <li>1 and 3: The length of the header itself (zero-padding is necessary to achieve predictable results, otherwise the header length changes after putting in the numbers, making the numbers invalid)</li> <li>2 and 4: The length of the header + the number of UTF-8 bytes of the entire HTML document</li> </ul> <p>This can be pasted into Word and Excel. No fragments or HTML comments required.</p> <p>Sample C# code:</p> <pre><code>int start = header.Length; int end = header.Length + Encoding.UTF8.GetByteCount(html); </code></pre>
Make sure sub directories don't listen to mod rewrite <p>I am using some dynamic pages on every .html file in my root.</p> <p>With the following line:</p> <pre><code>RewriteRule ^(.*).html content.php?alias=$1 [L] </code></pre> <p>This works fine, but I also got some other websites on the same location, only a few folders down. I don't want them to listen to this line, everytime I create a .html file, I get redirect to content.php in my root.</p> <p>Example:</p> <p>Location of my content.php:</p> <pre><code>public_html/Website/content.php public_html/Website/_intern/websites/index.html </code></pre> <p>The above file gets redirected to the content.php in my root.</p> <p>How can I prevent that from happening?</p>
<p>Tweak your regex. Instead of <code>.*</code> which matches anything you should use <code>[^/]+</code> to match anything but <code>/</code>. This ensures, you don't select anything in sub-directories:</p> <pre><code>RewriteRule ^([^/]+)\.html$ content.php?alias=$1 [L,QSA,NC] </code></pre>
Disable tax programmatically for a specific user role <p>In my woocommerce web site, I have enable Tax in general WooCommerce settings.</p> <p>I would like to disable tax for a specific user role programmatically ( with any hooks ), from my shop, checkout page and from order email.</p> <p>How could I achieve this?</p> <p>Thanks</p>
<blockquote> <p>You can't disable WooCommerce tax for a specific user role programmatically, <strong>but you can apply for a specific user role a zero tax rate.</strong></p> </blockquote> <p>First you need to have this specific user role set in worpress. If it's the case, let say that this custom user role is <strong><code>'resellers'</code></strong> for my code example.</p> <p>Second, you have to enable in WooCommerce settings a <strong>zero tax rate</strong>:</p> <p><a href="http://i.stack.imgur.com/apAxb.png" rel="nofollow"><img src="http://i.stack.imgur.com/apAxb.png" alt="enter image description here"></a></p> <p>And then for each country, you will have to set this <strong>zero tax rate</strong>:</p> <p><a href="http://i.stack.imgur.com/6wF3e.png" rel="nofollow"><img src="http://i.stack.imgur.com/6wF3e.png" alt="enter image description here"></a></p> <p>Third - Then this function hooked in <strong><code>woocommerce_product_tax_class</code></strong> will do the trick:</p> <pre><code>function zero_rate_for_custom_user_role( $tax_class, $product ) { // Getting the current user $current_user = wp_get_current_user(); $current_user_data = get_userdata($current_user-&gt;ID); // &lt;== &lt;== &lt;== &lt;== &lt;== &lt;== &lt;== Here you put your user role slug if ( in_array( 'resellers', $current_user_data-&gt;roles ) ) $tax_class = 'Zero Rate'; return $tax_class; } add_filter( 'woocommerce_product_tax_class', 'zero_rate_for_custom_user_role', 1, 2 ); </code></pre> <blockquote> <p>You will just need to put instead of 'resellers' your desired user role slug.</p> </blockquote> <p><em>This code goes in function.php file of your active child theme (or theme) or also in any plugin file.</em></p> <p>This code is tested and fully functional.</p> <p>Reference: <a href="http://stackoverflow.com/questions/39836170/woocommerce-enabling-zero-rate-tax-class-to-some-specific-user-roles/39838828#39838828">WooCommerce - Enabling &quot;Zero rate&quot; tax class to some specific user roles</a></p>
Laravel eloquent - filter by concatenation of multiple columns <p>I'm new to Laravel, and I got stuck trying to perform the following. I have a simple users table with the following columns: </p> <ul> <li><code>id</code></li> <li><code>first_name</code></li> <li><code>last_name</code></li> </ul> <p>I'm about to make a user list with an option of filtering. One of the filters is <code>full_name</code>, but I do not store <code>full_name</code> of the users, and I can't modify the table structure.</p> <p>Over a few days I got to this:</p> <pre><code>$query = \DB::table('users'); $query-&gt;select(\DB::raw('CONCAT_WS(" ", `last_name`, `first_name`) as `full_name`, id'))-&gt;having('full_name', 'LIKE',$input['filter_name']); $result = $query-&gt;get(['*']); </code></pre> <p>But it's not working. </p> <p><strong>Spec</strong>: I'm using the latest laravel. </p>
<p>I think you forgot the wildcards in the LIKE statement.</p> <p>Instead of this</p> <pre><code>$query-&gt;select(\DB::raw('CONCAT_WS(" ", `last_name`, `first_name`) as `full_name`, id'))-&gt;having('full_name', 'LIKE',$input['filter_name']); </code></pre> <p>Try:</p> <pre><code>$query-&gt;select(\DB::raw('CONCAT_WS(" ", `last_name`, `first_name`) as `full_name`, id'))-&gt;having('full_name', 'LIKE', '%' . $input['filter_name'] . '%'); </code></pre>
How to create toggleable sidenav layout in React.js? <p>I am porting my layout from jQuery to React.js. This is very common one that consists of:</p> <ul> <li>header with toggle button</li> <li>sidenav with navigation links</li> <li>content whose width adapts to sidenav state.</li> </ul> <p>As you can imagine to achieve that a lot of (css) stuff is going on. I am really confused about possible approaches.</p> <p>Here is mine:</p> <pre><code>class CoreLayout extends Component { constructor(props) { super(props) this.state = { sidenavCollapsed: false } } onSidenavToggle() { const { sidenavCollapsed } = this.state document.body.classList.toggle('collapsed', !sidenavCollapsed) this.setState({ sidenavCollapsed: !sidenavCollapsed }) } render() { const { sidenavCollapsed } = this.state return ( &lt;div&gt; &lt;Header onSidenavToggle={::this.onSidenavToggle}&gt;&lt;/Header &lt;Sidenav&gt; &lt;div className="content"&gt;content&lt;/div&gt; &lt;/div&gt; ) } } </code></pre> <p>I do all the styling according to class attached to body element:</p> <pre><code>.collapsed .header {} .collapsed .sidenav {} .collapsed .content {} </code></pre> <p>Basically it's toggling sidenav width and content margin betwen 220 and 60.</p> <p><strong>So...</strong></p> <p>Should I pass collapsed property to each of layout elements and add class <code>collapsed</code> separately? What I am trying to achieve is <a href="http://demo.naksoid.com/elephant/flaming-red/" rel="nofollow">similar to this</a>.</p> <p>What is the correct way of doing <code>fade-out-in</code> sidenav items animation? Till now I was using jQuery utilities, but I am not sure if directly using <code>window.requestAnimationFrame()</code> is correct. I have tried <code>ReactCSSTransitionGroup</code> with no success.</p>
<p>Just add a <code>class</code> to the navbar on button toggle and animate the transition using css.</p> <p>See the demo</p> <p><a href="https://jsfiddle.net/kuLy0g8z/" rel="nofollow">https://jsfiddle.net/kuLy0g8z/</a> </p>
On redash how to create a chart that shows counts of types <p>I am trying to create something similar to the example here:</p> <p><a href="http://demo.redash.io/embed/query/387/visualization/518?api_key=cc11cd75d4f3934b17de1f0621abd2f0c9cce713" rel="nofollow">http://demo.redash.io/embed/query/387/visualization/518?api_key=cc11cd75d4f3934b17de1f0621abd2f0c9cce713</a></p> <p>But I can not figure it out. If someone can explain how to create this specific chart it would be great.</p> <p>You can assume I am using a similar dataset and query with mongodb.</p> <p>This is the demo link with the query: <a href="http://demo.redash.io/queries/387/source#518" rel="nofollow">http://demo.redash.io/queries/387/source#518</a></p>
<p>The steps are:</p> <ol> <li>You write the query, run it and get the results.</li> <li>Click on "+ New Visualization" (next to the table header).</li> <li>Define your chart/visualization.</li> </ol> <p>But it's really hard to understand what part you can't figure out - do you have problem getting the results? Defining the chart?</p> <p>In the future, it's better to use the <a href="https://discuss.redash.io" rel="nofollow">Redash's forum</a> for such questions, as I stumbled at this question by chance.</p>
Format of a monetary number <p>I created a small currency converter. By cons I do not know how to give it a format with thousand separator. for example, the result is 10 000 000. 10 I would like to thank you if you can advise me. Below is my code</p> <pre><code>class ChangeViewController: UIViewController { @IBOutlet weak var usdamount: UITextField! @IBOutlet weak var label: UILabel! var noImput = "Merci de saisir une valeur" var currencynum = Int() override func viewDidLoad() { super.viewDidLoad() label.text = "" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // rejet du clavier override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?){ view.endEditing(true) super.touchesBegan(touches, with: event) } @IBAction func currency(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex{ case 0: currencynum = 0 break case 1: currencynum = 1 break default: break } } @IBAction func convert(_ sender: AnyObject) { if usdamount.text == "" { label.text = noImput } else { let num = Int(usdamount.text!) switch currencynum { case 0: let convertednum = Double(num!) * 14500 label.text = "\(num!) Euro(s) = \(convertednum) Rupiah(s)" break case 1: let convertednum = Double(num!) * 0.000067 label.text = "\(num!) Rupiah = \(convertednum) Euros" break default: break } } } } </code></pre>
<p>Hello swift already has a currency UI style, for your case</p> <p><strong>SWIFT 3</strong></p> <pre><code> let amount = Int(usdamount.text!) let numberFormatter = NumberFormatter() numberFormatter.currencyCode = "USD" numberFormatter.numberStyle = NumberFormatter.Style.currency let newValue = numberFormatter.string(from: NSNumber(value: amount!)) print(newValue) </code></pre> <p><strong>SWIFT 2</strong></p> <pre><code> let amount = Int(usdamount.text!) let numberFormatter = NSNumberFormatter() numberFormatter.currencyCode = "EUR" numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle let newValue = numberFormatter.stringFromNumber(amount)! print(newValue) </code></pre> <p><a href="http://i.stack.imgur.com/yIhNV.png" rel="nofollow"><img src="http://i.stack.imgur.com/yIhNV.png" alt="enter image description here"></a></p>
Explicitly set the storage path of an image clicked using Cordova API <p>I am extremely new to Cordova and am working on the Android platform. I need to store an image in a custom location. The <code>navigator.camera.getPicture</code> method stores the clicked image in the cache, but I need to store that image in a custom folder in the root. How can I accomplish this? Any suggestions in this regard will be appreciated.</p>
<p>Camera plugin store data in Android/Data/my.package.com/ directory.This directory is always accessible from your app even if you didn't grant read/write permission in manifest file of Android.It is always safe to do this while developing a API. If you still you want to change and store file at custom location then create your own plugin to achieve this.</p>
Fos Elastica remove common words(or, and etc..) from search query <p>Hello I`m trying to get query results using FosElasticaBundle with this query, I can't find a working example for filtering common words like (and, or) if it is possible this words not to be highlighted also would be really good. My struggle so far :</p> <pre><code> $searchForm = $this-&gt;createForm(SearchFormType::class, null); $searchForm-&gt;handleRequest($request); $matchQuery = new \Elastica\Query\Match(); $matchQuery-&gt;setField('_all', $queryString); $searchQuery = new \Elastica\Query(); $searchQuery-&gt;setQuery($matchQuery); $searchQuery-&gt;setHighlight(array( "fields" =&gt; array( "title" =&gt; new \stdClass(), "content" =&gt; new \stdClass() ), 'pre_tags' =&gt; [ '&lt;strong&gt;' ], 'post_tags' =&gt; [ '&lt;/strong&gt;' ], 'number_of_fragments' =&gt; [ '0' ] )); </code></pre> <p>Thanks in advance ;)</p>
<p>Do you want (and, or) to be ignored or not to have a value on your search? If that's the case you may want to use stop words on your elasticsearch index. Here's a reference. <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/using-stopwords.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/guide/current/using-stopwords.html</a></p>
VBA Code - Skip some parts if some others are excecuted <p>I have written this piece of code but have gutted out the additional filler in between. Depending on time points selected, it will hide the appropriate rows.</p> <p>Container 1 will always be filled, however, if another container is not selected, I want it to hide all the remaining rows without processing the rest of the code. So if Container 1 and 2 are selected, it will run the code for these without running the rest of the code.</p> <p>Rewriting this as loop would be incredibly complex as there are so many possible timepoints, it is more an issue of skipping the code that is not relevant. Almost like a goto line or something? I don't know!</p> <p>Is there any other way to make this code run more efficiently than temporarily disabling the DisplayPageBreaks, ScreenUpdating and Enable Events? There is no calculation performed on the page, only row hides.</p> <p>For Example, if Q26 is blank (No container 2) I want it to go to the end of the code without processing anything else but how I have written it, it still process the rest of the code.</p> <p>Thanks for your help</p> <pre><code>If Worksheets("StabDataCapture").Range("q26").Value = "" Then Worksheets("Template").Rows("142:1048576").EntireRow.Hidden = True Else </code></pre> <p>Thank you for you help!</p> <pre><code>Sub Containers() Dim xPctComp As Integer Application.StatusBar = "Container 1: " &amp; _ Format(xPctComp, "##0%") ActiveSheet.DisplayPageBreaks = False Application.EnableEvents = False Application.ScreenUpdating = False 'CONTAINER 1 ROW HIDES '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If Worksheets("StabDataCapture").Range("B33").Value = "" Then Worksheets("Template").Rows("8:8").EntireRow.Hidden = True End If Application.StatusBar = "Container 2: " &amp; _ Format(xPctComp, "##25%") If Worksheets("StabDataCapture").Range("q26").Value = "" Then Worksheets("Template").Rows("142:1048576").EntireRow.Hidden = True Else 'CONTAINER 2 ROW HIDES '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If Worksheets("StabDataCapture").Range("P33").Value = "" Then Worksheets("Template").Rows("146:146").EntireRow.Hidden = True End If Application.StatusBar = "Container 3: " &amp; _ Format(xPctComp, "##50%") 'CONTAINER 3 ROW HIDES If Worksheets("StabDataCapture").Range("c91").Value = "" Then Worksheets("Template").Rows("280:1048576").EntireRow.Hidden = True Else '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If Worksheets("StabDataCapture").Range("B98").Value = "" Then Worksheets("Template").Rows("284:284").EntireRow.Hidden = True End If Application.StatusBar = "Container 4: " &amp; _ Format(xPctComp, "##75%") If Worksheets("StabDataCapture").Range("q91").Value = "" Then Worksheets("Template").Rows("418:1048576").EntireRow.Hidden = True Else '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If Worksheets("StabDataCapture").Range("P98").Value = "" Then Worksheets("Template").Rows("422:422").EntireRow.Hidden = True End If Application.EnableEvents = True Application.ScreenUpdating = True Application.StatusBar = "" End Sub </code></pre>
<p>You need a routine to reactivate the screen and events, </p> <pre><code>Sub Restart_Screen() With Application .EnableEvents = True .ScreenUpdating = True .StatusBar = vbNullString End With End Sub </code></pre> <p>Using <code>Exit Sub</code>, it could look like this :</p> <pre><code>Sub test_vividillusion() Dim xPctComp As Integer Dim wS As Worksheet Dim wsT As Worksheet Set wS = Sheets("StabDataCapture") Set wsT = Sheets("Template") With Application .EnableEvents = False .ScreenUpdating = False .StatusBar = "Container 1: " &amp; Format(xPctComp, "##0%") End With ActiveSheet.DisplayPageBreaks = False 'CONTAINER 1 ROW HIDES '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If wS.Range("B33").Value = vbNullString Then wsT.Rows("8:8").EntireRow.Hidden = True Application.StatusBar = "Container 2: " &amp; Format(xPctComp, "##25%") If wS.Range("q26").Value = vbNullString Then wsT.Rows("142:1048576").EntireRow.Hidden = True Restart_Screen Exit Sub Else End If 'CONTAINER 2 ROW HIDES '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If wS.Range("P33").Value = vbNullString Then wsT.Rows("146:146").EntireRow.Hidden = True Application.StatusBar = "Container 3: " &amp; Format(xPctComp, "##50%") If wS.Range("c91").Value = vbNullString Then wsT.Rows("280:1048576").EntireRow.Hidden = True Restart_Screen Exit Sub Else End If 'CONTAINER 3 ROW HIDES '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If wS.Range("B98").Value = vbNullString Then wsT.Rows("284:284").EntireRow.Hidden = True Application.StatusBar = "Container 4: " &amp; Format(xPctComp, "##75%") If wS.Range("q91").Value = vbNullString Then wsT.Rows("418:1048576").EntireRow.Hidden = True Restart_Screen Exit Sub Else End If '@@@@@@@@@@@@@@@@@@@@@@@@@@@ 60°C @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 'Show/Hide 1@60 If wS.Range("P98").Value = vbNullString Then wsT.Rows("422:422").EntireRow.Hidden = True Restart_Screen End Sub </code></pre>
Retrieving data from file and storing in variable c# <p>I want to create a file in which I can write certain text and then store it in variables because I must change the text depending on the PC they are on.My question is what type of file should I write my text in? (.txt , .xml , .xls , .etc) I know you can do on any type you want but for what type of file is c# built to do such a task?</p> <p><p> To be more clearer (because I know I have a problem expressing what I want ) I will give an example.</p> <h3>Text file:</h3> <pre><code>SN:123321123 PCName:blabla Something.else:Text </code></pre> <p>And I would like to extract <code>123321123</code> and store it in a variable SN a.s.o. from my perspective I think I should store them in excel files to return them using <code>sheet.get_Range("first", last);</code> ,but I want to know if there is a simpler way?</p>
<p>Use XML, there is lots of support and documentation on how to do this online. Another arguably 'cleaner' result would be JSON. This uses a simple key value pair relationship which is similar to the example you posted. But both are good.</p> <p>XML Example:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;catalog&gt; &lt;book id="bk101"&gt; &lt;author&gt;Gambardella, Matthew&lt;/author&gt; &lt;title&gt;XML Developer's Guide&lt;/title&gt; &lt;genre&gt;Computer&lt;/genre&gt; &lt;price&gt;44.95&lt;/price&gt; &lt;publish_date&gt;2000-10-01&lt;/publish_date&gt; &lt;description&gt;XML example&lt;/description&gt; &lt;/book&gt; &lt;/catalog&gt; </code></pre> <p>JSON Example:</p> <pre><code>{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] } </code></pre>
Javascript - Create new Date using a UK format and moment.js <p>I have a date in UK format "DD/MM/YYYY HH:mm" and I want to create a new date with javascript. I'm trying the following using moment.js but it doesn't recognise the timepart and simply adds on the current time.</p> <pre><code> var myDate = "11/10/2016 09:00" // The toDate() is equivalent to the javascript new Date() function var newDate = moment(myDate, "YYYY-MM-DD HH:mm").val()).toDate(); // output: // 20161011T091406Z // Tue Oct 11 2016 09:14:06 GMT+0100 </code></pre> <p>As you can see its changed the time part to the time the script is run.</p>
<p>Figured it out myself by doing the following:</p> <pre><code>var myDate = "11/10/2016 09:00" myDate = moment(myDate, "DD/MM/YYYY HH:mm").toISOString(); var newDate = moment(myDate).toDate(); </code></pre>
Database Selection Via ComboBox <p>I have a <code>combobox</code> that I would like to use to select the database from a selection available to the user. I have found plenty of information on populating the fields with table values but nothing on making a selection on which <code>.dbo</code> they can use. I'm guessing the same principle can be used as below... but I would presume that (<code>database =</code>) needs to be taken out and replaced some how. any advice would be appreciated</p> <pre><code>var connectionString = "server = (local); database = database; integrated security = true;" string Sql = "select database..."; SqlConnection _con = new SqlConnection(connectionString); _con.Open(); SqlCommand cmd = new SqlCommand(Sql, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { combobox1.Items.Add(reader[0]); } </code></pre>
<p>You need this query;</p> <pre><code>string Sql = "SELECT * FROM sys.databases"; </code></pre>
Constraints getting changed when adding a view over window or navigation controller? <p>I had an application in which I need to display a custom status bar over all the application. For which I wrote this code in to the <code>didFinishLaunchingWithOptions:</code> method</p> <pre><code>self.window.windowLevel = UIWindowLevelStatusBar; </code></pre> <p>Then in the viewController I created a view with (0, 0, width, 20) frame view and added some elements to it.</p> <p>I am trying to add that view above the window like this</p> <pre><code>AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [self.statusview setTranslatesAutoresizingMaskIntoConstraints:YES]; [appdelegate.window addSubview:statusview]; </code></pre> <p>But it is getting added at the top left without having no elements. But when I am setting the width and adding the elements again then it is showing.</p> <p>Can anybody help me on this?</p>
<p>i think your problem is the view's width, make sure the width is right.</p> <p>if the width is right and the problem is still here, please update your code and screenshot.</p>
Button of a Fragment inside ViewPager trigger onClickListener on wrong reference <p>Sorry about my dumb title, I will describe it clearly below:</p> <p><strong>Situation</strong></p> <p>I have a <code>ViewPager</code> with 4 <code>OnBoardingFragment</code>s inside. Each <code>Fragment</code> have exactly same layout which was <code>inflated</code>from same xml file. This layout contain a <code>Button</code> which I called <code>btnNext</code> and I set the <code>OnClickListener</code> for it.</p> <p>Function <code>getItem</code> of my PagerAdapter</p> <pre><code>@Override public Fragment getItem(int position) { String title, description, button; int resource; boolean end = false; switch (position) { case 0: title = context.getString(R.string.on_boarding_title_1); description = context.getString(R.string.on_boarding_description_1); resource = R.drawable.on_boarding_bg_0; button = context.getString(R.string.on_boarding_button_1); break; case 1: title = context.getString(R.string.on_boarding_title_2); description = context.getString(R.string.on_boarding_description_2); resource = R.drawable.on_boarding_bg_1; button = context.getString(R.string.on_boarding_button_2); break; case 2: title = context.getString(R.string.on_boarding_title_3); description = context.getString(R.string.on_boarding_description_3); resource = R.drawable.on_boarding_bg_2; button = context.getString(R.string.on_boarding_button_3); break; default: title = context.getString(R.string.on_boarding_title_4); description = context.getString(R.string.on_boarding_description_4); resource = R.drawable.on_boarding_bg_3; button = context.getString(R.string.on_boarding_button_4); end = true; } return OnBoardingFragment.newInstance(title, description, resource, button, end); } @Override public int getCount() { return 4; } </code></pre> <p>Functions of <code>OnBoardingFragment</code>:</p> <pre><code>public static OnBoardingFragment newInstance(String title, String description, int resource, String button, boolean end) { Bundle bundle = new Bundle(); bundle.putString(EXTRA_TITLE, title); bundle.putString(EXTRA_DESCRIPTION, description); bundle.putInt(EXTRA_IMAGE, resource); bundle.putString(EXTRA_BUTTON, button); bundle.putBoolean(EXTRA_END, end); OnBoardingFragment fragment = new OnBoardingFragment(); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { title = bundle.getString(EXTRA_TITLE); description = bundle.getString(EXTRA_DESCRIPTION); button = bundle.getString(EXTRA_BUTTON); end = bundle.getBoolean(EXTRA_END); imageResource = bundle.getInt(EXTRA_IMAGE); show log ---&gt; Log.e(this.toString() + "/" + end + "/" + title); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.on_boarding_fragment, container, false); TextView tvTitle = (TextView) rootView.findViewById(R.id.tv_title); TextView tvDescription = (TextView) rootView.findViewById(R.id.tv_description); TextView btnDiscovery = (TextView) rootView.findViewById(R.id.tv_discovery); imageView = (ImageView) rootView.findViewById(R.id.iv_image); final Button btnNext = (Button) rootView.findViewById(R.id.btn_next); if (end) { btnDiscovery.setVisibility(View.VISIBLE); btnDiscovery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startRegionActivity(); } }); } btnNext.setText(button); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { show log ---&gt; Log.e(OnBoardingFragment.this.toString() + "/" + end + "/" + title + "/" + ((Button)v).getText()); if (end) { ((SplashActivity) getActivity()).gotoNextPage(); } else { startLoginActivity(); } } }); tvTitle.setText(title); tvDescription.setText(description); ImageUtils.loadBitmap(getActivity(), imageResource, imageView, 0.8f, new ImageUtils.LoadBitmapCallback() { @Override public void onLoadComplete(ImageView imageView) { } @Override public void onLoadFail() { } }); return rootView; } </code></pre> <p><strong>The problem is</strong></p> <p>When my app started it show the <strong>first</strong> <code>Fragment</code>, then I pressed the <code>Button</code> and trigger <code>onItemClick()</code> method, and the method was referenced to the <strong>last</strong> <code>Fragment</code>.</p> <p>Log when create <code>Fragment</code></p> <pre><code>OnBoardingFragment{a8ede47 id=0x7f10013b}/false/XIN CHÀO! OnBoardingFragment{8787674 #0 id=0x7f10013b}/false/BÁN LIỀN TAY, KIẾM TIỀN NGAY OnBoardingFragment{119f79d #1 id=0x7f10013b}/false/CHAT MIỄN PHÍ OnBoardingFragment{1ee7412 #2 id=0x7f10013b}/true/NGƯỜI THẬT, HÀNG THẬT </code></pre> <p>Log when <code>onClickListener()</code> was triggered</p> <pre><code>OnBoardingFragment{1ee7412 #2 id=0x7f10013b}/true/NGƯỜI THẬT, HÀNG THẬT/Đi chợ ngay nào! </code></pre> <p>Log when the <code>btnNext</code> was initialized:</p> <pre><code>button: android.support.v7.widget.AppCompatButton{17c69e97 VFED..C. ......I. 0,0-0,0 #7f1002c8 app:id/btn_next} button: android.support.v7.widget.AppCompatButton{31941c VFED..C. ......I. 0,0-0,0 #7f1002c8 app:id/btn_next} button: android.support.v7.widget.AppCompatButton{30765b87 VFED..C. ......I. 0,0-0,0 #7f1002c8 app:id/btn_next} button: android.support.v7.widget.AppCompatButton{9cf19e VFED..C. ......I. 0,0-0,0 #7f1002c8 app:id/btn_next} </code></pre> <p><strong>Question</strong></p> <p>Why it happen and how to resolve?</p>
<p>Please refer the sample in the below link for using view pager with multiple fragments: <a href="https://guides.codepath.com/android/ViewPager-with-FragmentPagerAdapter" rel="nofollow">https://guides.codepath.com/android/ViewPager-with-FragmentPagerAdapter</a></p>
Private or Public Image Setting for Autoscale in SL <p>I am trying to set Operating System for autoscale.</p> <p>In case of Operating System, I have set the code with API below.</p> <pre><code> /** * Operating System */ String operatingSystem = "WIN_2012-STD-R2_64"; virtualGuestMemberTemplate.setOperatingSystemReferenceCode(operatingSystem); </code></pre> <p>It works fine with Operating system, but what about private or public image ?</p> <pre><code> /** * Public Image */ String GlobalIdentifier = "1176d22b-176a-499a-8d94-f9aaf29155a3"; virtualGuestMemberTemplate.setGlobalIdentifier(GlobalIdentifier); </code></pre> <p>It returns an error, invalid guest template. How can I set VirtualGuestMemberTemplate for public and private Image ?</p> <p><a href="http://i.stack.imgur.com/uJpPm.png" rel="nofollow"><img src="http://i.stack.imgur.com/uJpPm.png" alt="Select Operating system"></a></p>
<p>keep in mind that the configuration of the VM in autoscale group is almost the same like the configuiration when you create a new VM using the SoftLayer_Virtual_Guest::createObject so to set the image template you need to do it like this:</p> <pre><code>{ "blockDeviceTemplateGroup": { "globalIdentifier": "07beadaa-1e11-476e-a188-3f7795feb9fb" } } </code></pre> <p>see <a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createObject" rel="nofollow">http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createObject</a> for more information</p> <p>Regards</p>
How to escape dollar sign ($) in emmet? <p>As emmet use dollar sign ($) for numbering like:</p> <pre><code>p#p${$}*3 //outputs &lt;p id="p1"&gt;1&lt;/p&gt;&lt;p id="p2"&gt;2&lt;/p&gt;&lt;p id="p3"&gt;3&lt;/p&gt; </code></pre> <p>it has its significant usefulness.</p> <p>But, in case of currency, I am having strange problem with it.</p> <pre><code>p{$10} //outputs &lt;p&gt;${14}&lt;/p&gt; expected &lt;p&gt;$10&lt;/p&gt; </code></pre> <p>What can I do for this type of scenario?</p> <p><strong>Note:</strong> To be precise, I am using <a href="https://github.com/Krizz/jquery.emmet" rel="nofollow">https://github.com/Krizz/jquery.emmet</a> as jquery emmet plugin.</p>
<p>Could you try and use <code>&amp;#36;</code>? This should escape it properly.</p> <p>Source: <a href="http://www.fileformat.info/info/unicode/char/0024/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/0024/index.htm</a></p>
How to disable page element on certain articles in Joomla <p>I want to make a 100% clean bootstrap template for Joomla 1.5 (i know i know but it runs as intranet application so it's safe - i dont want to mess with this ;) ) and wonder how to disable template element (ex. div) on certain article pages (not associated to selected category/section ID) or parent menu position. I want to hardcode it directly in template.</p> <p><strong>I need something like this (example!)</strong></p> <pre><code>{if JArticle-&gt;Category-ID != 2 &amp;&amp; 3}Do something{else}Do something else{/if} </code></pre>
<p>First you need to get the article id from the request. I'm not sure if in Joomla 1.5 this is the correct way (on latest Joomla releases, JRequest is deprecated), but anyway, you'll need to use the JRequest class.</p> <p><code>$id = JRequest::getInt('id');</code></p> <p>Then use this id:</p> <pre><code>if (($id != 2) &amp;&amp; ($id != 3)) { // id is not 2 nor 3 } else { // otherwise } </code></pre>
Prepopulate Dropdown with Object <p>I am trying to create a dropdown and want to prepopulate it with object.</p> <pre><code>&lt;script&gt; angular.module("myapp", []) .controller("MyController", function($scope) { $scope.country = { id: "2", name: "USA" }; $scope.countries = [{ id: "1", name: "India" }, { id: "2", name: "USA" }, { id: "3", name: "UK" }, { id: "4", name: "Nepal" }]; }); &lt;/script&gt; &lt;div&gt; Country Name : &lt;select ng-model="country" ng-options="country as country.name for country in countries"&gt;&lt;/select&gt; &lt;/div&gt; </code></pre> <p>But the countries dropdown is not being prepopulated with country object.I am not sure what is the problem.</p> <p>JSFIDDLE link :<a href="http://jsfiddle.net/6qo3vs6c/" rel="nofollow">http://jsfiddle.net/6qo3vs6c/</a></p>
<p>Remove <code>country as</code> and add <code>track by country.id</code> in <code>ng-options</code>.</p> <pre><code>&lt;select ng-model="country" ng-options="country.name for country in countries track by country.id"&gt;&lt;/select&gt; </code></pre> <p><a href="https://jsfiddle.net/DieuNQ/3gtvpa77/1/" rel="nofollow">Here</a> is your. See <a href="http://stackoverflow.com/questions/20845210/setting-selected-values-for-ng-options-bound-select-elements">more</a>.</p> <p>Hope this helps.</p>
How to fix Error ITMS-90513 caused by missing TVTopShelfImage.TVTopShelfPrimaryImageWide in your app's Info.plist <p>Detailed error description:</p> <blockquote> <p>ERROR ITMS-90513: "Missing Info.plist Key. Your app's Info.plist in 'Payload/xxx.app' must contain the 'TVTopShelfImage.TVTopShelfPrimaryImageWide' key."</p> </blockquote>
<p>Starting with tvOS 10 you also have to provide wide version of TopShelfImage.</p> <p>Find it in asset catalog right next to your icon and the old TopShelfImage.</p> <p>Project settings / General / App Icons and Launch images / App Icons source / click the little right arrow on the right.</p>
PostgreSQL timeseries query with outer join <p>In PostgreSQL 9.5 database there is a table <em>metrics_raw</em> containing various metrics (<em>types: varchar</em>).<br> Types are (for example): <em>TRA</em>, <em>RTC</em>.<br> I'm executing following SQL to get year-to-date monthly aggregations:</p> <pre><code>SELECT count(*), "ticks"."ts" AS "timestamp" FROM "metrics_raw" RIGHT OUTER JOIN generate_series('2016-01-01'::timestamp, '2016-10-10'::timestamp, '1 month'::interval) AS ticks(ts) ON "ticks"."ts" = date_trunc('months', "metrics_raw"."timestamp") WHERE "metrics_raw"."type" = 'TRA' OR "metrics_raw"."type" IS NULL GROUP BY "ticks"."ts" ORDER BY "ticks"."ts" </code></pre> <p>The table contains some records of <em>TRA</em> type (~10 records) and 1 record of <em>RTC</em> type.<br> Executing the query for <em>TRA</em> I get <strong>10</strong> rows result as expected, but for <em>RTC</em> query I get only <strong>7</strong> rows. One more thing is that having no <em>RTC</em> metrics I get <strong>10</strong> rows too. </p> <p>Where could be a mistake?</p>
<p>Thank @Nemeros, I fixed query to be:</p> <pre><code>SELECT "ticks"."ts" AS "timestamp" FROM generate_series('2016-01-01'::timestamp, '2016-10-10'::timestamp, '1 month'::interval) AS ticks(ts) LEFT OUTER JOIN ( SELECT * FROM "metrics_raw" WHERE "metrics_raw"."type" = 'TRA' ) as "metrics" ON "ticks"."ts" = date_trunc('months', "metrics"."timestamp") GROUP BY "ticks"."ts" ORDER BY "ticks"."ts" </code></pre>
How to pass a list of lists through a for loop in Python? <p>I have a list of lists :</p> <pre><code>sample = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']] count = [[4,3],[4,2]] correctionfactor = [[1.33, 1.5],[1.33,2]] </code></pre> <p>I calculate frequency of each character (pi), square it and then sum (and then I calculate het = 1 - sum). </p> <pre><code>The desired output [[1,2],[1,2]] #NOTE: This is NOT the real values of expected output. I just need the real values to be in this format. </code></pre> <p>The problem: I do not how to pass the list of lists(sample, count) in this loop to extract the values needed. I previously passed only a list (eg <code>['TACT','TTTT'..]</code>) using this code. </p> <ul> <li>I suspect that I need to add a larger for loop, that indexes over each element in sample (i.e. indexes over <code>sample[0] = ['TTTT', 'CCCZ']</code> and <code>sample[1] = ['ATTA', 'CZZC']</code>. I am not sure how to incorporate that into the code.</li> </ul> <p>** Code</p> <pre><code>list_of_hets = [] for idx, element in enumerate(sample): count_dict = {} square_dict = {} for base in list(element): if base in count_dict: count_dict[base] += 1 else: count_dict[base] = 1 for allele in count_dict: #Calculate frequency of every character square_freq = (count_dict[allele] / count[idx])**2 #Square the frequencies square_dict[allele] = square_freq pf = 0.0 for i in square_dict: pf += square_dict[i] # pf --&gt; pi^2 + pj^2...pn^2 #Sum the frequencies het = 1-pf list_of_hets.append(het) print list_of_hets "Failed" OUTPUT: line 70, in &lt;module&gt; square_freq = (count_dict[allele] / count[idx])**2 TypeError: unsupported operand type(s) for /: 'int' and 'list'er </code></pre>
<p>I'm not completely clear on how you want to handle the 'Z' items in your data, but this code replicates the output for the sample data in <a href="https://eval.in/658468" rel="nofollow">https://eval.in/658468</a></p> <pre><code>from __future__ import division bases = set('ACGT') #sample = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']] sample = [['ATTA', 'TTGA'], ['TTCA', 'TTTA']] list_of_hets = [] for element in sample: hets = [] for seq in element: count_dict = {} for base in seq: if base in count_dict: count_dict[base] += 1 else: count_dict[base] = 1 print count_dict #Calculate frequency of every character count = sum(1 for u in seq if u in bases) pf = sum((base / count) ** 2 for base in count_dict.values()) hets.append(1 - pf) list_of_hets.append(hets) print list_of_hets </code></pre> <p><strong>output</strong></p> <pre><code>{'A': 2, 'T': 2} {'A': 1, 'T': 2, 'G': 1} {'A': 1, 'C': 1, 'T': 2} {'A': 1, 'T': 3} [[0.5, 0.625], [0.625, 0.375]] </code></pre> <p>This code could be simplified further by using a collections.Counter instead of the <code>count_dict</code>.</p> <p>BTW, if the symbol that's not in 'ACGT' is <em>always</em> 'Z' then we can speed up the <code>count</code> calculation. Get rid of <code>bases = set('ACGT')</code> and change</p> <pre><code>count = sum(1 for u in seq if u in bases) </code></pre> <p>to</p> <pre><code>count = sum(1 for u in seq if u != 'Z') </code></pre>
SQL INSERT INTO with Multiple SELECTS From Different Tables <p>I am attempting to Insert rows with data from 2 tables. The first table is my users AspNetUsers and the second table AspNetUserRoles. I want to give all users the same role. I have tried the following:</p> <pre><code> INSERT INTO [MyDB].[dbo].[AspNetUserRoles] ([UserId], [RoleId]) SELECT (SELECT Id FROM [MyDB].[dbo].AspNetUsers) AS UserId, (SELECT Id FROM [MyDB].[dbo].[AspNetRoles] WHERE Name = 'Intermediary') AS RoleId </code></pre> <p>I get the error:</p> <p>Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, &lt;, &lt;= , >, >= or when the subquery is used as an expression</p> <p>This is because the query is selecting all the users, which I want, but my SQL needs to be modified to insert each user and the same RoleId.</p> <p>I think I might need to use a cursor, or how should I go about this? I am using MS SQL Server.</p>
<p>This should work:</p> <pre><code>INSERT INTO [MyDB].[dbo].[AspNetUserRoles] ([UserId], [RoleId]) SELECT Id, (SELECT Id FROM [MyDB].[dbo].[AspNetRoles] WHERE Name = 'Intermediary') AS RoleId FROM [MyDB].[dbo].AspNetUsers </code></pre> <p>as long as <code>WHERE Name = 'Intermediary'</code> return 1 row.</p>
How to call a wizard from other wizard in Odoo8? <p>I have a wizard in which there is a one2many field. I made a button in each line of the one2many which calls another wizard made by me. This wizard is for modifying some values of the selected line.</p> <p>My purpose is to return the first wizard, with the new changes, when you click on the <strong>Apply</strong> button of my wizard.</p> <blockquote> <p>Example:</p> <p>The first wizard has a one2many field with three records:</p> <ul> <li>Product A | 1 ud | Source location X | Dest location Y | Lot A1</li> <li>Product B | 2 ud | Source location X | Dest location Y | Lot B1</li> <li>Product C | 3 ud | Source location X | Dest location Y | Lot C1</li> </ul> <p>Now, I click on the first line button I made (each line has one), and my wizard is opened. Here I can modify the lot of the first line (the one with the Product A). Imagine I set Lot A0 and click on <strong>Apply</strong>.</p> <p>I should return to the parent wizard, and see the same data except for the changes made. So the result will be:</p> <ul> <li>Product A | 1 ud | Source location X | Dest location Y | <strong>Lot A0</strong></li> <li>Product B | 2 ud | Source location X | Dest location Y | Lot B1</li> <li>Product C | 3 ud | Source location X | Dest location Y | Lot C1</li> </ul> </blockquote> <p>Does anyone know how to achieve this? How could I preserve the first wizard data?</p>
<p>First you need to browse current record of Wizard and it's line. Afterward write value as you want. </p> <p>Return that current id with wizard object.</p> <p>Try with following trick:</p> <pre><code>#apply button method logic def apply_data(self, cr, uid, ids, context=None): if not context: context = {} ctx = context.copy() for wizard in self.browse(cr, uid, ids[0], context=context): for line in wizard.one2many_field: line.write({ 'field_name': field_value }) dummy, view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'module_name', 'wizard_form_view_name') return { 'name':_("Name of your Wizard"), 'view_mode': 'form', 'view_id': view_id, 'view_type': 'form', 'res_id': ids and ids[0] or False, 'res_model': 'wizard.object.name', 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'new', 'context': ctx } </code></pre> <p>NOTE:</p> <p>You can also update context value as well.</p> <p>Apply button type must be object to execute method logic.</p>
Binding a context to an objects this <pre><code>var test = function() { console.log(this.x); }; test.bind({x:777}); console.log(test()); // &lt;--- I'm expecting the console to echo '777' </code></pre> <p>I have seem to have missed something here in understanding binding.</p>
<p>Doh! Missed the equals.</p> <pre><code>var test = function() { console.log(this.x); }; test = test.bind({x:777}); console.log(test()); </code></pre>
Why do I get different errors when I use a non-existing alias in realurl? 404 with postvarsets, 500 with fixedpostvars <p>I have two different configurations for two different extensions. With news I use postvarsets:</p> <pre><code>'postVarSets' =&gt; array ( '_DEFAULT' =&gt; array ( 'news' =&gt; array ( 0 =&gt; array ( 'GETvar' =&gt; 'tx_news_pi1[news]', 'lookUpTable' =&gt; array ( 'table' =&gt; 'tx_news_domain_model_news', 'id_field' =&gt; 'uid', 'alias_field' =&gt; 'title', 'useUniqueCache' =&gt; 1, 'useUniqueCache_conf' =&gt; array ( 'strtolower' =&gt; 1, 'spaceCharacter' =&gt; '-', ), ), ), ), ), ) </code></pre> <p>For an own extension to display categories I use fixedpostvars:</p> <pre><code>'fixedPostVars' =&gt; array ( 'category' =&gt; array ( 0 =&gt; array ( 'GETvar' =&gt; 'tx_myextension_plugin[mainCategory]', 'lookUpTable' =&gt; array ( 'table' =&gt; 'sys_category', 'id_field' =&gt; 'uid', 'alias_field' =&gt; 'title', 'languageGetVar' =&gt; 'L', 'languageField' =&gt; 'sys_language_uid', 'transOrigPointerField' =&gt; 'l10n_parent', 'useUniqueCache' =&gt; 1, 'useUniqueCache_conf' =&gt; array ( 'strtolower' =&gt; 1, 'spaceCharacter' =&gt; '-', ), ), ), ), ), </code></pre> <p>If I now use some invalid URL in news, I get a 404 (which is completely right). If I now use some invalid category in my URL, I get a 500 error with the error message:</p> <blockquote> <p>Exception while property mapping at property path "": The identity property "ergeriguehrgoiekweukw" is no UID.</p> </blockquote> <p>Why is there a difference between the two configurations and how can I get a 404 as well for the fixedpostvars?</p>
<p>i am not sure but i think this is useful for you. add 'enable404forInvalidAlias' => 1, for getting 404 error. in fixedPostVars realURL configuration.</p>
One mail, multiple content depending the mail address <p>I don't know if it is possible or if it has already been asked. But here's my problem. I would like to send a mail to multiple address, and display in the mail, the mail address and some account information according the email address (not only the name).</p> <p>Ex: I send an email to <strong>john@gmail.com</strong>, <strong>jack@gmail.com</strong> &amp; <strong>luke@gmail.com</strong>.</p> <p>John will see "Hello <strong>John</strong>, ...", Jack will see "Hello <strong>Jack</strong>, ...", ...</p> <p>Is it possible to do it by sending a single mail? Or do I need to send 1 mail by account?</p> <p>PS: I don't know if it can help, but I user PHPMailer.</p>
<p>You will have to send separate emails to send different content.</p> <p>If you want to make your life easier, though, you ought to use a template with PHPMailer and provide the necessary data. There are plenty of <a href="http://stackoverflow.com/questions/38158181/send-html-emails-using-phpmailer-and-html-templates">other questions</a> and <a href="https://github.com/PHPMailer/PHPMailer/wiki" rel="nofollow">documentation</a> on doing this.</p> <p>Also note that if you are sending multiple emails you should be using BCC anyway or everyone will see everyone else's email address and you will most likely get hurt for spam.</p>
UserName - Password check function returning "false" <p>I'm having some trouble managing my login for a website. I've tried several different methods and queries which all seem to lead to the same problem: the method I use to check <code>username</code> and <code>password</code> always returns <code>false</code>.</p> <p>To make it easier to understand, here's what I'm trying to do:</p> <ul> <li>Controller file calls view page and prompts user for <code>username</code> and <code>password</code></li> <li>I'm using a <code>callback</code> function to set a rule for the form</li> <li>the <code>callback</code> function calls Model method</li> <li>Model method returns <code>TRUE</code> if login details are correct and <code>FALSE</code> otherwise.</li> </ul> <p>Apparently it always returns <code>FALSE</code> as the login never works ... </p> <p>I'm using CodeIgniter.</p> <p>Controller file:</p> <pre><code>class Login extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;helper(array('form', 'url')); $this-&gt;load-&gt;library(array('form_validation', 'session')); } public function index() { $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'callback_login_check[password]'); if ($this-&gt;form_validation-&gt;run() == FALSE) { //loading view as long as it is not correct $this-&gt;load-&gt;view('login'); } else { //temporary successful login page $this-&gt;load-&gt;view('success'); } } public function login_check($usr, $pwd) { $this-&gt;load-&gt;database(); $this-&gt;load-&gt;model('EZ_Query'); $result = $this-&gt;EZ_Query-&gt;get_user_details($usr, $pwd); if ($result == TRUE) { return TRUE; } else { $this-&gt;form_validation-&gt;set_message('login_check', 'Password does not match Username'); return FALSE; } } } </code></pre> <p>Model file:</p> <pre><code>class EZ_Query extends CI_Model { public function get_user_details($usr, $pwd) { $sql = "SELECT * FROM PROFIL WHERE USER = '$usr' AND MDP = '$pwd'"; $query = $this-&gt;db-&gt;query($sql); if ($query-&gt;num_rows() == 1) { $row = $query-&gt;row(); //session variables $data = array('name' =&gt; $row-&gt;NOMPROFIL, 'fname' =&gt; $row-&gt;PRENOMPROFIL, 'type' =&gt; $row-&gt;TYPEPROFIL); $this-&gt;session-&gt;set_userdata($data); return TRUE; } else { return FALSE; } } } </code></pre> <p>Less useful, here's part of login view page:</p> <pre><code>&lt;body&gt; &lt;?php echo validation_errors(); echo form_open('Login'); echo form_label('Username', 'username'); echo form_input('username')."&lt;br /&gt;"; echo form_label('Password', 'password'); echo form_password('password')."&lt;br /&gt;"; echo form_submit('sumbit', 'Enter'); echo form_close(); ?&gt; &lt;/body&gt; </code></pre> <p>Sorry for bad english, and thanks for your help.</p>
<p>I have changed a couple of things on here for you to try</p> <p>I hope you are using a good hash for passwords <strong>NOT MD5</strong> use <a href="http://php.net/manual/en/function.password-hash.php" rel="nofollow">http://php.net/manual/en/function.password-hash.php</a> and <a href="http://php.net/manual/en/function.password-verify.php" rel="nofollow">http://php.net/manual/en/function.password-verify.php</a></p> <p>Filename: Login.php</p> <pre><code>&lt;?php class Login extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;helper(array('form', 'url')); $this-&gt;load-&gt;library(array('form_validation', 'session')); // Autoload the session because you may need it else where } public function index() { // remove the word password from callback as it on the username // login all ways good to use required $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|callback_login_check'); $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'trim|required'); if ($this-&gt;form_validation-&gt;run() == FALSE) { //loading view as long as it is not correct $this-&gt;load-&gt;view('login'); } else { //temporary successful login page $this-&gt;load-&gt;view('success'); } } public function login_check() { $usr = $this-&gt;input-&gt;post('username'); $pwd = $this-&gt;input-&gt;post('password'); $this-&gt;load-&gt;database(); // Autoload database best. // Filename of model should be Ez_query.php and same with class only first letter upper case $this-&gt;load-&gt;model('ez_query'); $result = $this-&gt;ez_query-&gt;get_user_details($usr, $pwd); if ($result == TRUE) { return TRUE; } else { $this-&gt;form_validation-&gt;set_message('login_check', 'Password does not match Username'); return FALSE; } } } </code></pre>
indexeddb objectstore.add() keypath = 'id' <p>i have a few object stores, and split things up between them. and during initial install of chrome extension, i am adding data to the various object stores, and i am wanting to make sure the data aligns up correctly. so when things go out of sync during install. the "keypath / id" will match things up correctly. nothing big there.</p> <p>issue comes in after the initial install. and adding another record. and the "id" / keyPath / key for initial records are showing id:1, id:2, id:3, etc...</p> <p>but for a record after initial install. i no longer know what the key will be until it is added to the objectstore. is there a code snip i am missing so i can create an object and add to objecstore, to also up the id, or did i mess up originally creating id: 1 and should of used something like keyPath: 1 or key: 1 or Primarykey: 1?</p> <p>i can take long way around it, and use some promises, and </p> <pre><code>objectstore.add(object) .then(objecstore.get(event.key) .then(objestore.put(key, {"id":key}) </code></pre> <p>i do note remember correct promise code to above. but objectstore.add, then getting key once added, then .put({"id": key}) to update "id" is done, is the jist of it. i am trying to prevent ever needing to do this in the first place.</p> <p>kinda like in SQL like database, and having 2 primarykeys that are numbers, autoinncrement, and are exactly same in every way for the same table. but in my case, keys update, and "id" is taking up space. and not sure how to remove 'id' from initial get go. Or once done, how to keep keys and 'id' synced without a bunch of extra blah promises. </p> <p>comments in below code, trying to figure it out. and no success as of yet figuring it out myself</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> const ms_master = [{ //======================== //did i mess up here in creating id: and should of used like keypath:1? //======================== "id": 1, "baseurl": "www.example1.net", "prefix": "ex1", "name": "tryout1", }, { "id": 2, "baseurl": "www.something.com", "prefix": "so", "name": "some some", }, { "id": 3, "baseurl": "woops.org", "prefix": "woo", "name": "arghs", }] var db; var request = window.indexedDB.open("mystyle", 1); request.onerror = function(event) { console.log("error: ") }; request.onsuccess = function(event) { db = event.target.result; console.log("success: " + db); }; request.onupgradeneeded = function(event) { var db = event.target.result; if (!db.objectStoreNames.contains("ms_master")) { //======================== //did i mess up here in creating the store? //======================== var objectStore = db.createObjectStore("ms_master", { keypath: "id", autoIncrement: true, unique: true }); objectStore.createIndex("baseurl", "baseurl", { unique: false }); objectStore.createIndex("prefix", "prefix", { unique: false }); objectStore.createIndex("name", "name", { unique: false }); //======================== //seems to make no difference //======================== //objectStore.createIndex("id","id", { unique: true }); for (var i in ms_master) { objectStore.add(ms_master[i]); } //======================== //once added, should i do a objecstore.get and grab data, then do a objectstore.put that does not have 'id" in it? //======================== } $(document).ready(function() { document.getElementById('ms_table_add').addEventListener("click", ms_table_add); } function ms_table_add() { var db; var request = indexedDB.open('mystyle', 1); request.onsuccess = function(e) { db = e.target.result; var transaction = db.transaction('ms_master', "readwrite"); var objectStore = transaction.objectStore('ms_master'); var myobj = [ "id", "name", "prefix", "baseurl" ]; var myarray = {}; for (var h = 0; h &lt; myobj.length; h++) { if (h == 0) { //======================== //am i not getting the correct code to get id and keypath to sync up? //======================== //{name: 'ms_master', keyPath: 'id'} //myarray[myobj[h]] = 'id'; } else { var temp = document.getElementById('ms_table_add_' + myobj[h]).value; if (typeof temp !== "undefined" &amp;&amp; temp !== null &amp;&amp; temp !== "") { myarray[myobj[h]] = temp; } } } objectStore.add(myarray); //============================== //trying to avoid extra promises to add, then get key, then update id here. //============================== document.getElementById("ms_listings_master_add").innerHTML = ""; } } function site_adding() { //function that builds up a html form / textareas / inputs and .innerhtml into //&lt;div id="ms_listings_master_add"&gt;&lt;/div&gt; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button id="site_adding"&gt;add a site&lt;/button&gt; &lt;/br&gt; &lt;div id="ms_listings_master_add"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
<p>You're using two features together - in-line keys and key generators. I'll explain them both separately then how they compose.</p> <p><strong>In-Line and Out-of-Line Keys</strong></p> <p><em>In-line keys</em> have the key value appear in the record itself - a store with a keyPath uses in-line keys. By contrast, <em>out-of-line keys</em> have the key value separate.</p> <pre><code>var storeWithOutOfLineKeys = db.createObjectStore('s1'); storeWithOutOfLineKeys.put({name: 'alice'}, 1); var storeWithInLineKeys = db.createObjectStore('s2', {keyPath: 'id'}); storeWithInLineKeys.put({name: 'bob', id: 1}); </code></pre> <p>Calls to <code>put()</code> and <code>add()</code> will fail if you don't supply an explicit key for a store with out-of-line keys. Calls to <code>put()</code> and <code>add()</code> will fail if you <em>do</em> supply an explicit key to a store with in-line keys, and will fail if the record does not contain the in-line key value (e.g. missing the <code>id</code> property in the above example)</p> <p><strong>Key Generators</strong></p> <p>When you specify <code>autoIncrement: true</code> you're using what the spec calls a <em>key generator</em>. For each record added, if not specified otherwise then the first will get <code>1</code>, the second <code>2</code>, etc. You can find out what key was used by looking at the result of the <code>put()</code> or <code>add()</code> request, e.g.</p> <pre><code>var request = store.put({name: 'alice'}); request.onsuccess = function() { console.log('put got generated key: ' + request.result; }; </code></pre> <p><strong>Both In-Line Keys and Key Generators</strong></p> <p>When a key generator is used, the behavior of <code>add()</code> and <code>put()</code> change:</p> <p><em>Key generator and out-of-line keys:</em> it is not necessary to pass an explicit key when calling <code>add()</code> or <code>put()</code>; if omitted, the generated key is used:</p> <pre><code>var storeWithOutOfLineKeys = db.createObjectStore('s1', {autoIncrement: true}); storeWithOutOfLineKeys.put({name: 'alice'}); </code></pre> <p>If an explicit key is passed it <em>will</em> be used, either overwriting a previous record or adding a new one. (If the key passed happens to be a number higher than the generator value, the generator will be set to that number.)</p> <p><em>Key generator and in-line keys:</em> it is not necessary to specify the key in the record when calling <code>add()</code> or <code>put()</code>; if omitted, the generated key is injected into the value.</p> <pre><code>var storeWithInLineKeys = db.createObjectStore('s2', {keyPath: 'id'}); storeWithInLineKeys.put({name: 'bob'}).onsuccess = function(e) { var id = e.target.result; storeWithInLineKeys.get(id).onsuccess = function(e) { console.log(JSON.stringify(e.target.result)); // {"name": "bob", "id": 1} }); }); </code></pre> <p>Similarly though, if the record <em>does</em> contain a key value it will be used instead. (And if it's a number higher than the key generator state, the key generator will be adjusted.)</p> <p>I believe this last case matches what your code is doing - both in-line keys and a key generator. You can use the result of <code>add()</code> and <code>put()</code> requests to determine the key that was added, and update records by specifying the key explicitly in the record:</p> <pre><code>storeWithInLineKeys.put({name: 'eve', id: 1}); // overwrites old #1 </code></pre>
Display route title inside root component <p>I have a root component and want to display route title inside special section in it.<br>I can detect which route is active in every component.<br>However, I don`t know how to do it inside root component. </p> <p>This code shows title fine in ChildComponent1 :</p> <pre><code>route:ActivatedRoute ngOnInit() { this.route.data.subscribe( data =&gt; console.log(data) ) } </code></pre> <p>How can I detect what is current route`s title and display it inside the root component?</p> <pre><code>export const routes: Routes = [ {path: '', component: Component1, canActivate: [NonAuthGuard]}, { path: 'root', component: rootcomponent, canActivate: [AuthGuard], children: [ { path: 'Child1', component: ChildComponent1, data: { title: 'Child1' }, canActivate: [AuthGuard], canDeactivate: [CanDeactivateGuard] }, { path: 'Child2', component: ChildComponent2, data: { title: 'Child2' }, canActivate: [AuthGuard], canDeactivate: [CanDeactivateGuard] }, ]} </code></pre>
<p>You could inject <code>Router</code> in your root component and then subscribe its <strong>events</strong>. Example:</p> <pre><code>constructor(private router : Router) { this.router.events.subscribe((event) =&gt; { if(event instanceof NavigationStart) { console.log(event); console.log(event.url); } }); } </code></pre> <p>You should check if your event is instance of <code>NavigationStart</code> or <code>NavigationEnd</code>, because your event will fire <em>several</em> times.</p>
Using the same thread for other database operations after it has finished processing <p>I am writing an hibernate application which involves batch processing on the records stored.</p> <p>Assume there are 30000 records stored in database table and i am using 30 threads. Each thread processes 1000 records in parallel i.e. batch by batch. Thread1 processes 1 to 1000 Thread2: 1001 to 2001, etc. Here process means i am performing a select operation on all of them in a batch. I am processing these records to send them to a web-service by parsing them.</p> <p>The scenario is there is a column named status in the database table where if the record is accepted by the webservice then the status column of the record is made as 1 else 0.</p> <p>Now the issue arises here when Thread1 finishes processing records with id's 1 to 1000 and Thread 2 is still processing 1001 to 2001. Assume the records with id's 5 to 30 and 40 to 50 status are 0 i.e. undelivered to the webservice. Now my scenario demands the thread which has finished processing i.e. Thread1 should start processing the records with id's 5 to 30 and 40 to 50 and try to redeliver the message in the record to the webservice.</p> <p>I am using <code>ExecutorService</code> for coding the same, how to achieve the above.</p>
<p>You could use a shared blocking queue, which is filled with the records you need to process (which means that you select those 30000 records somewhere outside of your <code>ExecutorService</code> threads).</p> <p>Then, in your <code>Thread</code> code each thread gets top 1000 (<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ArrayBlockingQueue.html#drainTo-java.util.Collection-int-" rel="nofollow">using this method</a>) records from the queue and does it's processing. Here is the important part: the records rejected by a web-service are put back to the queue - so when another executor thread is available it will pick the undelivered.</p> <p>You would need to add delivery counter to your records and check if a message is redelivered limited number of times (so they aren't redelivered forever if they are somehow malformed).</p>
I'm trying to bind an address in the PowerShell script <p>I'm trying to bind an address in the PowerShell script so my testers can run wiremocks and it automatically points to the correct environment when they run it.</p> <pre><code>echo "Running WireMock" $WiremockFileName = "wiremock-standalone-2.1.12.jar" $Port = 8050 $Address = "my.integration.address" if (-not(Test-Path "./$WiremockFileName")) { echo "Going to download wiremock"; Invoke-WebRequest "http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.1.12/$WiremockFileName" -OutFile $WiremockFileName echo "Finished" } echo "Looking for JRE" $JAVA = "" if ($JAVA -eq "") { # In case a specific version of Java is in the path already $JavaExe = Get-Command "java" -ErrorAction SilentlyContinue if ($JavaExe) { $JAVA = JavaExe.Definition } } if ($JAVA -eq "") { # This seems to work on RBI machines $jre7Path = "C:\Program Files (x86)\Java\jre7\bin\java.exe" $testJre7 = Test-Path $jre7Path -ErrorAction SilentlyContinue if ($testJre7) { $JAVA = $jre7Path } } if ($JAVA -eq "") { # Nope - I give up echo "I give up! I can't find JAVA anywhere" echo "Put it in your path and stop giving me a hard time or send a pull request" exit 1 # echo "Press any key to continue" # $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } &amp; $JAVA -jar $WiremockFileName --bind-address $Address --https-port $Port --verbose exit $LASTEXITCODE </code></pre> <p>I'm trying to get this part working:</p> <pre><code>&amp; $JAVA -jar $WiremockFileName --bind-address $Address --https-port $Port --verbose </code></pre> <p>but <code>--bind-address $Address</code> seems to not work.</p>
<p>beside the address binding...in line 20 I'm pretty sure it should be</p> <p><code>$JAVA = $JavaExe.Definition</code></p> <p>instead of </p> <p><code>$JAVA = JavaExe.Definition</code></p>
Chef git sync using knife role create and new workstation setup <p>I have a simple question about keeping my chef-repo in sync with what's on the server.</p> <p>Here is the steps I took to create a new role:</p> <pre><code>cd /chef-repo/roles knife role create windows_base </code></pre> <p>Then when I do:</p> <pre><code>knife role list </code></pre> <p>I can see the new windows_base role appearing, however I do not see a json file created under roles. When I push this to git this file wont exist?</p> <p>So when I go onto a different workstation and pull everything to that workstation, the role windows_base wont exist. Why is there no json file created when I do knife role create windows_base and there obviously is when creating a role manually using a .rb file.</p> <p>Simply put - how can I keep my chef-repo in sync with git if there is no file created and the role is directly created on the server?</p>
<p>The <code>knife * create</code> commands are issuing the create directly against the API. We don't offer generator commands (which live under <code>chef generate</code>) for roles, you'll just have to create the file yourself. In general you probably don't want to use the <code>create</code> commands, instead make the files you want and then <code>knife upload roles/</code>.</p>
I can't select Microsoft Git Provider <p>I was confused, when I click and select Microsoft Git Provider, the select option does not accept my selection, but if I select other option it's fine, I need to select Microsoft Git Provider to fix my error in team explorer. I tried to clear cache and restart but still the problem was there, I am using Visual Studio community 2015.</p> <p><a href="http://i.stack.imgur.com/rVFh3.png" rel="nofollow">Please check Image</a></p> <p>Any idea?</p>
<p>Finally I fixed, just update Visual Studio. under tools/Extension and Updates/ visual studio update.</p>
How I add bracket in string variable in TCL file <p>I have written one TCL script but I have one problem when making a string variable as below:</p> <pre><code>set a 100 set b "this is variable[$a]" </code></pre> <p>I want b to be assign with b = "<code>this is variable[100]</code>" but I got the error: </p> <pre> invalid command name 100 </pre> <p>Please help me to fix it :-(.</p>
<p>You just need to escape it:</p> <pre><code>set a 100 set b "this is variable\[$a\]" </code></pre>
Select Case to handle active TabPage <p>A program with a Form and a TabControl. I need to handle what happens when the user close the form according to the active TabControlPage</p> <p>Is working with If - Then like this</p> <pre><code>If PanelChooserTabControl.SelectedTab Is SelectionTabPage Then 'What I want End If If PanelChooserTabControl.SelectedTab Is EditionTabPage Then 'The user can´t leave e.Cancel = True End If </code></pre> <p>But I will have more TabPages and I want to make the code easy with Select Case</p> <pre><code>Dim TabPageActive As String = PanelChooserTabControl.SelectedTab.ToString Select Case TabPageActive Case "TabPage:{SelectionTabPage}" 'What I want Case "EditionTabPage" 'What I want End Select </code></pre> <p>But the TabPageActive variable is loaded with something like TabPage:{SelectionTabPage}</p> <p>and not only "SelectionTabPage". Even using TabPage:{SelectionTabPage} as the Case variable (like the example code) is not working. </p> <p><strong>Do I need to make another string conversion or trim?</strong></p>
<p>You can try something like:</p> <pre><code>Select Case True Case PanelChooserTabControl.SelectedTab Is SelectionTabPage Case PanelChooserTabControl.SelectedTab Is EditionTabPage ... End Select </code></pre> <p>or on tabPage index change save as an enum the page and use this enum in the case.</p>
Save User Settings ( switch Toggles ) Xamarin forms <p><a href="http://i.stack.imgur.com/UXt5m.png" rel="nofollow">page screenshot</a></p> <p>Lets say we have a page in PCL xamarin forms application I want to save the settings ( toggle switch choices ) for each users : - save them locally and remotly</p>
<p>Probably the fastest way to implement this is by using James Montemagno's <a href="https://github.com/jamesmontemagno/SettingsPlugin" rel="nofollow">Settings Plugin</a>. It's available as a NuGet package, just remember to install it in all of your projects both shared and platform.</p> <p>It should be pretty self-explanatory. When you install the package it already creates a helper class for you and shows you a readme file.</p> <p>It works only with simple types, being: <code>Boolean</code>, <code>Int32</code>, <code>Int64</code>, <code>String</code>, <code>Single</code>(float), <code>Guid</code>, <code>Double</code>, <code>Decimal</code>, <code>DateTime</code>.</p> <p>When you installed the package you get a default static class to access your settings which looks like this:</p> <pre><code>private static ISettings AppSettings { get { return CrossSettings.Current; } } </code></pre> <p>You can now define your settings with key/value pairs and define a default value, i.e.:</p> <pre><code>private const string UserNameKey = "username_key"; private static readonly string UserNameDefault = string.Empty; private const string SomeIntKey = "int_key"; private static readonly int SomeIntDefault = 6251986; </code></pre> <p>And retrieve them by properties, like this:</p> <pre><code>public static string UserName { get { return AppSettings.GetValueOrDefault&lt;string&gt;(UserNameKey, UserNameDefault); } set { AppSettings.AddOrUpdateValue&lt;string&gt;(UserNameKey, value); } } public static int SomeInt { get { return AppSettings.GetValueOrDefault&lt;int&gt;(SomeIntKey, SomeIntDefault); } set { AppSettings.AddOrUpdateValue&lt;int&gt;(SomeIntKey, value); } } </code></pre> <p>You can also use databinding in Xamarin.Forms so you don't need any redundant code. More in-depth can be read about in the documentation <a href="https://github.com/jamesmontemagno/SettingsPlugin#databinding-in-xamarinforms" rel="nofollow">here</a>.</p> <p>Because it is using properties etc. you could implement some code yourself to call a backend service and store the settings there as well.</p>
Spring tool suite vs intellij running a spring boot project <p>I was using eclipse - sts , to launch my spring boot projects with option "run as -> spring boot app" and it is working fine , now I decided to switch into intellij IDE, but I'm not able to run my projects anymore, when I try to run my class with Springboot.run , I'm getting </p> <pre><code>ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.4.0.RELEASE) [INFO ] 2016-10-11 11:22:54.170 [main] RestApplication - Starting RestApplication on Mateusz-PC with PID 8304 (C:\Users\Mateusz\Documents\RESTService\target\classes started by Mateusz in C:\Users\Mateusz\Documents\RESTService) [INFO ] 2016-10-11 11:22:54.214 [main] RestApplication - No active profile set, falling back to default profiles: default [INFO ] 2016-10-11 11:22:54.347 [main] AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@209da20d: startup date [Tue Oct 11 11:22:54 CEST 2016]; root of context hierarchy [INFO ] 2016-10-11 11:22:54.375 [background-preinit] Version - HV000001: Hibernate Validator 5.2.4.Final [WARN ] 2016-10-11 11:22:54.798 [main] AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [pl.kaczynski.RestApplication]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport [ERROR] 2016-10-11 11:22:54.907 [main] SpringApplication - Application startup failed org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [pl.kaczynski.RestApplication]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:546) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:286) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:237) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:204) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:173) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE] at pl.kaczynski.RestApplication.main(RestApplication.java:11) [classes/:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_31] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_31] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_31] at java.lang.reflect.Method.invoke(Method.java:483) ~[?:1.8.0_31] at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:?] Caused by: java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:163) ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:301) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:237) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:537) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] ... 21 more Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContext at java.lang.Class.getDeclaredMethods0(Native Method) ~[?:1.8.0_31] at java.lang.Class.privateGetDeclaredMethods(Class.java:2693) ~[?:1.8.0_31] at java.lang.Class.getDeclaredMethods(Class.java:1967) ~[?:1.8.0_31] at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:152) ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:301) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:237) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:537) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] ... 21 more Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContext at java.net.URLClassLoader$1.run(URLClassLoader.java:372) ~[?:1.8.0_31] at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[?:1.8.0_31] at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_31] at java.net.URLClassLoader.findClass(URLClassLoader.java:360) ~[?:1.8.0_31] at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_31] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[?:1.8.0_31] at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_31] at java.lang.Class.getDeclaredMethods0(Native Method) ~[?:1.8.0_31] at java.lang.Class.privateGetDeclaredMethods(Class.java:2693) ~[?:1.8.0_31] at java.lang.Class.getDeclaredMethods(Class.java:1967) ~[?:1.8.0_31] at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:152) ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:301) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:237) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:537) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE] ... 21 more </code></pre> <p>so folks, how should I do this in IntelliJ ??</p>
<p>You need to create the Run Configuration. Run -> Edit Configurations and add new configuration. Choose Spring boot and specify the main class and it should do it.</p>
Why componentDidMount gets called multiple times in react.js & redux? <p>I read <code>componentDidMount</code> gets called only once for initial rendering but I'm seeing it's getting rendered multiple times.</p> <p>It seems I created a recursive loop.</p> <ul> <li>componentDidMount dispatches action to fetch data</li> <li>upon receiving the data, it fires success action to store the data in redux state.</li> <li>a parent react component is connected to redux store and has <code>mapStateToProps</code> for the entry that just changed in the above step</li> <li>parent renders child components (which is programmatically selected via variable)</li> <li>the child component's componentDidMount gets called again</li> <li>it dispaches action to fetch data</li> </ul> <p>I think that's what's happening. I may be wrong. </p> <p>How can I stop the loop?</p> <p>Here's the code for programmatically rendering child components.</p> <pre><code> function renderSubviews({viewConfigs, viewConfig, getSubviewData}) { return viewConfig.subviewConfigs.map((subviewConfig, index) =&gt; { let Subview = viewConfigRegistry[subviewConfig.constructor.configName] let subviewData = getSubviewData(subviewConfig) const key = shortid.generate() const subviewLayout = Object.assign({}, subviewConfig.layout, {key: key}) return ( &lt;div key={key} data-grid={subviewLayout} &gt; &lt;Subview {...subviewData} /&gt; &lt;/div&gt; ) }) } </code></pre>
<p>A component instance will only get mounted once and unmounted when it gets deleted. In your case it gets deleted and recreated.</p> <p>The point of the <code>key</code> prop is to help React find the previous version of the same component. That way it can update a previous component with new props rather than create a new one. </p> <p>React can often work fine without a key, the exception being a list with items. It wants a key there so it can keep track when items get rearranged, created or deleted.</p> <p>In your case, you are explicitly telling React that your component is different from the previous one. You're giving a new key on each render. This forces React to treat the previous instance as having been deleted. Any children of that component are also unmounted and dismantled.</p> <p>What you ought to do is not (ever) generate a key at random. Keys should always be based on the identity of the data a component is displaying. If it's not a list item you probably don't need a key. If it is a list item, it's much better to use a key derived from the data's identity, such as an ID property, or maybe a combination of multiple fields.</p> <p>If generating a random key would have been the correct thing to do, React would have just taken care of that for you.</p> <p>You should place your initial fetch code in the root of your React tree, usually that's <code>App</code>. Don't put it in some random child. At least you should put it in a component that exist for the lifetime of your app.</p> <p>The main reason to put it in <code>componentDidMount</code> is so it doesn't run on the server, because server-side components never get mounted. This is important for universal rendering. Even if you're not doing this now, you might do this later, and being prepared for it is a best practice. </p>
What is the Regression algo to Use for this case? <p>Having this Data :</p> <pre><code>clientId zipCode codeHeatingType countingType consumptionProfile householdCount squareFootage 01 75015 ELEC P012 A400 6 25 02 75002 GAZ P011 A600 3 30 </code></pre> <p>and the AvgConsumtion</p> <pre><code>clientId AvgConsumption 01 300.5 (KWH) 02 400 (KWH) </code></pre> <p>What machine learning to use to estimate the Avgconsumption depending on the client characteristics ? LogisticRegression ?, multilabel classification ?...</p> <p>is it possible to have an exemple with string colums ?</p>
<p>You need a regression algorithm that predicts a continuous variable. You can find the list of regression algorithms implemented in <code>spark.ml</code> <a href="http://spark.apache.org/docs/latest/ml-classification-regression.html#regression" rel="nofollow">here</a> with exemples.</p> <p>Categorical predictors can be transformed in various ways using non-parametric (non-optimized) <code>Transformer</code> (see <a href="http://spark.apache.org/docs/latest/ml-features.html" rel="nofollow">http://spark.apache.org/docs/latest/ml-features.html</a>). For instance <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.ml.feature.OneHotEncoder" rel="nofollow">OneHotEncoder</a> will convert a categorical predictors in a set of binary predictors. Exemples are provided in the <a href="http://spark.apache.org/docs/latest/ml-features.html#onehotencoder" rel="nofollow">documentation</a>.</p> <p>Note: inform you on some basics in machine learning before trying too much. There is a series of pitfalls that are purely of statistical nature. For specific questions, ask <a href="http://stats.stackexchange.com/">here</a></p>
Windows IOT printer support <p>I want to make usb printer work with Windows IOT (Raspberry PI), so I need a universal print driver compiled for ARM architecture. But I haven't found any out of box solutions for this. Tried to write it, but can't find a good tutorial.</p> <p>Is there any out of box solutions? If no, maybe there is any open-source implementation that can be compiled for ARM processor? Or maybe good tutorial how to implement it?</p> <p>P.S. Please don't recommend changing Windows IOT to Raspbian with Gutenprint. It's not sutable for my case.</p>
<h1>Suggestions:</h1> <h2>GDI</h2> <ol> <li>Turn on your raspberry pi, and browse to the c:\windows\system32 folder as shown in the picture below<br> <a href="https://i.stack.imgur.com/bWeUu.png" rel="nofollow"><img src="https://i.stack.imgur.com/bWeUu.png" alt="enter image description here"></a></li> <li>Copy the gdi32.dll and gdi32min.dll files from the raspberry pi "Windows Iot" image to your local pc. In this example I have copied them to my downloads folder.</li> <li><p>Open visual studio command prompt for ARM and follow the steps in the screenshot below: <a href="https://i.stack.imgur.com/UeqxV.png" rel="nofollow"><img src="https://i.stack.imgur.com/UeqxV.png" alt="enter image description here"></a></p></li> <li><p>Examine the output in those 2 text files and ascertain which gdi functions are available.</p></li> <li>You would then need to test each function that you might need to use and make sure it doesn't return "not implemented" or something similar.</li> <li>Here is a link to a tutorial for printing from the GDI <a href="http://www.codeproject.com/Articles/764057/GDI-Drawing-and-Printing" rel="nofollow">http://www.codeproject.com/Articles/764057/GDI-Drawing-and-Printing</a></li> </ol> <p>So it looks like only old-school GDI functions are available, however this would be most similar to "universal" print driver output.</p> <h2>Or Postscript / HP PCL</h2> <p>Write your own postscript output. On Linux this can be accomplished by dumping postscript codes directly to the printer over the network via cups, or usb via cups. This is by far the easiest solution.</p> <h2>Or line mode</h2> <p>Use a line-mode printer over rs232 (receipt printer, zebra, intermec, it is 1970's technology, but still works - no graphics though)</p>
Hibernate CRUD with lists <p>If I have entitys:</p> <ol> <li>Entity1 has list with Entity2;</li> <li>Entity2 has list with Entity3;</li> <li>Entity3 has list with Entity4;</li> </ol> <p>What is operations in my code I have to do when I add new Entity4 in DB?</p> <ol> <li>Just set parent for Entity4 and save Entity4?</li> </ol> <p>or</p> <ol start="2"> <li>Set parent for Entity4 and save Entity4. Add Entity4 in list of Entity3 and save Entity3.</li> </ol> <p>or</p> <ol start="3"> <li>Add Entity4 in list of Entity3 and save Entity3. And All Entitys will be update.</li> </ol>
<p>It really depends on whether the list maintained by <code>Entity3</code> is set to cascade operations such as <code>PERSIST</code>, <code>MERGE</code>, and <code>DELETE</code>. </p> <p>If the list is configured to cascade, then all you'd need to do is:</p> <ul> <li>Set the parent of <code>Entity4</code>.</li> <li>Add <code>Entity4</code> to its parent's list and merge the modified parent.</li> </ul> <p>If cascade is not configured, then you'd need to do:</p> <ul> <li>Set the parent of <code>Entity4</code>.</li> <li>Persist the newly created instance <code>Entity4</code>.</li> <li>Add <code>Entity4</code> to its parent's list and merge the modified parent.</li> </ul> <p>Now you may ask why must the parent entity of <code>Entity4</code> have its list updated and subsequently merged in either case? </p> <p>That is to make sure that both sides of the association are updated correctly and properly point to one another. Its very likely given the scenario that the parent side of the association is already loaded into the persistence context, so adding the child to the database won't refresh and be visible to an already loaded entity unless its refreshed. The easiest solution in this case is to always modify both sides correctly.</p> <pre><code>public class ParentEntity { // add child to the parent entity, maintains association public void addChild(ChildEntity child) { if ( child.getParent() != null ) { child.getParent().removeChild( child ); } child.setParent( this ); children.add( child ); } // remove child from parent, disassociates association public void removeChild(ChildEntity child) { if ( this.equals( child.getParent() ) ) { child.setParent( null ); children.remove( child ); } } } </code></pre> <p>I usually find it helpful to expose helper methods like the above on my domain models so that my code doesn't need to be concerned with the associations required to be maintained. I also would likely make the setter for the parent entity's list private so that only Hibernate can use it if needed to force strict use of the <code>addChild</code> / <code>removeChild</code> methods.</p>
How to build a sandbox environment <p>Hi SecurityManager Experts out there ;-)</p> <p>I have written a small plugin framework that loads plugins with separate isolated classloaders. For a successfull undeploy of a plugin it is important to make sure that no reference to classes loaded by the plugin classloader are held by the application.</p> <p>There is a feature in Java called shutdown hook that enables client code to register a thread that is executed when the JVM was requested to shut down. This implies that potentially there will be references held by the JVM to a class loaded by the plugin classloader. </p> <p>My first attempt was to install a SecurityManager that denies adding a shutdown hook. This totally works and denies all attempts to add shutdown hooks. The interesting thing is, that I realized, that it is not the plugin itself that wants to add a shutdown hook. The plugin just triggers the AWT/Swing internals (precise: <code>SunFontManager</code>) by loading a font. The <code>SunFontManager</code> in turn adds the shutdown hook to do some of it's internal handling when the JVM exits. I do not want to deny that the plugin loads a font (because it has to) and I do not want do deny the Java internals to add their stuff.</p> <p>For me it seems that I would have to grant more permissions to the code (if the <code>sun.*|java.*|javax.*</code> package is in the stack trace..uuuhmm...ugly) than it would have normally. But this breaks the conventions of the security framework which assumes that client code cannot have more privileges than code that is calling it.</p> <p>How can I distinguish that it is not the plugin code but the Java internals that wants to do something? Or is there any other way to make sure not to corrupt the internals by denying something?</p> <h2>Example of what happens</h2> <p>To make things clearer, here is what actually happens in my application. I have a custom SecurityManager installed that should deny <code>addShutdownHook</code> performed directly by plugins, but should not deny those calls if performed as a side-effect by Java internal classes.</p> <pre> Context: Calls: ---------------------------------------------- AppClassloader Application | PluginClassloader PluginObject.init() | AppClassloader Font.create() | AccessController.doPrivileged(...) { Runtime.addShutdownHook(...) } </pre> <p>The SecurityManager was installed using <code>System.setSecurityManager()</code> and does this:</p> <pre><code>@Override public void checkPermission(java.security.Permission perm) { if (perm.getName().equals("shutdownHooks")) { if (threadContextClassLoaderIsPluginClassLoader()) { throw new SecurityException("Installing shutdown hooks is not allowed."); } } } </code></pre> <p>Although the <code>addShutdownHook</code> is called inside a <code>doPrivileged</code>-block my <code>SecurityManager</code> is called. Am I missing something? Should I check for the privileged context myself?</p>
<p>I found out that I was totally misunderstanding the Java security concept. I want to build a sandbox for plugin code so that it is always running in a restricted environment where I can control the permissions it has. The application should always run alongside with full access granted. </p> <p>Here is how to build a sandbox for classes loaded by a separate classloader:</p> <ol> <li><strong>Use the default SecurityManager</strong> If you find yourself implementing your own <code>java.lang.SecurityManager</code> to allow or deny actions based on permissions you are probably doing wrong! You only need to install the default <code>java.lang.SecurityManager</code> by doing this <code>System.setSecurityManager(new SecurityManager());</code>. Now you get a working access control by using Java defaults.</li> <li><p><strong>Grant all permissions to application</strong> The application that loads the plugins should get full access. This is because we trust ourselves. I solved this by starting my application with a policy file that grants all access. I think the policy file is needed on application start because the AppClassLoader needs to create the correct protection domains for the classes. Start the main application with the JavaVM argument <code>java.security.policy=&lt;URL-TO-POLICY&gt;</code> where <code>&lt;URL-TO-POLICY</code> points to the following policy file:</p> <p><code>grant { permission java.security.AllPermission; };</code> </p></li> <li><p><strong>Custom policy implementation</strong> We need to install our custom policy after application startup. We want to separate the permissions for the main application (which runs with full access granted) and the plugins (which permissions we want to limit). The plugins should run in a sandbox with hand-picked permissions. To achieve this, here is the custom policy implementation:</p> <pre><code>class SandboxPolicy extends Policy { @Override public PermissionCollection getPermissions(ProtectionDomain domain) { // Decide if the plugin permissions are needed or full access can be granted using all permissions. if (isPlugin(domain)) { return pluginPermissions(); } else { return applicationPermissions(); } } private boolean isPlugin(ProtectionDomain domain) { // Identify the classloader of the protection domain // The PluginClassLoader is assumed to be the one that loaded // the plugin return domain.getClassLoader() instanceof PluginClassLoader; } private PermissionCollection pluginPermissions() { // Empty permissions = No permissions // This is not the point to add plugin permissions return new Permissions(); } private PermissionCollection applicationPermissions() { // Grant full access to the application Permissions permissions = new Permissions(); permissions.add(new AllPermission()); return permissions; } } </code></pre></li> <li><p><strong>ProtectionDomains per Classloader</strong> The classloaders are responsible to create a <code>ProtectionDomain</code> for every source, code is loaded from. The protection domains specify the permissions that will be granted to the code. We have to modify the set of permissions the classloader adds to the protection domains. To do this, let your PluginClassloader extend the <code>java.security.SecureClassLoader</code>. Then override the method <code>java.security.SecureClassLoader.getPermissions(CodeSource)</code> in the following way: </p> <pre><code>@Override protected PermissionCollection getPermissions(CodeSource codeSource) { PermissionCollection pc; // The SecureClassloader per default grants access to read resources from the source JAR. // This is useful. Call super to get those permissions: pc = super.getPermissions(codeSource); // At this point you can extend permissions. // For example grant read access to a file. pc.add(new FilePermission("path\\file", "read")); return (pc); } </code></pre></li> </ol> <p><strong>Note:</strong> See the policy implementation and have a look at my comment <code>// This is not the point to add plugin permissions</code>. The policy is asked by the <code>AccessController</code> to see if a permission can be granted. If permissions are added here, the information you can get from the caller are very limited. I woul not recommend to calculate and add any permissions here. The classloader is the point where you can add permissions based on the code source. I recommend to add permissions here. They become visible in the protection domains and you can easily observe what the AccessController is doing with those protection domains.</p> <p><strong>Privileged actions</strong></p> <p>There is another part in my question that I want to answer. </p> <blockquote> <p>The interesting thing is, that I realized, that it is not the plugin itself that wants to add a shutdown hook. The plugin just triggers the AWT/Swing internals (precise: SunFontManager) by loading a font.</p> </blockquote> <p>There are actions that will be performed as a side effect of plugin code. A class <code>org.plugin.A</code> can trigger the Swing/AWT internals to add a shutdown hook. In this case we do not want to deny this. The Java classes are in scope of the application and should get full access. The plugin code may be restricted and adding a shutdown hook directly should fail with <code>SecurityException</code>. This is a common use-case of <code>java.security.AccessController.doPrivileged(PrivilegedAction&lt;T&gt;)</code>. A privileged action makes sure that the <code>AccessController</code> will only take the protection domain of the last stack frame into account. AWT/Swing is adding its shutdown hook inside a privileged action and therefore is allowed to do so, because the protection domain of the classes performin this action where setup with full access permission. Please refer to any documentation of <code>java.security.AccessController</code> to learn more about privileged actions.</p>
sync threads to read different resources at exactly the same time <p>I have two cameras and this is important to read the frames with OpenCV exactly at the same time, I thought something like <code>Lock</code> but I cannot figure out the way I can implement this, I need some trigger to push and enable the threads to read frames, and then wait for another trigger hit, something like below:</p> <pre><code>def get_frame(queue, cap): while running: if(read_frame): queue.put(cap.read()); else: # without this sleep this function just consumes unnecessary CPU time time.sleep(some_time); q = Queue.Queue() # for every camera for u in xrange(2): t = threading.Thread(target=get_frame, args = (q, caps[u])) t.daemon = True t.start() </code></pre> <p>The problems with the above implementation are:</p> <ol> <li>I need the sleep time to be defined since I don't know the delay in between every frame read(i.e it might be long or short, depending on the calculation)</li> <li>This does not enable me to read once for every trigger hit. </li> </ol> <p>So this approach won't work, Any suggestions?</p>
<p>Consider getting FPS from VideoCapture. Also, note the difference between VideoCapture.grab and VideoCapture.retrieve frame. This is used for camera synchronization.</p> <p>First call VideoCapture#grab for both cameras and then retrieve the frames. See <a href="http://docs.opencv.org/trunk/d8/dfe/classcv_1_1VideoCapture.html#ae38c2a053d39d6b20c9c649e08ff0146" rel="nofollow">docs</a>.</p>
What happened to VMDepot? <p>I know that bitnami has moved all his images to the Azure Marketplace, but there was others VM on vmdepot. Now there is no simple way to share virtual machines on Azure.</p>
<p>As you mentioned, Microsoft Azure decide to removed their old VM Depot Marketplace and all the Bitnami Images have been moved to their new Marketplace: </p> <p><a href="https://azure.microsoft.com/en-us/marketplace/" rel="nofollow">https://azure.microsoft.com/en-us/marketplace/</a>.</p> <p>You can create your a virtual machine image for the Azure Marketplace and publish it following the guide below:</p> <p><a href="https://azure.microsoft.com/en-us/documentation/articles/marketplace-publishing-vm-image-creation/" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/marketplace-publishing-vm-image-creation/</a></p>
Error:(90, 58) error: cannot find symbol variable drawable <p>I am a begginer in Java for Android development. I am reading a book called "Android Application Development for Dummies". In chapter 5 of the book, the following code snippet is given which is not working.</p> <p>Can someone please help me know what I'm doing wrong within the code? All help is appreciated.</p> <pre><code>package helloandroid.android.dummies.com.silentmodetoggle; import android.support.v7.app.AppCompatActivity; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private AudioManager mAudioManager; private boolean mPhoneIsSilent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setButtonClickListener(); mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); checkIfPhoneIsSilent(); setButtonClickListener(); } private void setButtonClickListener() { Button toggleButton = (Button) findViewById(R.id.toggleButton); toggleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mPhoneIsSilent) { //Change back to silent mode mAudioManager .setRingerMode(AudioManager.RINGER_MODE_NORMAL); mPhoneIsSilent = false; } else { // Change to silent mode mAudioManager .setRingerMode(AudioManager.RINGER_MODE_SILENT); mPhoneIsSilent = true; } // Now toggle the UI again toggleUI(); } }); } /** * Checks to see if the phone is currently in silent mode */ private void checkIfPhoneIsSilent() { int ringerMode = mAudioManager.getRingerMode(); if (ringerMode == AudioManager.RINGER_MODE_SILENT) { mPhoneIsSilent = true; } else { mPhoneIsSilent = false; } } /** * Toggles the UI images from silent to normal and vice versa */ private void toggleUI() { ImageView imageView = (ImageView) findViewById(R.id.phone_icon); Drawable newPhoneImage; if (mPhoneIsSilent) { newPhoneImage = getResources(drawable.phone_silent } else { newPhoneImage = getResources(drawable.phone_on); } imageView.setImageDrawable(newPhoneImage); } @Override protected void onResume() { super.onResume(); checkIfPhoneIsSilent(); toggleUI(); } } </code></pre> <p>Some kindly offer to help. Thank you.</p> <pre><code>UPDATE 10-12 13:53:28.672 2965-2965/? D/dalvikvm: Not late-enabling CheckJNI (already on) 10-12 13:53:28.692 2965-2965/helloandroid.android.dummies.com.silentmodetoggle E/Trace: error opening trace file: No such file or directory (2) 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.app.Application.registerOnProvideAssistDataListener, referenced from method com.android.tools.fd.runtime.BootstrapApplication.registerOnProvideAssistDataListener 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve virtual method 231: Landroid/app /Application;.registerOnProvideAssistDataListener (Landroid/app /Application$OnProvideAssistDataListener;) 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.app.Application.unregisterOnProvideAssistDataListener, referenced from method com.android.tools.fd.runtime.BootstrapApplication.unregisterOnProvideAssistDataLis tener 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve virtual method 234: Landroid/app /Application;.unregisterOnProvideAssistDataListener (Landroid/app /Application$OnProvideAssistDataListener;)V 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/InstantRun: Instant Run Runtime started. Android package is helloandroid.android.dummies.com.silentmodetoggle, real application class is </code></pre> <p>null.</p> <pre><code>10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/InstantRun: No instant run dex files added to classpath 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve check-cast 1884 (Landroid/util/ArrayMap;) in Lcom/android /tools/fd/runtime/MonkeyPatcher; 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x1f at 0x025e 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.MonkeyPatcher.pruneResourceCache 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve const-class 1884 (Landroid/util/ArrayMap;) in Lcom/android /tools/fd/runtime/MonkeyPatcher; 10-12 13:53:28.703 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x1c at 0x0060 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve interface method 15983: Landroid/view /Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid /view/Menu;I)V 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;) 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve interface method 15985: Landroid/view /Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve interface method 15989: Landroid/view /Window$Callback;.onWindowStartingActionMode (Landroid/view /ActionMode$Callback;I)Landroid/view/ActionMode; 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve virtual method 669: Landroid/content /res/TypedArray;.getChangingConfigurations ()I 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: VFY: unable to resolve virtual method 691: Landroid/content /res/TypedArray;.getType (I)I 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle E/VdcInflateDelegate: Exception while inflating &lt;vector org.xmlpull.v1.XmlPullParserException: Binary XML file line #17&lt;vector&gt; tag requires viewportHeight &gt; 0 at </code></pre> <p>android.support.graphics.drawable.VectorDrawableCompat.updateStateFromTypedArray(</p> <pre><code>VectorDrawableCompat.java:544) at android.support.graphics.drawable.VectorDrawableCompat.inflate (VectorDrawableCompat.java:478) at </code></pre> <p>android.support.graphics.drawable.VectorDrawableCompat.createFromXmlInner</p> <pre><code>(VectorDrawableCompat.java:441) at android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate.createFromXmlInner(AppCompatDrawableManager.java:742) at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:362) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:185) at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:720) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190) at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:77) at android.support.v7.app.AppCompatDelegateImplBase.&lt;init&gt;(AppCompatDelegateImplBase.java:127) at android.support.v7.app.AppCompatDelegateImplV9.&lt;init (AppCompatDelegateImplV9.java:147) at android.support.v7.app.AppCompatDelegateImplV11.&lt;init&gt; (AppCompatDelegateImplV11.java:27) at android.support.v7.app.AppCompatDelegateImplV14.&lt;init&gt; (AppCompatDelegateImplV14.java:50) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181) at </code></pre> <p>android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521) at </p> <pre><code>android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71) at helloandroid.android.dummies.com.silentmodetoggle.MainActivity.onCreate(MainActivity.java:18) at android.app.Activity.performCreate(Activity.java:5008) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) at android.app.ActivityThread.access$600(ActivityThread.java:130) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at </code></pre> <p>com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Metho 10-12 13:53:28.732 </p> <pre><code> 2965-2965/helloandroid.android.dummies.com.silentmodetoggle D/AndroidRuntime: Shutting down VM 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb2e51288) 10-12 13:53:28.732 2965-2965/helloandroid.android.dummies.com.silentmodetoggle E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{helloandroid.android.dummies.com.silentmodetoggle/helloandroid.andro id.dummies.com.silentmodetoggle.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable /abc_vector_test.xml from drawable resource ID #0x7f02005 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) at android.app.ActivityThread.access$600(ActivityThread.java:13 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at </code></pre> <p>com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) Caused by: android.content.res.Resources$NotFoundException: File res/drawable</p> <pre><code>/abc_vector_test.xml from drawable resource ID #0x7f020052 at android.content.res.Resources.loadDrawable(Resources.java:1918) at android.content.res.Resources.getDrawable(Resources.java:659) at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:346) at </code></pre> <p>android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:185) at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:720) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190) at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:77) at android.support.v7.app.AppCompatDelegateImplBase. (AppCompatDelegateImplBase.java:127) at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:147) at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:27) at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:50) at </p> <pre><code>android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181) at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521) at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71) at helloandroid.android.dummies.com.silentmodetoggle.MainActivity.onCreate(MainActivity.java:18) at android.app.Activity.performCreate(Activity.java:5008) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)  at android.app.ActivityThread.access$600(ActivityThread.java:130)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:137)  at android.app.ActivityThread.main(ActivityThread.java:4745)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)  at dalvik.system.NativeStart.main(Native Method)  Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:877) at android.graphics.drawable.Drawable.createFromXml(Drawable.java:818) at android.content.res.Resources.loadDrawable(Resources.java:1915) at android.content.res.Resources.getDrawable(Resources.java:659)  at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:346)  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:185)  at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:720)  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190)  at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:77)  at android.support.v7.app.AppCompatDelegateImplBase.&lt;init&gt;(AppCompatDelegateImplBase.java:127)  at android.support.v7.app.AppCompatDelegateImplV9.&lt;init&gt;(AppCompatDelegateImplV9.java:147)  at android.support.v7.app.AppCompatDelegateImplV11.&lt;init&gt;(AppCompatDelegateImplV11.java:27)  at android.support.v7.app.AppCompatDelegateImplV14.&lt;init&gt;(AppCompatDelegateImplV14.java:50)  at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)  at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)  at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)  at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)  at helloandroid.android.dummies.com.silentmodetoggle.MainActivity.onCreate(MainActivity.java:18)  at android.app.Activity.performCreate(Activity.java:5008)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)  at android.app.ActivityThread.access$600(ActivityThread.java:130)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:137)  at android.app.ActivityThread.main(ActivityThread.java:4745)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)  at dalvik.system.NativeStart.main(Native Method)  10-12 13:53:28.752 2965-2969/helloandroid.android.dummies.com.silentmodetoggle D/dalvikvm: GC_CONCURRENT freed 305K, 7% free 6071K/6471K, paused 16ms+1ms, total 18ms 10-12 13:53:31.472 2965-2965/? I/Process: Sending signal. PID: 2965 SIG: 9 </code></pre> <blockquote> <p>The above is the Exception Logcat which I found very difficult to paste However, somehow I managed. Your updated and edited answer is giving an error at the "else" block.</p> </blockquote>
<p><strong>Do something like this</strong></p> <pre><code>private void toggleUI() { ImageView imageView = (ImageView) findViewById(R.id.phone_icon); if (imageView != null) { int imageResId = mPhoneIsSilent ? R.drawable.phone_silent : R.drawable.phone_on; imageView.setImageResource(imageResId); } else { Log.e("ERR", "ImageView is null"); } } </code></pre>
Transpose result of hibernate query into list of POJOs <p>I got a generics class that contains runQuery method that has following code setup:</p> <pre><code>public Object runQuery(String query) { Query retVal = getSession().createSQLQuery(query); return retVal.list(); } </code></pre> <p>I am trying to figure out how to transpose the returned values into a list of Check objects (List):</p> <pre><code>public class Check { private int id; private String name; private String confirmationId; //getters and setters } </code></pre> <p>Most queries that i run are actually stored procs in mysql. I know of native queries and resultTransforms (which if implemented would mean i have to change my generics and not after that). Any ideas how i can accomplish this with current setup?</p>
<p>You can find tutorials on ORMs ( <a href="http://stackoverflow.com/questions/7067860/what-is-object-relational-mappingorm-in-relation-to-hibernate-and-jdbc">What is Object/relational mapping(ORM) in relation to Hibernate and JDBC?</a> ). </p> <p>Basically, you add annotation to your Check class to tell hibernate which java fields matches which DB field, make a JPQL (it looks like SQL) request and it gets your object and maps them from DB to POJO.</p> <p>It's a broad subject, this is a good start: <a href="https://www.tutorialspoint.com/hibernate/hibernate_quick_guide.htm" rel="nofollow">https://www.tutorialspoint.com/hibernate/hibernate_quick_guide.htm</a> It will require some configuration, but that's worth it. Here's one tutorial on annotation based configuration: <a href="https://www.tutorialspoint.com/hibernate/hibernate_annotations.htm" rel="nofollow">https://www.tutorialspoint.com/hibernate/hibernate_annotations.htm</a> but with less explanations on how ORM works (there's also EclipseLink as an ORM)</p> <p>Else, you could make you're own mapper, which takes values from a <code>ResultSet</code>, and set them in your class. For a lot of reason, I would recommand using an ORM than this method (Except maybe if you have only one class that is stored in the DB, which I doubt).</p>
How do I get the second Item in an Iteration? <p><strong>I get the first item like this:</strong></p> <pre><code>{foreach $sArticle.sBlockPrices as $blockPrice} {if $blockPrice@first} First element {else} ... {/if} {/foreach} </code></pre> <p>How do I get the second/third item?</p>
<p>Use the index property of foreach referenced here: <a href="http://www.smarty.net/docsv2/en/language.function.foreach.tpl" rel="nofollow">http://www.smarty.net/docsv2/en/language.function.foreach.tpl</a></p> <p>Try something like this: </p> <pre><code>{foreach name=$sArticle.sBlockPrices item=$blockPrice name=blockPrices} {if $smarty.foreach.blockPrices.index == 2} ... {/if} {/foreach} </code></pre>
shopt -s autocd missing when inside tmux? <p>It's very strange. I have <code>shopt -s autocd</code> set within my <code>.bashrc</code> file and if I run <code>shopt -p</code> in my shell I can see that it's available (and set).</p> <p>But the moment I start up a tmux shell and run <code>shopt -p</code> the autocd option is no longer shown and any attempt to just move into a directory without a <code>cd</code> command prefixing it will fail with a message saying <code>-bash: /Users/me/some/directory: is a directory</code></p> <p>Here is the output of <code>shopt -p</code> <em>inside</em> tmux...</p> <pre><code>shopt -u cdable_vars shopt -s cdspell shopt -u checkhash shopt -s checkwinsize shopt -s cmdhist shopt -u compat31 shopt -s dotglob shopt -u execfail shopt -s expand_aliases shopt -u extdebug shopt -s extglob shopt -s extquote shopt -s failglob shopt -s force_fignore shopt -s gnu_errfmt shopt -s histappend shopt -u histreedit shopt -u histverify shopt -u hostcomplete shopt -s huponexit shopt -s interactive_comments shopt -u lithist shopt -s login_shell shopt -u mailwarn shopt -u no_empty_cmd_completion shopt -s nocaseglob shopt -u nocasematch shopt -u nullglob shopt -s progcomp shopt -s promptvars shopt -u restricted_shell shopt -u shift_verbose shopt -s sourcepath shopt -u xpg_echo </code></pre> <p>Here is the output of <code>shopt -p</code> <em>outside</em> tmux...</p> <pre><code>shopt -s autocd shopt -u cdable_vars shopt -s cdspell shopt -u checkhash shopt -u checkjobs shopt -s checkwinsize shopt -s cmdhist shopt -u compat31 shopt -u compat32 shopt -u compat40 shopt -u compat41 shopt -u compat42 shopt -s complete_fullquote shopt -u direxpand shopt -s dirspell shopt -s dotglob shopt -u execfail shopt -s expand_aliases shopt -u extdebug shopt -s extglob shopt -s extquote shopt -u failglob shopt -s force_fignore shopt -u globstar shopt -u globasciiranges shopt -s gnu_errfmt shopt -s histappend shopt -u histreedit shopt -u histverify shopt -u hostcomplete shopt -s huponexit shopt -s interactive_comments shopt -u lastpipe shopt -u lithist shopt -s login_shell shopt -u mailwarn shopt -u no_empty_cmd_completion shopt -s nocaseglob shopt -u nocasematch shopt -u nullglob shopt -s progcomp shopt -s promptvars shopt -u restricted_shell shopt -u shift_verbose shopt -s sourcepath shopt -u xpg_echo </code></pre>
<p><code>tmux</code> creates a login shell by default for each new window/pane. This means <code>.bash_profile</code> (or possibly <code>.profile</code> or <code>.bash_login</code>, depending on the available files) is executed, not <code>.bashrc</code>. See the man page for information on the <code>default-shell</code> and <code>default-conmand</code> options.</p> <p>(The name of the current shell in the error message, <code>-bash</code>, also confirms that you are in a login shell, not a regular interactive shell.)</p>
SourceTree install behaving strangely <p>Hi we are in the process of transitioning to Git/SourceTree/Bitbucket and are a bit new to this. I installed Source Tree on a colleagues machine and few funny things happen which I don't remember happening on mine.</p> <ol> <li>SourceTree didn't have a version of Git installed - so it gave us an embedded option which we installed but I was a bit confused by</li> <li>There wasn't a default global git ignore we had to create one</li> <li>We couldn't stash we had to explicitly set the username and email in the terminal before it would work and even then it didn't seem to stash properly</li> </ol> <p>I suspect I've done something wrong/different during the install and I was wondering whether anyone could shed any light on this? Perhaps during the setup process with Altassian/activating a licence? Cheers. </p>
<p>I think this isn't really an issue, I reinstalled it and it started working. I've probably inadvertently done something without realizing it.</p>
SQL SUM() and ANGULAR.JS <p>I know how to connect, display, remove, add data from my database and display all of it on my website. Everthing works correctly. I see my results on my website and in my database. I do this with AngularJS, AJAX and PHP but my problem is I don't know how to dispaly MYSQL SUM() one of my column. For example this is my table in mysql and I would like to dispaly the total sum of the money column.</p> <pre><code>id money 1 23 2 345 3 111 </code></pre> <p>This is what I got:</p> <p><strong>index.html:</strong></p> <p>..................</p> <pre><code> &lt;table class="table table-striped"&gt; &lt;tr&gt; &lt;th&gt;Money&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{{ wcdrates.sumMoney }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>.................</p> <p>I don't know If I should leave ng-repeat as it is or use something different instead. Anyway ng-repeat dosent'work. It shows me all results from money column not the total SUM. ............</p> <p><strong>controller.js</strong></p> <p>.....................</p> <pre><code>$http.post('./php/showMoney.php') .success(function(data) { $scope.wcdrates = data; }) .error(function(err) { $log.error(err); }) </code></pre> <p>....................</p> <p><strong>connectDatabase.php</strong></p> <pre><code>&lt;?php define("__HOST__", "127.0.0.1"); define("__USER__", "root"); define("__PASS__", ""); define("__BASE__", "davbaza"); class DB { private $con = false; private $data = array(); public function __construct() { $this-&gt;con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__); if(mysqli_connect_error()) { die("DB connection failed:" . mysqli_connect_error()); } } public function qryPop() { $sql = "SELECT * FROM `wcdrates` ORDER BY `id` DESC"; $qry = $this-&gt;con-&gt;query($sql); if($qry-&gt;num_rows &gt; 0) { while($row = $qry-&gt;fetch_object()) { $this-&gt;data[] = $row; } } else { $this-&gt;data[] = null; } $this-&gt;con-&gt;close(); } public function qryFire($sql=null) { if($sql == null) { $this-&gt;qryPop(); } else { $this-&gt;con-&gt;query($sql); $this-&gt;qryPop(); } //$this-&gt;con-&gt;close(); return $this-&gt;data; } } </code></pre> <p>?></p> <p><strong>showMoney.php</strong></p> <pre><code>&lt;?php include('connectDatabase.php'); $db = new DB(); $sql = "SELECT SUM(money) as sumMoney FROM wcdrates"; $data = $db-&gt;qryFire(); echo json_encode($data); </code></pre> <p>mysql</p> <pre><code> CREATE TABLE IF NOT EXISTS `wcdrates` ( `id` int(11) NOT NULL AUTO_INCREMENT, `money` int(11) NOT NULL, PRIMARY KEY (`id`) ) </code></pre> <p>I have no idea what I should change to get what I want.</p>
<p>change the <code>qryPop</code> in your code , to following code .</p> <pre><code> $sql = "SELECT id,money , SUM(money) as sumMoney FROM `wcdrates` ORDER BY `id` DESC"; </code></pre> <p>Hope you will get the answer</p>
Select left 4 characters without duplicates <p>I have a database table named <code>monthly</code>. One of the column names is <code>month</code>.</p> <p>Inside <code>month</code>, there is these few datas - <code>201601, 201602, 201501, 201502</code>.</p> <p>Now what I want to do is to get the first 4 characters from the LEFT (basically trying to just take the year value out) and display it without duplicates.</p> <p>This is the mySQL code that I tried:</p> <pre><code>SELECT LEFT(month,4) from monthly </code></pre> <p>This however is wrong. Can I know how do I write the query to get only the first 4 characters without any duplicate value? </p> <p>So for this, the result should be just <code>2015, 2016</code>.</p>
<pre><code>SELECT DISTINCT LEFT(month,4) AS `Year` FROM monthly </code></pre>
When to use static binding and when to use dynamic binding in Java? <p>Recently I am learning how to use Slf4j. And I know two new concepts:static binding and dynamic binding.In JCL(Jakarta Commons Logging) it use dynamic binding to choose the implementation while Slf4j is using static binding. In this case we know Slf4j is more wise.But how about other case? </p> <p>If we meet a problem that we can resolve it both in using static bingding and dynamic binding, then how we choose? Is there any basic rules?</p> <p>My English is not very good.So I am not sure whether i have made it clear.If you have more question , please comment. </p> <p>THX.</p>
<p>Here : <a href="http://javarevisited.blogspot.com/2012/03/what-is-static-and-dynamic-binding-in.html" rel="nofollow">Link</a></p> <p>Few important difference between static and dynamic binding</p> <p>1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.</p> <p>2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.</p> <p>3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.</p> <p>3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.</p> <p><strong>Static Binding Example in Java</strong></p> <pre><code> public class StaticBindingTest { public static void main(String args[]) { Collection c = new HashSet(); StaticBindingTest et = new StaticBindingTest(); et.sort(c); } //overloaded method takes Collection argument public Collection sort(Collection c) { System.out.println("Inside Collection sort method"); return c; } //another overloaded method which takes HashSet argument which is sub class public Collection sort(HashSet hs) { System.out.println("Inside HashSet sort method"); return hs; } } </code></pre> <p>Output: Inside Collection sort method</p> <p><strong>Example of Dynamic Binding in Java</strong></p> <pre><code> public class DynamicBindingTest { public static void main(String args[]) { Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car vehicle.start(); //Car's start called because start() is overridden method } } class Vehicle { public void start() { System.out.println("Inside start method of Vehicle"); } } class Car extends Vehicle { @Override public void start() { System.out.println("Inside start method of Car"); } } </code></pre> <p>Output: Inside start method of Car</p>
How to use different middlewares for different paths in GO? <p>Hi I am using <a href="https://github.com/justinas/alice" rel="nofollow">justinas/alice</a>, and I want to create different middlewares based on paths. i.e if I have path1 and path2, I want to apply m1,m2,m3 for path 1 and m1,m2 for path 2</p> <p>I tried:</p> <ul> <li>Creating two mux routers first: </li> </ul> <p><code>router := mux.NewRouter() router2 := mux.NewRouter()</code></p> <ul> <li>Assign the paths to them:</li> </ul> <p><code>router.HandleFunc(path1,Func1) router2.HandleFunc(path2,Func2) </code></p> <ul> <li>Then I wanted to have something like this</li> </ul> <p><code>middlewares:=alice.New(m1,m2).Then(router2) middlewaress:=middlewares.Append(middlewares) </code> - Then:</p> <pre><code>if err := http.ListenAndServe(fmt.Sprintf(":%d", sconf.Server.Port), middlewaress); err != nil { } </code></pre> <p>how can I do something like this?</p>
<p>You need to let set the handlers for <code>router</code> and <code>router</code> to the returned chain from <code>alice</code>.</p> <pre><code>// define routers router := mux.NewRouter() // assuming this is gorilla mux router2 := mux.NewRouter() // create alice chains chain1 := alice.New(m1, m2, m3).Then(func1) chain2 := alice.New(m1, m2).Then(func2) // set chains as path handlers router.HandleFunc(path1, chain1) router2.HandleFunc(path2, chain2) </code></pre>
App Crash on iPad after update to XCode 8 <p>I updated XCode like MacOS suggested to XCode 8. I run my App on Simulator and it worked fine. But when i tried to run the App on my iPad the App crashed unexpected. <br> I was looking for the problem but couldn't find any place because it still runs on simulator. But then installed the older XCode 7.3.1 again and the app runs again on my iPad.<br> Here is the CrashLog :</p> <pre><code>Incident Identifier: 3756AFDE-0D06-4401-BD20-4352991F773B CrashReporter Key: ebdd050a249780097b3342e8a223149b3afac815 Hardware Model: iPad4,2 Process: BLAA [1057] Path: /private/var/containers/Bundle/Application/ECE0A2F1-B367-4AAD-8162-ED58E73C6C50/VISUS.app/VISUS Identifier: BLAA.server Version: 1.0 (1.0) Code Type: ARM-64 (Native) Parent Process: launchd [1] Date/Time: 2016-10-11 10:15:24.24 +0200 Launch Time: 2016-10-11 10:15:20.20 +0200 OS Version: iOS 9.3.2 (13F69) Report Version: 105 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Triggered by Thread: 0 Filtered syslog: None found Last Exception Backtrace: 0 CoreFoundation 0x180f3adb0 __exceptionPreprocess + 124 1 libobjc.A.dylib 0x18059ff80 objc_exception_throw + 56 2 Foundation 0x1818b4704 -[NSCoder(Exceptions) __failWithException:] + 132 3 Foundation 0x1818b48bc -[NSCoder(Exceptions) __failWithExceptionName:errorCode:format:] + 440 4 Foundation 0x1818833b8 _decodeObjectBinary + 2996 5 Foundation 0x18188274c _decodeObject + 304 6 UIKit 0x186567688 -[UINib instantiateWithOwner:options:] + 1220 7 UIKit 0x186409230 -[UIViewController _loadViewFromNibNamed:bundle:] + 376 8 UIKit 0x1861ce118 -[UIViewController loadView] + 176 9 UIKit 0x1860908ec -[UIViewController loadViewIfRequired] + 144 10 UIKit 0x1860a90d0 -[UIViewController __viewWillAppear:] + 132 11 UIKit 0x186243e5c -[UINavigationController _startCustomTransition:] + 1052 12 UIKit 0x18614fe40 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688 13 UIKit 0x18614fb1c -[UINavigationController __viewWillLayoutSubviews] + 60 14 UIKit 0x18614fa84 -[UILayoutContainerView layoutSubviews] + 208 15 UIKit 0x18608c1e4 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 656 16 QuartzCore 0x183a1e994 -[CALayer layoutSublayers] + 148 17 QuartzCore 0x183a195d0 CA::Layer::layout_if_needed(CA::Transaction*) + 292 18 QuartzCore 0x183a19490 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32 19 QuartzCore 0x183a18ac0 CA::Context::commit_transaction(CA::Transaction*) + 252 20 QuartzCore 0x183a18820 CA::Transaction::commit() + 500 21 QuartzCore 0x183a11de4 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 80 22 CoreFoundation 0x180ef0728 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 23 CoreFoundation 0x180eee4cc __CFRunLoopDoObservers + 372 24 CoreFoundation 0x180eee8fc __CFRunLoopRun + 928 25 CoreFoundation 0x180e18c50 CFRunLoopRunSpecific + 384 26 GraphicsServices 0x182700088 GSEventRunModal + 180 27 UIKit 0x1860fa088 UIApplicationMain + 204 28 VISUS 0x10004971c 0x100044000 + 22300 29 libdyld.dylib 0x1809b68b8 start + 4 Global Trace Buffer (reverse chronological seconds): 2.660349 CFNetwork 0x000000018160e0a4 NSURLConnection finished with error - code -1009 2.661763 CFNetwork 0x00000001815d9d50 HTTP load failed (error code: -1009 [12:8]) 2.664646 CFNetwork 0x000000018155d73c _CFNetworkIsConnectedToInternet returning 0, flagsValid: 1, flags: 0x0 2.665455 CFNetwork 0x00000001815c0220 TCP Conn 0x1275d8e80 Failed : error 0:-65554 [-65554] 2.665455 CFNetwork 0x00000001815bff18 TCP Conn 0x1275d8e80 complete. fd: -1, err: -65554 2.665700 CFNetwork 0x00000001815c1444 TCP Conn 0x1275d8e80 event 3. err: -65554 2.669860 CFNetwork 0x00000001815c151c TCP Conn 0x1275d8e80 started 2.672486 CFNetwork 0x000000018160e0a4 NSURLConnection finished with error - code -1009 2.672756 CFNetwork 0x00000001815d9d50 HTTP load failed (error code: -1009 [12:8]) 2.674290 CFNetwork 0x000000018155d73c _CFNetworkIsConnectedToInternet returning 0, flagsValid: 1, flags: 0x0 2.675165 CFNetwork 0x00000001815c0220 TCP Conn 0x1275ce3d0 Failed : error 0:-65554 [-65554] 2.675165 CFNetwork 0x00000001815bff18 TCP Conn 0x1275ce3d0 complete. fd: -1, err: -65554 2.676078 CFNetwork 0x00000001815c1444 TCP Conn 0x1275ce3d0 event 3. err: -65554 2.679100 CFNetwork 0x00000001815c151c TCP Conn 0x1275ce3d0 started 2.682027 CFNetwork 0x000000018160e0a4 NSURLConnection finished with error - code -1009 2.682605 CFNetwork 0x00000001815d9d50 HTTP load failed (error code: -1009 [12:8]) 2.685203 CFNetwork 0x000000018155d73c _CFNetworkIsConnectedToInternet returning 0, flagsValid: 1, flags: 0x0 2.686100 CFNetwork 0x00000001815c0220 TCP Conn 0x1276abba0 Failed : error 0:-65554 [-65554] 2.686100 CFNetwork 0x00000001815bff18 TCP Conn 0x1276abba0 complete. fd: -1, err: -65554 2.688915 CFNetwork 0x00000001815c1444 TCP Conn 0x1276abba0 event 3. err: -65554 2.691734 CFNetwork 0x00000001815c151c TCP Conn 0x1276abba0 started 2.693133 CFNetwork 0x000000018160e0a4 NSURLConnection finished with error - code -1009 2.693526 CFNetwork 0x00000001815d9d50 HTTP load failed (error code: -1009 [12:8]) 2.698032 CFNetwork 0x000000018155d73c _CFNetworkIsConnectedToInternet returning 0, flagsValid: 1, flags: 0x0 2.698793 CFNetwork 0x00000001815c0220 TCP Conn 0x1276a7fb0 Failed : error 0:-65554 [-65554] 2.698793 CFNetwork 0x00000001815bff18 TCP Conn 0x1276a7fb0 complete. fd: -1, err: -65554 2.699551 CFNetwork 0x00000001815c1444 TCP Conn 0x1276a7fb0 event 3. err: -65554 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x0000000180ad411c __pthread_kill + 8 1 libsystem_pthread.dylib 0x0000000180ba0ef8 pthread_kill + 112 2 libsystem_c.dylib 0x0000000180a45dac abort + 140 3 VISUS 0x000000010016c1b8 0x100044000 + 1212856 4 CoreFoundation 0x0000000180f3b138 __handleUncaughtException + 652 5 libobjc.A.dylib 0x00000001805a023c _objc_terminate() + 112 6 libc++abi.dylib 0x0000000180592f44 std::__terminate(void (*)()) + 16 7 libc++abi.dylib 0x0000000180592b10 __cxa_rethrow + 144 8 libobjc.A.dylib 0x00000001805a0120 objc_exception_rethrow + 44 9 CoreFoundation 0x0000000180e18cf8 CFRunLoopRunSpecific + 552 10 GraphicsServices 0x0000000182700088 GSEventRunModal + 180 11 UIKit 0x00000001860fa088 UIApplicationMain + 204 12 VISUS 0x000000010004971c 0x100044000 + 22300 13 libdyld.dylib 0x00000001809b68b8 start + 4 Thread 1: 0 libsystem_kernel.dylib 0x0000000180ad4b48 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000180b9d530 _pthread_wqthread + 1284 2 libsystem_pthread.dylib 0x0000000180b9d020 start_wqthread + 4 Thread 2 name: Dispatch queue: com.apple.libdispatch-manager Thread 2: 0 libsystem_kernel.dylib 0x0000000180ad54d8 kevent_qos + 8 1 libdispatch.dylib 0x00000001809987d8 _dispatch_mgr_invoke + 232 2 libdispatch.dylib 0x0000000180987648 _dispatch_source_invoke + 0 Thread 3: 0 libsystem_kernel.dylib 0x0000000180ad4b48 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000180b9d530 _pthread_wqthread + 1284 2 libsystem_pthread.dylib 0x0000000180b9d020 start_wqthread + 4 Thread 4: 0 libsystem_kernel.dylib 0x0000000180ad4b48 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000180b9d530 _pthread_wqthread + 1284 2 libsystem_pthread.dylib 0x0000000180b9d020 start_wqthread + 4 Thread 5: 0 libsystem_kernel.dylib 0x0000000180ad4b48 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000180b9d530 _pthread_wqthread + 1284 2 libsystem_pthread.dylib 0x0000000180b9d020 start_wqthread + 4 Thread 6 name: com.apple.NSURLConnectionLoader Thread 6: 0 libsystem_kernel.dylib 0x0000000180ab8fd8 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x0000000180ab8e54 mach_msg + 72 2 CoreFoundation 0x0000000180ef0c60 __CFRunLoopServiceMachPort + 196 3 CoreFoundation 0x0000000180eee964 __CFRunLoopRun + 1032 4 CoreFoundation 0x0000000180e18c50 CFRunLoopRunSpecific + 384 5 CFNetwork 0x0000000181599c68 +[NSURLConnection(Loader) _resourceLoadLoop:] + 412 6 Foundation 0x000000018190fe4c __NSThread__start__ + 1000 7 libsystem_pthread.dylib 0x0000000180b9fb28 _pthread_body + 156 8 libsystem_pthread.dylib 0x0000000180b9fa8c _pthread_body + 0 9 libsystem_pthread.dylib 0x0000000180b9d028 thread_start + 4 Thread 7: 0 libsystem_kernel.dylib 0x0000000180ad4b48 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000180b9d530 _pthread_wqthread + 1284 2 libsystem_pthread.dylib 0x0000000180b9d020 start_wqthread + 4 Thread 8: 0 libsystem_kernel.dylib 0x0000000180ad4b48 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000180b9d530 _pthread_wqthread + 1284 2 libsystem_pthread.dylib 0x0000000180b9d020 start_wqthread + 4 Thread 0 crashed with ARM Thread State (64-bit): x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0xffffffffffffffff x4: 0x0000000000000010 x5: 0x0000000000000010 x6: 0x0000000000000000 x7: 0x0000000000000000 x8: 0x0000000008000000 x9: 0x0000000004000000 x10: 0x0000000000003c57 x11: 0x00000001a14e96d9 x12: 0x00000001a14e96d9 x13: 0x0000000000000018 x14: 0x000000008000001f x15: 0x0000000080000023 x16: 0x0000000000000148 x17: 0x00000001001b8270 x18: 0x0000000000000000 x19: 0x0000000000000006 x20: 0x000000019f013000 x21: 0x0000000127709120 x22: 0x00000001275f7ce0 x23: 0x000000019f01f150 x24: 0x000000019f023000 x25: 0x96006092194ae3d3 x26: 0x0000000186abe5b0 x27: 0x0000000181171ba5 x28: 0x000000019e0f8588 fp: 0x000000016fdbb830 lr: 0x0000000180ba0ef8 sp: 0x000000016fdbb810 pc: 0x0000000180ad411c cpsr: 0x00000000 Binary Images: 0x100044000 - 0x1001b7fff VISUS arm64 &lt;fc9818f7896039468eae4a57c3cf30eb&gt; /var/containers/Bundle/Application/ECE0A2F1-B367-4AAD-8162-ED58E73C6C50/VISUS.app/VISUS 0x120048000 - 0x120077fff dyld arm64 &lt;488b8b4696fb312db76da956e6f5aef5&gt; /usr/lib/dyld 0x180520000 - 0x180521fff libSystem.B.dylib arm64 &lt;77c873c418a6317f821f7b706d5b7dc6&gt; /usr/lib/libSystem.B.dylib 0x180524000 - 0x180576fff libc++.1.dylib arm64 &lt;9ec0d9dcf728349582c26a7da72f0364&gt; /usr/lib/libc++.1.dylib 0x180578000 - 0x180597fff libc++abi.dylib arm64 &lt;aaa40b7f52513cf79c6f814b133556a7&gt; /usr/lib/libc++abi.dylib 0x180598000 - 0x180904fff libobjc.A.dylib arm64 &lt;939f392022903f2da2858e676e4191ef&gt; /usr/lib/libobjc.A.dylib 0x180908000 - 0x18090cfff libcache.dylib arm64 &lt;43424f4c7252330ca92c1a865da896e1&gt; /usr/lib/system/libcache.dylib 0x180910000 - 0x18091bfff libcommonCrypto.dylib arm64 &lt;e47d758d207e32c8ab546b59785d2ab8&gt; /usr/lib/system/libcommonCrypto.dylib 0x18091c000 - 0x18091ffff libcompiler_rt.dylib arm64 &lt;b77c451c7ffb356fb3c8368cac95d8f3&gt; /usr/lib/system/libcompiler_rt.dylib 0x180920000 - 0x180927fff libcopyfile.dylib arm64 &lt;1c1678aa36073b42b4406c6dbb06e9f0&gt; /usr/lib/system/libcopyfile.dylib 0x180928000 - 0x180983fff libcorecrypto.dylib arm64 &lt;b42ff635d1303d45bafe057e5a1e6243&gt; /usr/lib/system/libcorecrypto.dylib 0x180984000 - 0x1809b2fff libdispatch.dylib arm64 &lt;65568801b7463adeb6e20dc25d14d801&gt; /usr/lib/system/libdispatch.dylib 0x1809b4000 - 0x1809b6fff libdyld.dylib arm64 &lt;e1f151766d6e3755a1a59f62d9a3d9f9&gt; /usr/lib/system/libdyld.dylib 0x1809b8000 - 0x1809b8fff liblaunch.dylib arm64 &lt;fbb5f1442c3039188da689963efde4d8&gt; /usr/lib/system/liblaunch.dylib 0x1809bc000 - 0x1809c0fff libmacho.dylib arm64 &lt;1f37b179ad26307192b3b763ba5f816a&gt; /usr/lib/system/libmacho.dylib 0x1809c4000 - 0x1809c5fff libremovefile.dylib arm64 &lt;267c6cbaf2193309bd8a191fad38cc79&gt; /usr/lib/system/libremovefile.dylib 0x1809c8000 - 0x1809defff libsystem_asl.dylib arm64 &lt;fffe50d37b1c3f92af6f4a68a6d60068&gt; /usr/lib/system/libsystem_asl.dylib 0x1809e0000 - 0x1809e1fff libsystem_blocks.dylib arm64 &lt;8bbf799e57f93ed1be24cf2ce6c221a3&gt; /usr/lib/system/libsystem_blocks.dylib 0x1809e4000 - 0x180a63fff libsystem_c.dylib arm64 &lt;a05dd3ed96153b1bb2da1954a08d4d23&gt; /usr/lib/system/libsystem_c.dylib 0x180a64000 - 0x180a67fff libsystem_configuration.dylib arm64 &lt;c5ce1ced5659354ab63871b42d04a7cd&gt; /usr/lib/system/libsystem_configuration.dylib 0x180a68000 - 0x180a6bfff libsystem_containermanager.dylib arm64 &lt;504648cfa43d3668b9678b74e33697f2&gt; /usr/lib/system/libsystem_containermanager.dylib 0x180a6c000 - 0x180a6dfff libsystem_coreservices.dylib arm64 &lt;8f94549c633036aa99efb0f067031a05&gt; /usr/lib/system/libsystem_coreservices.dylib 0x180a70000 - 0x180a86fff libsystem_coretls.dylib arm64 &lt;498e424eb31f3d5cb49523cec07f339d&gt; /usr/lib/system/libsystem_coretls.dylib 0x180a88000 - 0x180a90fff libsystem_dnssd.dylib arm64 &lt;096026a14628397ea96580ce7704f39e&gt; /usr/lib/system/libsystem_dnssd.dylib 0x180a94000 - 0x180ab6fff libsystem_info.dylib arm64 &lt;932df5ba705a3b6d948c5dcff196ea6b&gt; /usr/lib/system/libsystem_info.dylib 0x180ab8000 - 0x180ad9fff libsystem_kernel.dylib arm64 &lt;29df8d8d12d034ffa906bb02f04610f4&gt; /usr/lib/system/libsystem_kernel.dylib 0x180adc000 - 0x180af8fff libsystem_m.dylib arm64 &lt;a97bf91d4a233dbc94bef06734a2eac0&gt; /usr/lib/system/libsystem_m.dylib 0x180afc000 - 0x180b15fff libsystem_malloc.dylib arm64 &lt;a8af95191b283ca9aa7f9cf80c459bf5&gt; /usr/lib/system/libsystem_malloc.dylib 0x180b18000 - 0x180b7bfff libsystem_network.dylib arm64 &lt;a8e4200aecc73e56a8458a0e9cb4a6f0&gt; /usr/lib/system/libsystem_network.dylib 0x180b7c000 - 0x180b85fff libsystem_networkextension.dylib arm64 &lt;d1a7579c71943631845c2908d69bfbc6&gt; /usr/lib/system/libsystem_networkextension.dylib 0x180b88000 - 0x180b92fff libsystem_notify.dylib arm64 &lt;da8d7d155da230d287a67c46e9b3ccbc&gt; /usr/lib/system/libsystem_notify.dylib 0x180b94000 - 0x180b99fff libsystem_platform.dylib arm64 &lt;4386956061113d7a9e415e543b1243bc&gt; /usr/lib/system/libsystem_platform.dylib 0x180b9c000 - 0x180ba4fff libsystem_pthread.dylib arm64 &lt;7965d331db2c3bd2b8cbc1bc78babca2&gt; /usr/lib/system/libsystem_pthread.dylib 0x180ba8000 - 0x180baafff libsystem_sandbox.dylib arm64 &lt;f82362117e823f0fbcbf9922ca025f26&gt; /usr/lib/system/libsystem_sandbox.dylib 0x180bac000 - 0x180bbcfff libsystem_trace.dylib arm64 &lt;fe1b1e8d0b3633c58d415c6fe8594903&gt; /usr/lib/system/libsystem_trace.dylib 0x180bc0000 - 0x180bc5fff libunwind.dylib arm64 &lt;b0067e5ea3ca3b28abc5cb7d50390363&gt; /usr/lib/system/libunwind.dylib 0x180bc8000 - 0x180bc8fff libvminterpose.dylib arm64 &lt;630bf4c89edf3935b7afe56abdb5caad&gt; /usr/lib/system/libvminterpose.dylib 0x180bcc000 - 0x180bf1fff libxpc.dylib arm64 &lt;fc63a0a505523f7fac2c4ea9d9662ba1&gt; /usr/lib/system/libxpc.dylib 0x180bf4000 - 0x180df9fff libicucore.A.dylib arm64 &lt;9416014bb51e35aebdb2a9f572a2c5f8&gt; /usr/lib/libicucore.A.dylib 0x180dfc000 - 0x180e0dfff libz.1.dylib arm64 &lt;8fcb56adfdc13e9593582266b1e4ac18&gt; /usr/lib/libz.1.dylib 0x180e10000 - 0x181190fff CoreFoundation arm64 &lt;182fd72b7fdf330b8dbf70db93af6b63&gt; /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation 0x181194000 - 0x1811a4fff libbsm.0.dylib arm64 &lt;d045301bcacc37d785d754d5c978d979&gt; /usr/lib/libbsm.0.dylib 0x1811a8000 - 0x1811a8fff libenergytrace.dylib arm64 &lt;c4ee08bffdfc3ce0990c1fbeb858f9dc&gt; /usr/lib/libenergytrace.dylib 0x1811ac000 - 0x18121dfff IOKit arm64 &lt;0864d9c20424332d8979a4f548848c16&gt; /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit 0x181220000 - 0x181240fff libMobileGestalt.dylib arm64 &lt;9cc485a12c323768a6b6e88d973bd44e&gt; /usr/lib/libMobileGestalt.dylib 0x181244000 - 0x18132efff libxml2.2.dylib arm64 &lt;be446a86b5fa3620beeeb3a56a320e7b&gt; /usr/lib/libxml2.2.dylib 0x181330000 - 0x1813a2fff Security arm64 &lt;85e9578e7bc732ca9cced737b84163bb&gt; /System/Library/Frameworks/Security.framework/Security 0x1813a4000 - 0x1813fdfff SystemConfiguration arm64 &lt;92717250c7393c44878d137773604d46&gt; /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration 0x181400000 - 0x1814e8fff libsqlite3.dylib arm64 &lt;c703a175f1c43ed28d81b839ba961183&gt; /usr/lib/libsqlite3.dylib 0x1814ec000 - 0x181780fff CFNetwork arm64 &lt;aaa7ff247b7b3357aa90f6a4dddf0697&gt; /System/Library/Frameworks/CFNetwork.framework/CFNetwork 0x181784000 - 0x181791fff libbz2.1.0.dylib arm64 &lt;8ebfd413e3fd3889b546857fcf554b6f&gt; /usr/lib/libbz2.1.0.dylib 0x181794000 - 0x1817adfff liblzma.5.dylib arm64 &lt;68bb861dc8bd3547b5ace073ed504b14&gt; /usr/lib/liblzma.5.dylib 0x1817b0000 - 0x1817cafff libCRFSuite.dylib arm64 &lt;1a2c1f709f213faf81fd2223b719c899&gt; /usr/lib/libCRFSuite.dylib 0x1817cc000 - 0x1817f6fff libarchive.2.dylib arm64 &lt;bf6ae1a9c965363ba9f10ff0ca32ee7c&gt; /usr/lib/libarchive.2.dylib 0x1817f8000 - 0x181816fff libextension.dylib arm64 &lt;8a88fb35fee03a36ae138e676b9a0e9f&gt; /usr/lib/libextension.dylib 0x181818000 - 0x181819fff liblangid.dylib arm64 &lt;cdb184e30c3c303694a96b3150520673&gt; /usr/lib/liblangid.dylib 0x18181c000 - 0x181a8afff Foundation arm64 &lt;7cf4edf781cb30438b812ded8716cd95&gt; /System/Library/Frameworks/Foundation.framework/Foundation 0x181a8c000 - 0x181b37fff libBLAS.dylib arm64 &lt;097b7e769a3439ad8fdb3abb0edc9daf&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libBLAS.dylib 0x181b38000 - 0x181e9dfff libLAPACK.dylib arm64 &lt;566419f65c9338599694a04da8e20fbf&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLAPACK.dylib 0x181ea0000 - 0x182105fff vImage arm64 &lt;789df1b35e183397803583a25feff3c7&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vImage.framework/vImage 0x182108000 - 0x18212afff libvMisc.dylib arm64 &lt;3c655ae6f62035bbba069387c490efbb&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvMisc.dylib 0x18212c000 - 0x18213ffff libLinearAlgebra.dylib arm64 &lt;94d099e954d638e39ef1773639ef61af&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLinearAlgebra.dylib 0x182140000 - 0x18214ffff libSparseBLAS.dylib arm64 &lt;80ca4fb770613c76b2449daf05c6dc25&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libSparseBLAS.dylib 0x182150000 - 0x1821bcfff libvDSP.dylib arm64 &lt;f4e8d68f55af3511a28a616737dcc354&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvDSP.dylib 0x1821c0000 - 0x1821c0fff vecLib arm64 &lt;546ad53c3a4a36709fdf6e50b76b2ec9&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/vecLib 0x1821c4000 - 0x1821c4fff Accelerate arm64 &lt;a1953e95570a3de6a923a812ffbd90ad&gt; /System/Library/Frameworks/Accelerate.framework/Accelerate 0x1821c8000 - 0x1826f3fff CoreGraphics arm64 &lt;63001c4acb4135428df4b62f2f698e0f&gt; /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics 0x1826f4000 - 0x182708fff GraphicsServices arm64 &lt;d8509ae0233539218bf97db29a7d31c2&gt; /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices 0x18270c000 - 0x182754fff AppSupport arm64 &lt;1469530c1aa03d2486d678bed8482764&gt; /System/Library/PrivateFrameworks/AppSupport.framework/AppSupport 0x182758000 - 0x18282bfff MobileCoreServices arm64 &lt;2096d560a53b3fd28ff0a7f46e3ba060&gt; /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices 0x18282c000 - 0x18287bfff BaseBoard arm64 &lt;b6f2014b564430538f5252776acfa530&gt; /System/Library/PrivateFrameworks/BaseBoard.framework/BaseBoard 0x18287c000 - 0x182887fff AssertionServices arm64 &lt;48c978bd14553765b4a7f1cee1b14c83&gt; /System/Library/PrivateFrameworks/AssertionServices.framework/AssertionServices 0x182888000 - 0x1828acfff BackBoardServices arm64 &lt;207836d8c1833eeab468f622f4d0f366&gt; /System/Library/PrivateFrameworks/BackBoardServices.framework/BackBoardServices 0x1828b0000 - 0x1828b3fff MobileSystemServices arm64 &lt;6d85ae92680935bbb51db96c7a021118&gt; /System/Library/PrivateFrameworks/MobileSystemServices.framework/MobileSystemServices 0x1828b4000 - 0x1828e9fff FrontBoardServices arm64 &lt;b1a46eb324d23a51813b565ae7f04b88&gt; /System/Library/PrivateFrameworks/FrontBoardServices.framework/FrontBoardServices 0x1828ec000 - 0x1828f6fff UserNotificationServices arm64 &lt;74d3e76dff833048b39ae8e0ceb44140&gt; /System/Library/PrivateFrameworks/UserNotificationServices.framework/UserNotificationServices 0x1828f8000 - 0x182924fff SpringBoardServices arm64 &lt;6535787e172939d0b8abfe852a185b3d&gt; /System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices 0x182928000 - 0x182939fff MobileKeyBag arm64 &lt;169edc8949693d349807056d1e316f2a&gt; /System/Library/PrivateFrameworks/MobileKeyBag.framework/MobileKeyBag 0x18293c000 - 0x182942fff IOSurface arm64 &lt;d62fd4ed209e32f98d5dbc34f9484ef4&gt; /System/Library/PrivateFrameworks/IOSurface.framework/IOSurface 0x182944000 - 0x182950fff liblockdown.dylib arm64 &lt;36e1e9187c193410a5f7cf46e3dc7afe&gt; /usr/lib/liblockdown.dylib 0x182954000 - 0x182966fff CrashReporterSupport arm64 &lt;8e45addb6a1f379d98c9164764948fc2&gt; /System/Library/PrivateFrameworks/CrashReporterSupport.framework/CrashReporterSupport 0x182968000 - 0x18296afff IOSurfaceAccelerator arm64 &lt;65789d64b5f937e987c6f27125a38100&gt; /System/Library/PrivateFrameworks/IOSurfaceAccelerator.framework/IOSurfaceAccelerator 0x18296c000 - 0x1829adfff AppleJPEG arm64 &lt;24fc6e2cd59a318e9f59da6383bfd90d&gt; /System/Library/PrivateFrameworks/AppleJPEG.framework/AppleJPEG 0x1829b0000 - 0x182cd2fff ImageIO arm64 &lt;8b10562bfdd23addb249367deb92aefd&gt; /System/Library/Frameworks/ImageIO.framework/ImageIO 0x182cd4000 - 0x182cd8fff TCC arm64 &lt;09fcccda721f35c3936e68acf3d216a4&gt; /System/Library/PrivateFrameworks/TCC.framework/TCC 0x182cdc000 - 0x182ce1fff AggregateDictionary arm64 &lt;51bcd4b61f3739eb85fdcc4a037e3696&gt; /System/Library/PrivateFrameworks/AggregateDictionary.framework/AggregateDictionary 0x182ce4000 - 0x182cf1fff PowerLog arm64 &lt;a50ba8508d733823be55425db249606c&gt; /System/Library/PrivateFrameworks/PowerLog.framework/PowerLog 0x182cf4000 - 0x182d56fff libTelephonyUtilDynamic.dylib arm64 &lt;59e0bc898f27370d8e4961910f891b3b&gt; /usr/lib/libTelephonyUtilDynamic.dylib 0x182d58000 - 0x182d6afff CommonUtilities arm64 &lt;194ea4f46bf537029d10e4ce8b28ca5f&gt; /System/Library/PrivateFrameworks/CommonUtilities.framework/CommonUtilities 0x182d6c000 - 0x182d83fff libcompression.dylib arm64 &lt;ac77f3a3cad832a7b748c30e013bbc0b&gt; /usr/lib/libcompression.dylib 0x182d84000 - 0x182fcefff CoreData arm64 &lt;aa00d2e704e333e199f8e34b3c661b12&gt; /System/Library/Frameworks/CoreData.framework/CoreData 0x182fd0000 - 0x182fd4fff libCoreVMClient.dylib arm64 &lt;69b5ba7317d532b898c3ffb5574bb883&gt; /System/Library/Frameworks/OpenGLES.framework/libCoreVMClient.dylib 0x182fd8000 - 0x182fdcfff IOAccelerator arm64 &lt;d92ad93b196b38a6b054b1cc3fbd1f1a&gt; /System/Library/PrivateFrameworks/IOAccelerator.framework/IOAccelerator 0x182fe0000 - 0x182fe1fff libCVMSPluginSupport.dylib arm64 &lt;ed32d5e2c1e630b18097aa7890c92171&gt; /System/Library/Frameworks/OpenGLES.framework/libCVMSPluginSupport.dylib 0x182fe4000 - 0x182fe7fff libCoreFSCache.dylib arm64 &lt;abe2067778503127a31c42352d2e43ec&gt; /System/Library/Frameworks/OpenGLES.framework/libCoreFSCache.dylib 0x182fe8000 - 0x18302efff libGLImage.dylib arm64 &lt;e67acd0811bf318dadb48a49b97bee7b&gt; /System/Library/Frameworks/OpenGLES.framework/libGLImage.dylib 0x183030000 - 0x18303afff libGFXShared.dylib arm64 &lt;fdc295986ea03203bbfc904ffc4cca6b&gt; /System/Library/Frameworks/OpenGLES.framework/libGFXShared.dylib 0x18303c000 - 0x183043fff IOMobileFramebuffer arm64 &lt;f82bfbe1dc083eabb7ff1a8d9980fe47&gt; /System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer 0x183044000 - 0x183044fff libmetal_timestamp.dylib arm64 &lt;bdc8f33a1b453c8f827726c7f46640dc&gt; /System/Library/PrivateFrameworks/GPUCompiler.framework/libmetal_timestamp.dylib 0x183048000 - 0x18308efff Metal arm64 &lt;95ce1f8a4d483d11aa49533e2ae2a568&gt; /System/Library/Frameworks/Metal.framework/Metal 0x183090000 - 0x18309afff OpenGLES arm64 &lt;7c7a0c5191f53f518e994638139ca1df&gt; /System/Library/Frameworks/OpenGLES.framework/OpenGLES 0x18309c000 - 0x1830befff CoreVideo arm64 &lt;31ef8b764af3301ea5e7267fcae838cb&gt; /System/Library/Frameworks/CoreVideo.framework/CoreVideo 0x1830c0000 - 0x1830c2fff OAuth arm64 &lt;0f1ae5abcad13b4b948193a2405c61b4&gt; /System/Library/PrivateFrameworks/OAuth.framework/OAuth 0x1830c4000 - 0x1830fbfff Accounts arm64 &lt;1cf893c2c3c03137acb576d5a7fc2cee&gt; /System/Library/Frameworks/Accounts.framework/Accounts 0x1830fc000 - 0x1831eefff libiconv.2.dylib arm64 &lt;1c378c57054a32a6b2eed4e3cbb3a2b7&gt; /usr/lib/libiconv.2.dylib 0x1831f0000 - 0x1832a9fff CoreAudio arm64 &lt;25687ef4b3c4389f828006882b280db4&gt; /System/Library/Frameworks/CoreAudio.framework/CoreAudio 0x1832ac000 - 0x1832affff UserFS arm64 &lt;693602c29c64370aab1a77544ddc7e5a&gt; /System/Library/PrivateFrameworks/UserFS.framework/UserFS 0x1832b0000 - 0x18339efff CoreMedia arm64 &lt;51c728b4974936448426dccd30e3fc5a&gt; /System/Library/Frameworks/CoreMedia.framework/CoreMedia 0x1833a0000 - 0x1833a8fff libcupolicy.dylib arm64 &lt;056df1f0f2893ad08b9c7fbed9271c6f&gt; /usr/lib/libcupolicy.dylib 0x1833ac000 - 0x18341efff CoreTelephony arm64 &lt;d48572ad7be13a99b7a783c12c6657f4&gt; /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony 0x183420000 - 0x183500fff libFontParser.dylib arm64 &lt;7ab9c32919d731969bc2a75b3f03aa17&gt; /System/Library/PrivateFrameworks/FontServices.framework/libFontParser.dylib 0x183504000 - 0x183586fff VideoToolbox arm64 &lt;0902a89a960935c08b3715cadedc2a50&gt; /System/Library/Frameworks/VideoToolbox.framework/VideoToolbox 0x183588000 - 0x183588fff FontServices arm64 &lt;39a3005cf101328f94f3a412cfa04fae&gt; /System/Library/PrivateFrameworks/FontServices.framework/FontServices 0x18358c000 - 0x1836affff CoreText arm64 &lt;5d80f981ab953f73b08881908a610117&gt; /System/Library/Frameworks/CoreText.framework/CoreText 0x1836b0000 - 0x1836c1fff ProtocolBuffer arm64 &lt;4d1a9d53f37b3b448cbc62ede839532f&gt; /System/Library/PrivateFrameworks </code></pre> <p>can anybody explain me what happend ??</p>
<p>Your iPad allows permissions that may have Been initiated, unlike iPhone. I am so done With the pad I think I will burn it. Load new iOS and run SOPHOS TRACE MODULE, my Feeling is the auto access of many apps available Is a bit more secure than the old iOS. Failure to connect by a few previous "wide open doors " Will halt the new iOS. Remove all of your suspicious permissions from apps that have no Valid use for access to your personal data. Reload the iOS and give it a try....TP7</p>
Laravel Nested relationships using dot syntax querying each level <p>the goal here is to have my menu model create a tree with each related child and the child's related Page.</p> <p>I'm generating a tree with my model like this...</p> <pre><code> public static function tree() { return static::with(implode('.', array_fill(0, 100, 'children')))-&gt;with('Pages')-&gt;where('parent_id', '=', 0)-&gt;get(); } </code></pre> <p>But the problem comes with getting each childs related Page. I've tried this...</p> <pre><code> return static::with([implode('.', array_fill(0, 100, 'children')) =&gt; function($query) { $query-&gt;with('Pages'); }])-&gt;with('Pages')-&gt;where('parent_id', '=', $id)-&gt;get(); </code></pre> <p>and adding the eager loading query didn't seem to work. i think maybe using the dot sytax and querying it only queries the last one? I'm not sure on that.</p> <p>I need to query each level of the query but i don't know how. any help would be greatly appreciated!</p>
<p>UPDATE: it seems I've managed to fix this problem by doing this...</p> <pre><code>public static function genRelationalArray() { $arr = [implode('.', array_fill(0, 100, 'children'))]; for($i = 0; $i &lt; 10; $i++) { $item = 'children.Pages'; $arr[] = $item; $item = 'children.'. $item; } return $arr; } public static function treeFromId($id) { $childArr = static::genRelationalArray(); return static::with($childArr)-&gt;with('Pages')-&gt;where('parent_id', '=', $id)-&gt;get(); } </code></pre> <p>but if there is a shorter more efficient way of doing this please post :)</p>
create a multidimensional array in codeigniter controller <p>I'm having a controller to get users from DB and display every user in a table row</p> <pre><code>Controller: [update] //only first page displays data correctly but pager +1 using pagination displays user data only not getting orders as first page when I print_r($orders) in all pages I get correct orders but in the table the inner foreach doesn't work public function index($page_id = 1) { $perPage = 25; $offset = ($page_id - 1) * $perPage; if ($offset &lt; 0) { $offset = $perPage; } $lang_id = $this-&gt;data['active_language']-&gt;id; $config['base_url'] = base_url() . "reports/myController/index/"; $config['per_page'] = $perPage; $config['first_link'] = FALSE; $config['last_link'] = FALSE; $config['uri_segment'] = 4; $config['use_page_numbers'] = TRUE; $config['first_link'] = lang('first_page'); $config['last_link'] = lang('last_page'); $config['first_tag_open'] = '&lt;li&gt;'; $config['first_tag_close'] = '&lt;/li&gt;'; $config['last_tag_open'] = '&lt;li&gt;'; $config['last_tag_close'] = '&lt;/li&gt;'; $config['next_tag_open'] = '&lt;li&gt;'; $config['next_tag_close'] = '&lt;/li&gt;'; $config['prev_tag_open'] = '&lt;li&gt;'; $config['prev_tag_close'] = '&lt;/li&gt;'; $config['num_tag_open'] = '&lt;li&gt;'; $config['num_tag_close'] = '&lt;/li&gt;'; $config['cur_tag_open'] = '&lt;li&gt;&lt;strong&gt;'; $config['cur_tag_close'] = '&lt;/strong&gt;&lt;/li&gt;'; $config['display_pages'] = TRUE; $orders_serials_ids = $this-&gt;myModel-&gt;get_orders_serials_ids(); $config['total_rows'] = $this-&gt;myModel-&gt;count_orders(); $this-&gt;pagination-&gt;initialize($config); $users = $this-&gt;myModel-&gt;users_merchants($perPage, $offset); $this-&gt;data['users'] = $users; $user_orders = array(); foreach ($users as $user){ $user_orders[$user-&gt;user_id] = $this-&gt;myModel-&gt;get_orders($user-&gt;user_id); } View: &lt;table&gt; &lt;tr&gt; &lt;th&gt; &lt;?php echo 'user';?&gt; &lt;/th&gt; &lt;th&gt; &lt;?php echo 'email';?&gt; &lt;/th&gt; &lt;th&gt; &lt;?php echo 'device id';?&gt; &lt;/th&gt; &lt;/tr&gt; &lt;?php foreach($users as $val){ ?&gt; &lt;tr&gt; &lt;td&gt; &lt;?=$val-&gt;user_id?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $val-&gt;email;?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $val-&gt;device_id;?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php $order = array(); //empty the variable before each loop foreach($orders[$user-&gt;user_id] as $order){ echo '&lt;tr&gt;&lt;td colspan="4"&gt;'. date('Y-m',$order-&gt;unix_time). ' -&gt; '.round($order-&gt;amount2,2).'&lt;/td&gt;&lt;/tr&gt;'; } } ?&gt; &lt;/table&gt; &lt;ul class="pagination"&gt;&lt;?php if($pagination) echo $pagination;?&gt;&lt;/ul&gt; user id user name user email 1 Mike mike@yahoo.com order:10 order total:50 order date: 2016-09-12 order:12 order total:100 order date: 2016-09-14 2 Tom Tom@live.com order:15 order total:80 order date: 2016-09-13 order:16 order total:120 order date: 2016-09-14 order:17 order total:140 order date: 2016-10-10 </code></pre> <p>This works in the first page only but when I navigate to second page the controller url changes to index/2 r any other page number I get users rows without data orders though if I print_r orders above the table I get correct orders</p>
<p>you can reduce the code a little but in controller like this:</p> <pre><code>$this-&gt;data['users'] = $users; // correct data no problem here $user_orders = array(); foreach ($users as $user){ $user_orders[$user-&gt;user_id] = $this-&gt;myMmodel&gt;get_orders($user-&gt;user_id); //make user_id as key so that you can access easily for each user } $this-&gt;data['orders'] = $user_orders; </code></pre> <p>Then in view, you can access orders of each user inside the foreach loop like this:</p> <p>$orders[$user->user_id]</p> <p>as it is also an array, you have to run loop to create order rows for each user:</p> <pre><code>$order = array(); //empty the variable before each loop foreach($orders[$user-&gt;user_id] as $order){ echo '&lt;tr&gt;&lt;td&gt;'.$order-&gt;id.'&lt;/td&gt;'.....//more columns like this } </code></pre> <p>Hope this would help!</p>
Escape backslash in Python parameterized MySQL query <p>I am working on excel files and database storaging, precisely I am storaging excel data to MySQL database. At some point I am executing this query:</p> <pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = '{0}' '''.format(attivita) </code></pre> <p>And when I print the query result I get this:</p> <p>' SELECT id FROM attivita WHERE attivita = \\'Manutenzione\\' '</p> <p>When it tries to match 'attivita' with the right value, taken from the excel, I got errors because of the '\\'.</p> <p>I tried changing the triple quotes from " " " to ' ' ', as well as using <code>connection.escape_string()</code>, but I didn't solve the problem. Can anyone help me figuring out the problem? Thank you in advance.</p>
<p>I think that in your case better to use arguments to execute</p> <pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = %(attivita)s ''' cursor.execute(query_for_id, { 'attivita': attivita }) </code></pre> <p><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html</a></p>
R - string manipulation and extraction <p>I have a string <code>strEx &lt;- "list(A, B, C, D)"</code> that I would like to store as a character vector:</p> <pre><code>[1] "A" "B" "C" "D" </code></pre> <p>I'm not very good at regex (might be overkill as well, but I will need more of it in the future) which is probably part of my problem. I have a solution that I feel is too much code/bad form.</p> <p>It gives me what I want in the end but I still need to split it on commas and flatten it. I just feel this is a too crude a way to go about it. Anyone have a prettier solution?</p> <pre><code>d &lt;- gsub(".*\\((.*)\\).*", "\\1", strEx) d1 &lt;- unlist(tstrsplit(d, ", ", type.convert = TRUE, fixed = TRUE)) </code></pre>
<p>You could parse the expression like this:</p> <pre><code>#parse the expression pEx &lt;- parse(text = strEx)[[1]] </code></pre> <p>Expressions are actually lists of symbols and can be treated as such. Here we turn everything except <code>list</code> into characters:</p> <pre><code>vapply(pEx[-1], as.character, FUN.VALUE = "") #[1] "A" "B" "C" "D" </code></pre> <p>However, if you need to parse a string (which is what you propose as a solution using regex too), some preceding step should usually be improved. You should not have an expression that needs to be parsed.</p> <p>See this:</p> <pre><code>library(fortunes) fortune(106) #If the answer is parse() you should usually rethink the question. # -- Thomas Lumley # R-help (February 2005) </code></pre>
Create SOAP webservice(wsdl) client in c# <p>I have a soap based web service which has wsdl. and I have to create a windows form application client. can someone give me a small basic client? </p> <p>Tips: that small web service has only a method named "</p> <blockquote> <p>CALL(id,name,address)</p> </blockquote>
<p>Having Drew's method in mind, </p> <ol> <li>Right click on the project and select "add a service reference' and click "Advanced.." in add service reference dialog box. Then click "Add web reference" in add service reference dialog box. Input your webservice address in the address bar and click go. then rename your web reference name and click add reference.</li> </ol> <p>(for ws security) 2.Go to the Reference.cs and change <code>System.Web.Services.Protocols.SoapHttpClientProtocol</code> to <code>Microsoft.Web.Services2.WebServicesClientProtocol</code> (You might have to add service2 by nuget)</p> <ol start="3"> <li>Before calling your webservice, add this.</li> </ol> <p>UsernameToken token = new UsernameToken("", "", PasswordOption.SendPlainText); yourProxy.RequestSoapContext.Security.Tokens.Add(token);</p>
Issue with transitioning between activities containing adapters sharing the same data set <p>Given 2 activities, A starts B for result.</p> <p>Both activities have structures (A: RecyclerView, B: ViewPager) and adapters which connect to the same data set, stored in the Application object.</p> <p>B finishes and posts the result back to A.</p> <p>A gets the result on onActivityResult() and in the body of the function alters the data set (removes one element).</p> <p>Issue is that later (after debugger exits my code) I get a crash in B saying:</p> <pre><code>java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 9 </code></pre> <p>The stacktrace starts with:</p> <pre><code>android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271) android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358) android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607) android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246) android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301) android.view.Choreographer$CallbackRecord.run(Choreographer.java:871) android.view.Choreographer.doCallbacks(Choreographer.java:683) android.view.Choreographer.doFrame(Choreographer.java:619) android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857) android.os.Handler.handleCallback(Handler.java:751) android.os.Handler.dispatchMessage(Handler.java:95) android.os.Looper.loop(Looper.java:154)` </code></pre> <p>Not sure what's going on here .. shouldn't the activity B be gone for good after finish was called and before A.onActivityResult() is called?</p> <p>Is this because the exiting animation requires a final draw from B?</p> <p>EDIT: B.onStop() and B.onDestroy() are called after A.onActivityResult(). Why is this normal behaviour?</p>
<p>Try to call notifyDataSetChanged() before calling getCount() in your adapter. </p> <p>Something like this:</p> <pre><code>@Override public int getCount() { notifyDataSetChanged(); return list.size(); } </code></pre>
Get data from scope to another scope within one controller angularjs <p>I'm absolutely beginner in AngularJS. So, I'll be really appreciate for any help. I'm trying to build an app with charts in it using Ionic and Angular-nvD3 lineChart. I have data in json file. So, I've made factory and used getData(), $scope and service. I need one line chart with many data points on it. But output looks like every point is separate from another. I thought maybe it's because of $scope and getData function. Maybe there is some kind of loop in it, which separate data. I am trying to rewrite code to fix the problem, extract data from scope within the factory to another scope for separating this processes, but without any luck. My code in app.js below</p> <pre><code>(function() { var app = angular.module('starter', ['ionic','nvd3']); app.factory('services', ['$http', function($http){ var serviceBase = 'services/' var object = {}; object.getData = function(){ return $http.get('chart.json'); }; return object; }]); app.controller('MainCtrl', ['$scope', 'services', function($scope, services) { services.getData().then(function successCb(data) { $scope.data = _.map(data.data, function(prod) { var sin = []; sin.push({ x: prod.Date, y: prod.low }); return { values: sin, key: 'fff' } }); }); $scope.options = { chart: { type: 'lineChart', height: 450, margin : { top: 20, right: 20, bottom: 40, left: 55 }, lines: { xScale: d3.time.scale(), }, x: function(d){ return d3.time.format('%Y-%m-%d').parse(d.x); }, y: function(d){ return d.y; }, useInteractiveGuideline: true, dispatch: { stateChange: function(e){ console.log("stateChange"); }, changeState: function(e){ console.log("changeState"); }, tooltipShow: function(e){ console.log("tooltipShow"); }, tooltipHide: function(e){ console.log("tooltipHide"); } }, xAxis: { axisLabel: 'Time (ms)', tickFormat: function(d){ return d3.time.format('%d-%m-%Y')(d); }, }, yAxis: { axisLabel: 'Voltage (v)', tickFormat: function(d){ return d3.format('.02f')(d); }, axisLabelDistance: -10 }, callback: function(chart){ console.log("!!! lineChart callback !!!"); } }, title: { enable: true, text: 'Title for Line Chart' }, subtitle: { enable: true, text: 'Subtitle for simple line chart. Lorem ipsum dolor sit amet, at eam blandit sadipscing, vim adhuc sanctus disputando ex, cu usu affert alienum urbanitas.', css: { 'text-align': 'center', 'margin': '10px 13px 0px 7px' } }, caption: { enable: true, html: '&lt;b&gt;Figure 1.&lt;/b&gt; Lorem ipsum dolor sit amet, at eam blandit sadipscing, &lt;span style="text-decoration: underline;"&gt;vim adhuc sanctus disputando ex&lt;/span&gt;, cu usu affert alienum urbanitas. &lt;i&gt;Cum in purto erat, mea ne nominavi persecuti reformidans.&lt;/i&gt; Docendi blandit abhorreant ea has, minim tantas alterum pro eu. &lt;span style="color: darkred;"&gt;Exerci graeci ad vix, elit tacimates ea duo&lt;/span&gt;. Id mel eruditi fuisset. Stet vidit patrioque in pro, eum ex veri verterem abhorreant, id unum oportere intellegam nec&lt;sup&gt;[1, &lt;a href="https://github.com/krispo/angular-nvd3" target="_blank"&gt;2&lt;/a&gt;, 3]&lt;/sup&gt;.', css: { 'text-align': 'justify', 'margin': '10px 13px 0px 7px' } } }; }]); app.run(function($ionicPlatform) { $ionicPlatform.ready(function() { if(window.cordova &amp;&amp; window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }); }()); </code></pre> <p>And this is data in JSON file</p> <pre><code>[ { "Date": "2011-12-02", "low": 8758.22466765 }, { "Date": "2011-12-03", "low": 8771.50964703 }, { "Date": "2011-12-04", "low": 8784.79462641 }, { "Date": "2011-12-05", "low": 8798.07960579 }, { "Date": "2011-12-06", "low": 8689.04458518 }, { "Date": "2011-12-07", "low": 8720.07956456 }, { "Date": "2011-12-08", "low": 8718.97454394 }, { "Date": "2011-12-09", "low": 8584.72952332 }, { "Date": "2011-12-10", "low": 8616.084502700001 }, { "Date": "2011-12-11", "low": 8647.43948208 }, { "Date": "2011-12-12", "low": 8678.79446147 }, { "Date": "2011-12-13", "low": 8552.15944085 }, { "Date": "2011-12-14", "low": 8507.64442023 }, { "Date": "2011-12-15", "low": 8383.43939961 }, { "Date": "2011-12-16", "low": 8388.08437899 }, { "Date": "2011-12-17", "low": 8336.42602504 }, { "Date": "2011-12-18", "low": 8284.76767109 }, { "Date": "2011-12-19", "low": 8233.10931714 }, { "Date": "2011-12-20", "low": 8266.49429652 }, { "Date": "2011-12-21", "low": 8377.569275900001 }, { "Date": "2011-12-22", "low": 8308.55425529 }, { "Date": "2011-12-23", "low": 8319.82173467 }, { "Date": "2011-12-24", "low": 8331.08921405 }, { "Date": "2011-12-25", "low": 8342.35669343 }, { "Date": "2011-12-26", "low": 8353.62417281 } ] </code></pre> <p>I'm trying something like that:</p> <pre><code> services.getData().then(function successCb(data) { $scope.data = _.map(data.data); }); $scope.selectedSin = function(prod) { var sin = []; angular.forEach(data, function (sin) { sin.push({ x: data.Date, y: data.low }); return { values: sin, key: 'fff' } }); }; </code></pre> <p>But have an error in console: </p> <blockquote> <p>e.values is undefined</p> </blockquote> <p><a href="http://i.stack.imgur.com/cbU3r.png" rel="nofollow">Image of the line chart</a></p>
<pre><code> services.getData().then(function successCb(data) { $scope.data = _.map(data.data); }); $scope.selectedSin = function(prod) { var sin = []; angular.forEach(data, function (sin) { sin.push({ x: data.Date, y: data.low }); return { values: sin, key: 'fff' } }); }; </code></pre> <p>In your above snippet, from where the <strong>data</strong> comes that is passed to <code>angular.forEach?</code></p>
How do I customize the URL that Ember RESTAdapter calls? <p>In our Ember application, I have 3 different models:</p> <ul> <li>organizations</li> <li>users</li> <li>issues</li> </ul> <p>Issues are created by users who belong to an organization. Both <code>organizations</code> and <code>users</code> have an <code>issues</code> array with a bunch of issue IDs that belong in the <code>issues</code> model. For example, this is what the <code>users</code> model looks like:</p> <pre><code>// app/models/users.js export default DS.Model.extend({ name: DS.attr('string'), email: DS.attr('string'), belongsTo: DS.belongsTo('organizations'), issues: DS.hasMany('issues') }); </code></pre> <p>We have two APIs to view a list of all issues:</p> <ul> <li><code>GET /users/:userId/issues</code> - This API gets all the issues created by the user</li> <li><code>GET /organizations/:organizationId/issues</code> - This API gets all the issues created by users that belong to this organization</li> </ul> <p>The issue is, when I call <code>this.store.findAll('issues');</code>, the Ember RESTAdapter calls <code>GET /issues</code> by default. I can't figure out a way to get the RESTAdapter to call any of the URLs above. I can't use <code>this.store.findRecord('issues', 1);</code> because that calls a specific issue by ID like <code>GET /issues/:issueId</code>. How can I get the RESTAdapter to call the above URLs without having to manually make an AJAX request and push the API response to Ember Data?</p>
<p>You need to customize your adapter (you can have an adapter per-model if you want, as far as I know).</p> <p>In your specific example I think you want to customize the <a href="http://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html#method_urlForFindAll" rel="nofollow"><code>urlForFindAll</code></a> method.</p> <pre><code>// maybe in app/organization/adapter.js (if using pods for a model specific adapter) urlForFindAll(modelName) { return 'urlYouWantToUseWithOrganizations'; } </code></pre> <p>A good article on this situation is on <a href="https://emberigniter.com/fit-any-backend-into-ember-custom-adapters-serializers/" rel="nofollow">Ember Igniter</a></p>
Unity Prime31 prompt for photo is crashing on iOS 10 and XCode 8 <p>Calling EtceteraBinding.promptForPhoto resulting in immediate crash on iOS 10.</p> <pre><code>public void TakePhotoTapped() { #if UNITY_IOS EtceteraBinding.promptForPhoto(0.2f, PhotoPromptType.Camera, 0.8f, true); #endif } </code></pre> <p>Xcode spits out this log. It does look like some sort of permission issue? Please help.</p> <pre><code>2016-10-11 11:46:35.758167 xxx[1643:458841] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution. 2016-10-11 11:46:49.760643 xxx[1643:458841] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2016-10-11 11:46:49.768609 xxx[1643:458841] [MC] Reading from public effective user settings. 2016-10-11 11:47:02.450381 xxx[1643:459135] [access] This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCameraUsageDescription key with a string value explaining to the user how the app uses this data. </code></pre>
<p>This is related to new iOS 10 Privacy Settings requirement. You must declare ahead of time any access to private data or your App will crash.</p> <p>You can add a usage key to your app’s Info.plist together with a purpose string or add a script that will do it for you in Unity for all your builds.</p> <p>Xcode Info.plist tab: <a href="http://i.stack.imgur.com/HGMlK.png" rel="nofollow"><img src="http://i.stack.imgur.com/HGMlK.png" alt="Info.plist"></a></p> <p>SO for each framework you have to declare it's use and enter a string message that is shown to the user.</p> <p>You can also add a post processing script in your Assets/Editor folder, where you declare all features used - this will automatically add them to Info.plist:</p> <pre><code>using UnityEngine; using UnityEditor; using System.Collections; using UnityEditor.Callbacks; using System.Collections; using System.IO; using UnityEditor.iOS.Xcode; public class ChangeIOSplistFile : MonoBehaviour { [PostProcessBuild] public static void ChangeXcodePlist(BuildTarget buildTarget, string pathToBuiltProject) { if (buildTarget == BuildTarget.iOS) { // Get plist string plistPath = pathToBuiltProject + "/Info.plist"; PlistDocument plist = new PlistDocument(); plist.ReadFromString(File.ReadAllText(plistPath)); // Get root PlistElementDict rootDict = plist.root; var cameraKey = "NSCameraUsageDescription"; rootDict.CreateDict (cameraKey); rootDict.SetString (cameraKey, "Enter your description here."); var galleryKey = "NSPhotoLibraryUsageDescription"; rootDict.CreateDict (galleryKey); rootDict.SetString (galleryKey, "Enter your description here."); // Write to file File.WriteAllText(plistPath, plist.WriteToString()); } } } </code></pre>
What's are the types of JOINS will support in Mysql?Is there any possible way to do this? <ul> <li><p>How to do full joins in mysql.?and what are the types of joins will support in mysql. i'm beginner in mysql please help me solve this issue...</p> <p>Thank you!</p></li> </ul>
<p>Before asking this question, I am assuming that you have not searched the net for anything at all, let alone MySQL documentation. Because I have asked stupid questions in the past (without researching enough), I am going to answer this one. By the way, this is a habit you must work upon. You should search for material, read and try solutions to your problems before coming to Stack Exchange.</p> <p>Here's a snapshot from <a href="http://dev.mysql.com/doc/refman/5.7/en/join.html" rel="nofollow">Official MySQL Documentation</a>:</p> <p><a href="http://i.stack.imgur.com/1DjoG.png" rel="nofollow"><img src="http://i.stack.imgur.com/1DjoG.png" alt="From MySQL Documentation"></a></p> <p>Apart from this, here are a few links that would help you understand JOINs, in general:</p> <ol> <li><a href="https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/" rel="nofollow">Coding Horror's Visual Explanation of JOINs</a></li> <li><a href="http://stackoverflow.com/questions/17946221/sql-join-and-different-types-of-joins">Stack Overflow - SQL JOINs and their types</a></li> <li><a href="http://stackoverflow.com/questions/38549/what-is-the-difference-between-inner-join-and-outer-join">One of the most popular posts on Stack Overflow - Difference between Inner and Outer JOINs</a></li> </ol> <p>I think this would suffice for the basic knowledge of JOINs. You'd have to read more about what JOIN to use when - based on the data you want to fetch and also how your database management system (in this case, MySQL) <a href="https://dev.mysql.com/doc/internals/en/optimizer-determining-join-type.html" rel="nofollow">works with JOINs internally to optimize performance</a>.</p>
Ordering Azure Active Directory Graph Results by Created Date <p>Does anyone know how to order the results of a query to the Azure AD Graph API using the nuget assembly (<a href="https://www.nuget.org/packages/Microsoft.Azure.ActiveDirectory.GraphClient/" rel="nofollow">https://www.nuget.org/packages/Microsoft.Azure.ActiveDirectory.GraphClient/</a>) by "Created Date" (i.e. when the user was created in the directory?</p> <p>I can't find any documentation about a property which would contain this. Is the result set automatically ordered in this way?</p>
<p>There is a restriction at the moment on the '$orderby' expressions that can be specified for a Graph API query. From the <a href="https://msdn.microsoft.com/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options" rel="nofollow">documentation</a> - </p> <blockquote> <p>The following restrictions apply to $orderby expressions:</p> </blockquote> <ul> <li><blockquote> <p>Two sort orders are currently supported: DisplayName for User and Group objects, and UserPrincipalName for User objects. The default sort order for users is by UserPrincipalName.</p> </blockquote></li> </ul> <p>So even if the 'Created Date' was exposed as property on the User I doubt the query will work.</p>
Update ios Appstore app to allow only iPhone <p>I have my application in apple app store supporting, iPhone,iPad and iPod (Universal), Now I want to have my app compatible with only iPhone, How to achieve that.(In xcode device family I can check only iPhone and sumbit app sotre, will this make my app only supporting iphone ) Please help</p>
<p><strong>It is not possible</strong> with the original Bundle ID.</p> <p>Citing from the doc below:</p> <p><a href="https://developer.apple.com/library/content/qa/qa1623/_index.html" rel="nofollow">https://developer.apple.com/library/content/qa/qa1623/_index.html</a></p> <blockquote> <p>Bundles must continue to support any devices previously supported.</p> </blockquote> <p><strong>The only option</strong> for you is to create a new bundle ID and submit your app with it.</p> <blockquote> <p>Removing your app from the store, and uploading the update with a different bundle ID, will allow you to narrow the range of devices your update supports. However the update will be listed on the store as a separate app.</p> </blockquote>
How to access the value of a ctypes.LP_c_char pointer? <p>I have defined a struct : </p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", POINTER(c_char)) ] </code></pre> <p>The struct is initialised :</p> <pre><code>buf = create_string_buffer(f_handle.handle_bytes) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) </code></pre> <p>I am passing it by reference to a function that populates it.</p> <pre><code>ret = libc.name_to_handle_at(dirfd, pathname, byref(fh), byref(mount_id), flags) </code></pre> <p>I can check with strace that the call works, but I have not been able to figure out how to access the value of fh.f_handle</p> <p>fh.f_handle type is <code>&lt;ctypes.LP_c_char object at 0x7f1a7ca17560&gt;</code><br> fh.f_handle.contents type is <code>&lt;ctypes.LP_c_char object at 0x7f1a7ca17560&gt;</code> but I get a SIGSEGV if I try to access its value.<br> How could I get 8 bytes from f_handle into a string or array ?</p>
<p>fh.f_handle is shown as LP_c_char because you defined the struct that way.</p> <pre><code>buf = create_string_buffer(8) print type(buf) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) print type(fh.f_handle) </code></pre> <p>Will output</p> <pre><code>&lt;class 'ctypes.c_char_Array_8'&gt; &lt;class 'ctypes.LP_c_char'&gt; </code></pre> <p>You have defined your struct to accept a pointer to a c_char. So when you try to access fh.f_handle it will expect the value to be a memory address containing the address to the actual single c_char.</p> <p>But by trying to input a c_char * 8 from the string buffer it will convert the first part of your buffer to a pointer.</p> <p>Python tries to dereference your char[0] which means that it will look for a memory address with the value of the character you have defined in char[0]. That memory address is not valid, so your interpreter will signal a SIGSEGV.</p> <p>Now to create a class which properly handles a variable length buffer is quite difficult. An easier option is to pass the buffer as an opaque handle, to access it afterwards you need to cast it back to a char array.</p> <p>Example:</p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", c_void_p) ] buf = create_string_buffer(8) buf = cast(buf, c_void_p) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) f_handle_value = (c_char * fh.handle_bytes).from_address(fh.f_handle) </code></pre>
Maven enterprise application run with -1.0 in the end <p>Sometimes when i run my <strong>maven web application</strong>, the application run with <strong>-1.0</strong> in the end, and this make a problem, is there any explanation of this problem, and how we can solve it.</p> <p>Normal url : <a href="http://localhost:8080/projectmvn-web" rel="nofollow">http://localhost:8080/projectmvn-web</a></p> <p>Wrong url : <a href="http://localhost:8080/projectmvn-web" rel="nofollow">http://localhost:8080/projectmvn-web-1.0</a></p> <p>I use server <strong>glassfish-3.1.2</strong> and <strong>Netbeans 8.1</strong>.</p> <p>EDIT:</p> <p><strong>application.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" version="6"&gt; &lt;description&gt;description..&lt;/description&gt; &lt;display-name&gt;projectmvn-ear&lt;/display-name&gt; &lt;module&gt; &lt;ejb&gt;projectmvn-ejb-1.0.jar&lt;/ejb&gt; &lt;/module&gt; &lt;module&gt; &lt;web&gt; &lt;web-uri&gt;projectmvn-web-1.0.war&lt;/web-uri&gt; &lt;context-root&gt;/projectmvn-web&lt;/context-root&gt; &lt;/web&gt; &lt;/module&gt; &lt;library-directory&gt;lib&lt;/library-directory&gt; &lt;/application&gt; </code></pre> <p>Thank you.</p>
<p>Assuming the <code>1.0</code> is the project version in your <code>pom.xml</code> file, if you don't have the <code>build</code> element in your <code>pom.xml</code> add the following as a child of <code>project</code> element:</p> <pre><code>&lt;build&gt; &lt;finalName&gt;projectmvn-web&lt;/finalName&gt; &lt;/build&gt; </code></pre> <p>If you already have the <code>build</code> element add the <code>filalName</code> element as follows:</p> <pre><code>&lt;build&gt; &lt;finalName&gt;projectmvn-web&lt;/finalName&gt; // the rest goes here &lt;/build&gt; </code></pre> <p>With this setting Maven should create <code>projectmvn-web.war</code> in the <code>target</code>folder, i.e., without the version information on the filename.</p>
Wordpress child theme style.css not working <p>I have created a file structure in the same format as my parent theme. My parent theme is called Alpine and within Alpine there is a functions.php and style.css file. There do not appear to be any additional style.css files.</p> <p>I have created a directory called Alpine-child and within that I have created a functions.php and style.css file.</p> <p>I can't work out why any changes I make to the child style.css are not implemented but they are when I make the same changes in parent style.css</p> <p>This is my child style.css:</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-html lang-html prettyprint-override"><code>/* Theme Name: Alpine Child Theme URI: http://www.creative-ispiration.com/wp/alpine/ Description: My first child theme, based on Alpine Author: MilkshakeThemes Author URI: http://themeforest.net/user/milkshakethemes Template: Alpine Version: 1.0.0 Tags: one-column, two-columns, right-sidebar, fluid-layout, custom-menu, editor-style, featured-images, post-formats, rtl$ Text Domain: alpine-child */</code></pre> </div> </div> </p> <p>This is my child functions.php file:</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-html lang-html prettyprint-override"><code>&lt;?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ?&gt;</code></pre> </div> </div> </p>
<p>Take a look at your <code>&lt;head&gt;</code> tag. More importantly look at the order of your stylesheets.</p> <p>The styles from your child theme are being added first and then all the styles from your parent theme. This will cause the styles from the parent theme to override your child theme styles.</p> <p>You can change the priority of your <code>my_theme_enqueue_styles</code> function to run after the parent by using the third parameter of <a href="https://developer.wordpress.org/reference/functions/add_action/" rel="nofollow">add_action</a>. This will enqueue your child theme styles last and allow the CSS to work as expected.</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 11 ); function my_theme_enqueue_styles() { wp_enqueue_style( 'child-style', get_stylesheet_uri() ); } ?&gt; </code></pre>
Mod Rewrite: Leading slash followed by parameter after domain name <p>I'm trying to create a rewrite rule that changes a URLwith parameters into just a forward slash followed by a parameter.</p> <p>The RewriteRule: <code>RewriteRule ^(.*)$ send.php?url=$1&amp;name=&amp;submit=submit [NC,L]</code></p> <p>The above rule should then work for the URL: <code>example.com/google.com</code></p> <p>But although the URL <code>example.com/google.com</code> remains in the browser bar and I do not get a 404 or 500 server error, instead of adding google.com as a parameter, <code>send.php</code> is added as the URL parameter instead.</p> <p>The URL should go to: <code>send.php?url=google.com&amp;name=&amp;submit=submit</code> But it currently goes to: <code>send.php?url=send.php&amp;name=&amp;submit=submit</code></p> <p>Interestingly if I change the <code>RewriteRule</code> slightly, everything works fine. Working <code>RewriteRule</code> <code>RewriteRule ^send/(.*)$ /send.php?url=$1&amp;name=&amp;submit=submit [NC,L]</code></p> <p>Here's a copy of the log for both working and not working versions of the <code>RewriteRule</code>.<br> Log for (working)<code>RewriteRule ^send/(.*)$ /send.php?url=$1&amp;name=&amp;submit=submit [NC,L]</code> </p> <p>[Tue Oct 11 11:03:09.500902 2016] [rewrite:trace3] [pid 6376:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:14876] 127.0.0.1 - - [example.com/sid#611988][rid#2f16c40/initial] [perdir C:/xampp/htdocs/test/] add path info postfix: C:/xampp/htdocs/test/send -> C:/xampp/htdocs/test/send/google.com</p> <p>[Tue Oct 11 11:03:09.500902 2016] [rewrite:trace3] [pid 6376:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:14876] 127.0.0.1 - - [example.com/sid#611988][rid#2f16c40/initial] [perdir C:/xampp/htdocs/test/] strip per-dir prefix: C:/xampp/htdocs/test/send/google.com -> send/google.com</p> <p>[Tue Oct 11 11:03:09.500902 2016] [rewrite:trace3] [pid 6376:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:14876] 127.0.0.1 - - [example.com/sid#611988][rid#2f16c40/initial] [perdir C:/xampp/htdocs/test/] applying pattern '^send/(.*)$' to uri 'send/google.com'</p> <p>[Tue Oct 11 11:03:09.500902 2016] [rewrite:trace2] [pid 6376:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:14876] 127.0.0.1 - - [example.com/sid#611988][rid#2f16c40/initial] [perdir C:/xampp/htdocs/test/] rewrite 'send/google.com' -> '/send.php?url=google.com&amp;name=&amp;submit=submit'</p> <p>[Tue Oct 11 11:03:09.500902 2016] [rewrite:trace3] [pid 6376:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:14876] 127.0.0.1 - - [example.com/sid#611988][rid#2f16c40/initial] split uri=/send.php?url=google.com&amp;name=&amp;submit=submit -> uri=/send.php, args=url=google.com&amp;name=&amp;submit=submit</p> <p>Log for (not working)<code>RewriteRule ^(.*)$ send.php?url=$1&amp;name=&amp;submit=submit [NC,L]</code> </p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] [perdir C:/xampp/htdocs/test/] strip per-dir prefix: C:/xampp/htdocs/test/google.com -> google.com</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] [perdir C:/xampp/htdocs/test/] applying pattern '^(.*)$' to uri 'google.com'</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace2] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] [perdir C:/xampp/htdocs/test/] rewrite 'google.com' -> 'send.php?url=google.com&amp;name=&amp;submit=submit'</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] split uri=send.php?url=google.com&amp;name=&amp;submit=submit -> uri=send.php, args=url=google.com&amp;name=&amp;submit=submit</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] [perdir C:/xampp/htdocs/test/] add per-dir prefix: send.php -> C:/xampp/htdocs/test/send.php</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace2] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] [perdir C:/xampp/htdocs/test/] strip document_root prefix: C:/xampp/htdocs/test/send.php -> /send.php</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace1] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3314c38/initial] [perdir C:/xampp/htdocs/test/] internal redirect with /send.php [INTERNAL REDIRECT]</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#331af78/initial/redir#1] [perdir C:/xampp/htdocs/test/] strip per-dir prefix: C:/xampp/htdocs/test/send.php -> send.php</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#331af78/initial/redir#1] [perdir C:/xampp/htdocs/test/] applying pattern '^(.*)$' to uri 'send.php'</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace2] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#331af78/initial/redir#1] [perdir C:/xampp/htdocs/test/] rewrite 'send.php' -> 'send.php?url=send.php&amp;name=&amp;submit=submit'</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#331af78/initial/redir#1] split uri=send.php?url=send.php&amp;name=&amp;submit=submit -> uri=send.php, args=url=send.php&amp;name=&amp;submit=submit</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#331af78/initial/redir#1] [perdir C:/xampp/htdocs/test/] add per-dir prefix: send.php -> C:/xampp/htdocs/test/send.php</p> <p>[Tue Oct 11 11:21:58.485476 2016] [rewrite:trace1] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#331af78/initial/redir#1] [perdir C:/xampp/htdocs/test/] initial URL equal rewritten URL: C:/xampp/htdocs/test/send.php [IGNORING REWRITE]</p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] add path info postfix: C:/xampp/htdocs/test/css -> C:/xampp/htdocs/test/css/style.css, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] strip per-dir prefix: C:/xampp/htdocs/test/css/style.css -> css/style.css, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] applying pattern '^(.*)$' to uri 'css/style.css', referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace2] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] rewrite 'css/style.css' -> 'send.php?url=css/style.css&amp;name=&amp;submit=submit', referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] split uri=send.php?url=css/style.css&amp;name=&amp;submit=submit -> uri=send.php, args=url=css/style.css&amp;name=&amp;submit=submit, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] add per-dir prefix: send.php -> C:/xampp/htdocs/test/send.php, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace2] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] strip document_root prefix: C:/xampp/htdocs/test/send.php -> /send.php, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.862783 2016] [rewrite:trace1] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3316c40/initial] [perdir C:/xampp/htdocs/test/] internal redirect with /send.php [INTERNAL REDIRECT], referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.863783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3319138/initial/redir#1] [perdir C:/xampp/htdocs/test/] strip per-dir prefix: C:/xampp/htdocs/test/send.php -> send.php, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.863783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3319138/initial/redir#1] [perdir C:/xampp/htdocs/test/] applying pattern '^(.*)$' to uri 'send.php', referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.863783 2016] [rewrite:trace2] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3319138/initial/redir#1] [perdir C:/xampp/htdocs/test/] rewrite 'send.php' -> 'send.php?url=send.php&amp;name=&amp;submit=submit', referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.863783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3319138/initial/redir#1] split uri=send.php?url=send.php&amp;name=&amp;submit=submit -> uri=send.php, args=url=send.php&amp;name=&amp;submit=submit, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.863783 2016] [rewrite:trace3] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3319138/initial/redir#1] [perdir C:/xampp/htdocs/test/] add per-dir prefix: send.php -> C:/xampp/htdocs/test/send.php, referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>[Tue Oct 11 11:22:03.863783 2016] [rewrite:trace1] [pid 5176:tid 1632] mod_rewrite.c(476): [client 127.0.0.1:15724] 127.0.0.1 - - [example.com/sid#3e1988][rid#3319138/initial/redir#1] [perdir C:/xampp/htdocs/test/] initial URL equal rewritten URL: C:/xampp/htdocs/test/send.php [IGNORING REWRITE], referer: <a href="http://example.com/google.com" rel="nofollow">http://example.com/google.com</a></p> <p>Looking at the log it gets it correct to begin with: <code>url=google.com</code>, but then further along changes to <code>url=send.php</code></p> <p>So in summary, how can I turn this URL: <code>example.com/send.php?url=google.com&amp;name=&amp;submit=submit</code> into this URL: <code>example.com/google.com</code></p>
<p>Try with:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ send.php?url=$1&amp;name=&amp;submit=submit [NC,L] </code></pre> <p>This way you avoid to rewrite existing files and directories.</p> <p>With <code>-f</code> you test for files, and with <code>-d</code> for directories. <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond" rel="nofollow">http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond</a></p>
React-Native Fresh Install Compile Error <p>I've created a few react-native projects, and since updating to Sierra OSX and Xcode 8, upon opening each project, I get the error:</p> <p><code>Application AppName has not been registered. This is either to due to a require() error during initialisation or a failure to call AppRegistry.registerComponent.</code></p> <p>I've gone back to basics, uninstalled and reinstalled node, reinstalled latest react-native, created a fresh init, and still get the error. I've looked up and removed the custom-compiler-flags, as suggested <a href="https://github.com/facebook/react-native/issues/8584#issuecomment-236366222" rel="nofollow">here</a>.</p> <p>This is a real problem, if anyone has any insights I would be very appreciative!</p>
<p>I was having this error last night! All I did was to remove the node_modules, install then again and run the app again, it worked. – Crysfel</p>
What is NavigationServices.FirstOrDefault() of Template10 navigation service? <p>I want to navigate between pages in Template10. From the documentation, <a href="https://github.com/Windows-XAML/Template10/wiki/Services#navigationservice" rel="nofollow">https://github.com/Windows-XAML/Template10/wiki/Services#navigationservice</a>, the example is as follow</p> <blockquote> <p>// from inside any window var nav = WindowWrapper.Current().NavigationServices.FirstOrDefault(); nav.Navigate(typeof(Views.DetailPage), this.Value);</p> </blockquote> <p>Unfortunately WindowWrapper.Current().NavigationServices.FirstOrDefault() does not exist. What FirstOrDefault actually means?</p> <p>Also, how do I navigate to other page from page.xaml.cs?</p>
<p><code>FirstOrDefault()</code> is an extension method provided by LINQ. You need to add the line:</p> <pre><code>using System.Linq; </code></pre> <p>at the top of your file to get it.</p>
How to insert a attachment and update a custom field in a post type in Wordpress <p>I have a custom post type named ['notifications'] with a custom field named ['attachment'] for all posts in ['notifications'] .</p> <ul> <li>I want a user to upload a attachment into the library from the front end</li> <li>If upload is successful</li> <li>Get the filename of the attachment </li> <li>Then update a post in custom post type ['notifications'] by its id </li> <li>Update custom field ['attachment'] in a post to filename</li> </ul> <p>The meta_key for the custom field is ['_ct_text_57fc8ec4573cd']</p> <p>This is what I have so far</p> <p><strong>FOR THE FRONT END</strong></p> <pre><code>&lt;?php if (isset($_POST['upload'])) { if (!empty($_FILES)) { $file = $_FILES['file']; $attachment_id = upload_user_file($file); } } ?&gt; &lt;form action="" enctype="multipart/form-data" method="post"&gt; &lt;input name="file" type="file"&gt; &lt;/form&gt; </code></pre> <p><strong>INSIDE FUNCTIONS.PHP</strong></p> <pre><code>function upload_user_file($file = array()) { require_once(ABSPATH. 'wp-admin/includes/admin.php'); $file_return = wp_handle_upload($file, array('test_form' =&gt; false)); if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) { return false; } else { $filename = $file_return['file']; $post_ID_attachment = 33; $attachment = array('post_mime_type' =&gt; $file_return['type'], 'post_title' =&gt; $post_ID_attachment, 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'guid' =&gt; $file_return['url'] ); $attachment_id = wp_insert_attachment($attachment, $file_return['url']); require_once(ABSPATH. 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename); wp_update_attachment_metadata($attachment_id, $attachment_data); if (0 &lt; intval($attachment_id)) { return $attachment_id; } /* UPDATE ATTACHMENT BELOW*/ update_post_meta($post_ID_attachment, '_ct_text_57fc8ec4573cd', $filename); } return false; } </code></pre> <p>Not sure if I am doing it correctly. The code above inserts attachment successfully but it is not updating the custom field in post type ['notifications']</p>
<p>You have a return statement in your function, before <code>update_post_meta</code> query. Try following code:</p> <pre><code>function upload_user_file($file = array()) { require_once(ABSPATH. 'wp-admin/includes/admin.php'); $file_return = wp_handle_upload($file, array('test_form' =&gt; false)); if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) { return false; } else { $filename = $file_return['file']; $post_ID_attachment = 33; $attachment = array('post_mime_type' =&gt; $file_return['type'], 'post_title' =&gt; $post_ID_attachment, 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'guid' =&gt; $file_return['url'] ); $attachment_id = wp_insert_attachment($attachment, $file_return['url']); require_once(ABSPATH. 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename); wp_update_attachment_metadata($attachment_id, $attachment_data); /* UPDATE ATTACHMENT BELOW*/ update_post_meta($post_ID_attachment, '_ct_text_57fc8ec4573cd', $filename); if (0 &lt; intval($attachment_id)) { return $attachment_id; } } return false; } </code></pre> <p>Also I'm not sure you need these <code>require_once</code>-s in your code, since it in <code>function.php</code>, everything should be loaded.</p>
Update nested structure of maps and vectors <p>I have a map with a vector of map like this:</p> <pre><code>{:tags ["type:something" "gw:somethingelse"], :sources [{:tags ["s:my:tags"], :metrics [{:tags ["a tag"]} {:tags ["a noether tag" "aegn"]} {:tags ["eare" "rh"]}]}]} </code></pre> <p>Note that there can be multiple sources, and multiple metrics.</p> <p>Now I want to update the <code>:metrics</code> with an <code>id</code> by looking at the value of the tags. </p> <p>Example: if <code>["a tag"]</code> matches with for example id 1, and <code>["a noether tag" "aegn"]</code> with id 2 I want the updated structure to look like this:</p> <pre><code>{:tags ["type:something" "gw:somethingelse"], :sources [{:tags ["s:my:tags"], :metrics [{:tags ["a tag"] :id 1} {:tags ["a noether tag" "aegn"] :id 2} {:tags ["eare" "rh"]}]}]} </code></pre> <p>I made a function <code>transform</code> that can convert a tag to an id. E.g, <code>(transform "a tag")</code> returns 1.</p> <p>Now, when I try do add the ids with a for-comprehension I miss the old structure (only the inner ones get returned) and with <code>assoc-in</code> I have to know the indices upfront.</p> <p>How can I perform this transformation elegantly?</p>
<p>i would start bottom up, making transformation function for <code>:tags</code> entry, then for <code>:metrics</code> and then for <code>:sources</code>. </p> <p>let's say our transform function produces ids just by counting tags (just for illustration, it could be easily changed later):</p> <pre><code>(defn transform [tags] (count tags)) user&gt; (transform ["asd" "dsf"]) ;;=&gt; 2 </code></pre> <p>then apply transformation the metric entry:</p> <pre><code>(defn transform-metric [{:keys [tags] :as m}] (assoc m :id (transform tags))) user&gt; (transform-metric {:tags ["a noether tag" "aegn"]}) ;;=&gt; {:tags ["a noether tag" "aegn"], :id 2} </code></pre> <p>now use <code>transform-metric</code> to update source entry:</p> <pre><code>(defn transform-source [s] (update s :metrics #(mapv transform-metric %))) user&gt; (transform-source {:tags ["s:my:tags"], :metrics [{:tags ["a tag"]} {:tags ["a noether tag" "aegn"]} {:tags ["eare" "rh"]}]}) ;;=&gt; {:tags ["s:my:tags"], ;; :metrics [{:tags ["a tag"], :id 1} ;; {:tags ["a noether tag" "aegn"], :id 2} ;; {:tags ["eare" "rh"], :id 2}]} </code></pre> <p>and the last step is to transform the whole data:</p> <pre><code>(defn transform-data [d] (update d :sources #(mapv transform-source %))) user&gt; (transform-data data) ;;=&gt; {:tags ["type:something" "gw:somethingelse"], ;; :sources [{:tags ["s:my:tags"], ;; :metrics [{:tags ["a tag"], :id 1} ;; {:tags ["a noether tag" "aegn"], :id 2} ;; {:tags ["eare" "rh"], :id 2}]}]} </code></pre> <p>so, we're done here. </p> <p>Now notice that <code>transform-data</code> and <code>transform-source</code> are almost identical, so we can make an utility function that generates such updating functions:</p> <pre><code>(defn make-vec-updater [field transformer] (fn [data] (update data field (partial mapv transformer)))) </code></pre> <p>with this function we can define deep transformations like this:</p> <pre><code>(def transformer (make-vec-updater :sources (make-vec-updater :metrics (fn [{:keys [tags] :as m}] (assoc m :id (transform tags)))))) user&gt; (transformer data) ;;=&gt; {:tags ["type:something" "gw:somethingelse"], ;; :sources [{:tags ["s:my:tags"], ;; :metrics [{:tags ["a tag"], :id 1} ;; {:tags ["a noether tag" "aegn"], :id 2} ;; {:tags ["eare" "rh"], :id 2}]}]} </code></pre> <p>and based on this transformer construction approach we can make a nice function to update the values in vectors-of-maps-of-vectors-of-maps-of-vectors... structures, with arbitrary nesting level:</p> <pre><code>(defn update-in-v [data ks f] ((reduce #(make-vec-updater %2 %1) f (reverse ks)) data)) user&gt; (update-in-v data [:sources :metrics] (fn [{:keys [tags] :as m}] (assoc m :id (transform tags)))) ;;=&gt; {:tags ["type:something" "gw:somethingelse"], ;; :sources [{:tags ["s:my:tags"], ;; :metrics [{:tags ["a tag"], :id 1} ;; {:tags ["a noether tag" "aegn"], :id 2} ;; {:tags ["eare" "rh"], :id 2}]}]} </code></pre> <p><strong>UPDATE</strong></p> <p>in addition to this manual approach, there is a fantastic lib called <a href="https://github.com/nathanmarz/specter" rel="nofollow">specter</a> out there, that does exactly the same thing (and much more), but is obviously more universal and usable:</p> <pre><code>(require '[com.rpl.specter :as sp]) (sp/transform [:sources sp/ALL :metrics sp/ALL] (fn [{:keys [tags] :as m}] (assoc m :id (transform tags))) data) ;;=&gt; {:tags ["type:something" "gw:somethingelse"], ;; :sources [{:tags ["s:my:tags"], ;; :metrics [{:tags ["a tag"], :id 1} ;; {:tags ["a noether tag" "aegn"], :id 2} ;; {:tags ["eare" "rh"], :id 2}]}]} </code></pre>
2 separate controllers for the same end point in html and json or a single one? <p>I have the end points "/customers" and "/api/v1/customers", in html and json respectively for a list of customers. Do I have to create 2 different controllers and thus actions for them? Or can I return html or json from a single controller and action depending a requested format: html or json? Note that for "/api/v1/customers" I need authentication via an Api Key.</p>
<p>You can have one controller and action for both endpoints, but I would advise against it.</p> <p>You mentioned that those controllers need to do different stuff, so instead of adding stuff like "if json then check api key" make two separate controllers and extract common code of getting all the customers.</p> <p>There is a great talk about untangling business logic from http interface: <a href="http://www.elixirconf.eu/elixirconf2016/lance-halvorsen" rel="nofollow">http://www.elixirconf.eu/elixirconf2016/lance-halvorsen</a> Getting a list of customers might be out of your controllers, so at the end you will have two controllers like this:</p> <pre><code>defmodule MyApp.Api.CustomersController do plug MaApp.ApiAuth #plug for checking api key def index(conn, params) do ... customers = ActualLogic.get_customers() ... end end def MyApp.CustomersController do plug MyApp.UserAuth #for example checks if user is logged in def index(conn, params) do ... customers = ActualLogic.get_customers() ... end end </code></pre> <p>At the end your controller does not perform any logic, it calls something else to do the job and action is responsible only for web stuff like parsing params, authentication via api key, session cookies and translating end result to json/html.</p>
The two generate random numbers and their product is different <p>So im creating a program that generate 2 random numbers and need to multiply them:</p> <pre><code>public static int thenumber(){ int number1=(int)(Math.random()*10+1); return number1; } public static int thenumber2(){ int number2=(int)(Math.random()*10+1); return number2; } </code></pre> <p>and solve it in :</p> <pre><code>public static int thefusion(){ int demi =thenumber() * thenumber2(); return demi; } </code></pre> <p>My problem is when i run it the product of two number is Different ex: 7 * 4 = 24</p>
<p>A complete code example would be nice (see <a href="http://stackoverflow.com/help/mcve">How to create a Minimal, Complete, and Verifiable example</a>), but let me guess: You are first seeing the two random numbers (from printing them or some other way). Then you call your method. The method draws two <em>new</em> random numbers from <code>thenumber()</code> and <code>thenumber2()</code>. That’s the point in (pseudo-)random numbers, you don’t the same number each time. So if you drew the numbers 7 and 4 the first time, maybe next time you get 3 and 8, so the product is 24.</p> <p>There are a couple of possible solutions:</p> <ol> <li>When calling <code>thenumber()</code> and <code>thenumber2()</code>, assign the results to two variables. Now you can see which numbers you got. Pass those two numbers into your <code>thefusion</code> method, and it should calculate the expected product.</li> <li>Rather than <code>Math.random()</code> use the <code>Random</code> class and instantiate it with a known seed. Draw the two numbers from it and inspect them. Make a new <code>Random</code> instance from the same seed and have <code>thefusion()</code> use it. Now it will draw the same two numbers, and you will get the product you expected.</li> </ol>
Matlab - Scale down an image using an average of four pixels <p>I have just started learning image-processing and Matlab and I'm trying to scale down an image using an average of 4 pixels. That means that for every 4 original pixels I calculate the average and produce 1 output pixel. So far I have the following code:</p> <pre><code>img = imread('bird.jpg'); row_size = size(img, 1); col_size = size(img, 2); res = zeros(floor(row_size/2), floor(col_size/2)); figure, imshow(img); for i = 1:2:row_size for j = 1:2:col_size num = mean([img(i, j), img(i, j+1), img(i+1, j), img(i+1, j+1)]); res(round(i/2), round(j/2)) = num; end end figure, imshow(uint8(res)); </code></pre> <p>This code manages to scale down the image but it converts it to grayscale. I understand that I probably have to calculate the average of the <strong>RGB</strong> components for the output pixel but I don't know how to access them, calculate the average and insert them to the result matrix. </p>
<p>In Matlab, an RGB image is treated as a 3D array. You can check it with:</p> <pre><code>depth_size = size(img, 3) depth_size = 3 </code></pre> <p>The loop solution, as you have done, is explained in <a href="http://stackoverflow.com/a/39976574/6469393">Sardar_Usama's answer</a>. However, in Matlab it is recommended to avoid loops whenever you want to gain speed.</p> <p>This is a vectorized solution to scale down an RGB image by a factor of <code>n</code>:</p> <pre><code>img = imread('bird.jpg'); n = 2; % n can only be integer [row_size, col_size] = size(img(:, :, 1)); % getting rid of extra rows and columns that won't be counted in averaging: I = img(1:n*floor(row_size / n), 1:n*floor(col_size / n), :); [r, ~] = size(I(:, :, 1)); % separating and re-ordering the three colors of image in a way ... % that averaging could be done with a single 'mean' command: R = reshape(permute(reshape(I(:, :, 1), r, n, []), [2, 1, 3]), n*n, [], 1); G = reshape(permute(reshape(I(:, :, 2), r, n, []), [2, 1, 3]), n*n, [], 1); B = reshape(permute(reshape(I(:, :, 3), r, n, []), [2, 1, 3]), n*n, [], 1); % averaging and reshaping the colors back to the image form: R_avg = reshape(mean(R), r / n, []); G_avg = reshape(mean(G), r / n, []); B_avg = reshape(mean(B), r / n, []); % concatenating the three colors together: scaled_img = cat(3, R_avg, G_avg, B_avg); % casting the result to the class of original image scaled_img = cast(scaled_img, 'like', img); </code></pre> <h3>Benchmarking:</h3> <p>If you want to know why vectorized solutions are more popular, take a look at how long it takes to process an RGB 768 x 1024 image with the two methods:</p> <pre><code>------------------- With vectorized solution: Elapsed time is 0.024690 seconds. ------------------- With nested loop solution: Elapsed time is 6.127933 seconds. </code></pre> <p>So there is more than 2 orders of magnitude difference of speed between the two solutions.</p>
Cannot show cyrillic letters in PDF produced by apache fop <p>I have created PDF file from xsl file, but my cyrillic letters replaced by # symbol. What can I do? Please if you can give exact answers with exact examples. Thank you!!!</p> <p>This is simple piece of my code that uses cyrillic letters:</p> <pre><code> &lt;fo:table-cell padding="1em" text-align="center"&gt; &lt;fo:block &gt; &lt;fo:leader leader-pattern="rule" leader-length="80%" rule- style="solid" rule-thickness="1pt" /&gt; &lt;fo:block xml:lang="RU" font-family="Times New Roman" text- align="center"&gt;(подпись)&lt;/fo:block&gt; &lt;/fo:block&gt; &lt;/fo:table-cell&gt; </code></pre>
<p>Just create .xml file</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;fop version="1.0"&gt; &lt;renderers&gt; &lt;renderer mime="application/pdf"&gt; &lt;fonts&gt; &lt;directory&gt;C:\Windows\Fonts&lt;/directory&gt; &lt;/fonts&gt; &lt;/renderer&gt; &lt;/renderers&gt; &lt;/fop&gt; </code></pre> <p>And add this two lines of code in your java file:</p> <pre><code>File userConfig = new File("src/main/java/view/userConfig.xml"); FopFactory fopFactory = FopFactory.newInstance(userConfig); </code></pre>
How can I use Gradle to download dependencies and their source files and place them all in one directory? <p>I would like to use Gradle to download dependencies and their source files and place them all in one directory. I found this answer below that tells me how to do it for the dependencies themselves, but I would like to also get the source files. How do I do that?</p> <p>I know that the Eclipse plugin can grab source files, but I don't know where it places them.</p> <p><a href="http://stackoverflow.com/questions/32402541/how-can-i-use-gradle-to-just-download-jars">How can I use Gradle to just download JARs?</a></p>
<pre><code>apply plugin: 'java' configurations { runtimeSources } dependencies { compile 'foo:bar:1.0' runtime 'foo:baz:1.0' configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { ResolvedArtifact ra -&gt; ModuleVersionIdentifier id = ra.moduleVersion.id runtimeSources "${id.group}:${id.name}:${id.version}:sources" } } task download(type: Copy) { from configurations.runtime from configurations.runtimeSources into "${buildDir}/download" } </code></pre>
MySQL value of a parameter that reruns every entry <p>Is it possible to set value of a parameter such that in where clause it always results true?</p> <p>As example consider a query:</p> <pre><code>SELECT name FROM student WHERE class=@parameter; </code></pre> <p>Now my question is "is it possible to set a value of parameter such that this query reruns name of every student".</p>
<p>The typical method is:</p> <pre><code>SELECT name FROM student WHERE (class = @parameter OR @parameter IS NULL); </code></pre>
How to hide message window in MS SQL Server 2008? <p><a href="http://i.stack.imgur.com/pkCQo.png" rel="nofollow">enter image description here</a></p> <p>Attached Picture</p>
<p><kbd>CTRL</KBD> +<KBD>R</KBD></p> <p>hides message window</p> <p>you also can display results in seperate window like below</p> <p>goto Tools | Option menu. On the option dialog, navigate into Query Results | SQL Server | Results to Grid or Results to Text On the option dialog, check on [Display results in a separate tab].</p> <p>there is also connect item asking for close button as well</p> <p><a href="https://connect.microsoft.com/SQLServer/feedback/details/289069/sql-server-management-studio-cannot-close-the-results-messages-window" rel="nofollow">https://connect.microsoft.com/SQLServer/feedback/details/289069/sql-server-management-studio-cannot-close-the-results-messages-window</a></p>
Is there a way to add custom keyboard shortcuts to Vim for running numerous commands? <p>I'm having the following issue - whenever I finish writing some C++ code in Vim and want to compile and run it, I have to:</p> <ol> <li>Exit insert mode</li> <li>Save the file using the command <code>:w</code></li> <li>Write <code>:! g++ *.cpp -o programName; ./programName</code> in order to compile and run at once</li> </ol> <p>After inputting the last two commands once, I obviously make use of the upper arrow key on the keyboard to get the last few commands instead of writting them down again and again on future compilations and runs. </p> <p>But it's still kind of slow to me. So I was wondering if there's some sort of way to maybe create a keyboard shortcut which inputs these last two commands or even does all the three things at once!</p>
<p>You can use <code>map</code> to map keys to commands. <code>nmap</code> for normal mode, <code>imap</code> for insert mode etc</p> <pre><code>map &lt;key&gt; command </code></pre> <p>the <code>cpp</code> compiling you mentioned should go like:</p> <pre><code>autocmd FileType cpp nmap &lt;buffer&gt; &lt;F5&gt; :w&lt;bar&gt;!g++ -o %:r % &amp;&amp; ./%:r&lt;CR&gt; </code></pre> <p>Add this command to your <code>vimrc</code> and will compile and run the current cpp file.<br><br> <code>FileType cpp</code>- detects the <code>cpp</code> file directly, (<em>no need of manual regex</em>).<br> <code>nmap</code>- used for mapping key while normal mode.<br> <code>buffer</code>- for the current buffer (<em>in case of multiple splits</em>).<br> <code>&lt;F5&gt;</code>- for mapping the 'F5' key.<br> And the command that executes is: <code>:w | !g++ -o %:r % &amp;&amp; ./%:r&lt;CR&gt;</code><br></p> <p>In the above command, <code>%</code> is the file name without extension, while <code>%:r</code> is the file name(<em>with extension</em>),<br> <code>&lt;CR&gt;</code> stands for the "Enter" button (<em>Carriage Return</em>)</p>
block multiple request from same user id to a web method c# <p>I have a web method upload Transaction (ASMX web service) that take the XML file, validate the file and store the file content in SQL server database. we noticed that a certain users can submit the same file twice at the same time. so we can have the same codes again in our database( we cannot use unique index on the database or do anything on database level, don't ask me why). I thought I can use the lock statement on the user id string but i don't know if this will solve the issue. or if I can use a cashed object for storing all user id requests and check if we have 2 requests from the same user Id we will execute the first one and block the second request with an error message so if anyone have any idea please help</p>
<p>Blocking on strings is bad. Blocking your webserver is bad. </p> <p><code>AsyncLocker</code> is a handy class that I wrote to allow locking on any type that behaves nicely as a key in a dictionary. It also requires asynchronous awaiting before entering the critical section (as opposed to the normal blocking behaviour of locks):</p> <pre><code>public class AsyncLocker&lt;T&gt; { private LazyDictionary&lt;T, SemaphoreSlim&gt; semaphoreDictionary = new LazyDictionary&lt;T, SemaphoreSlim&gt;(); public async Task&lt;IDisposable&gt; LockAsync(T key) { var semaphore = semaphoreDictionary.GetOrAdd(key, () =&gt; new SemaphoreSlim(1,1)); await semaphore.WaitAsync(); return new ActionDisposable(() =&gt; semaphore.Release()); } } </code></pre> <p>It depends on the following two helper classes:</p> <p>LazyDictionary:</p> <pre><code>public class LazyDictionary&lt;TKey,TValue&gt; { //here we use Lazy&lt;TValue&gt; as the value in the dictionary //to guard against the fact the the initializer function //in ConcurrentDictionary.AddOrGet *can*, under some conditions, //run more than once per key, with the result of all but one of //the runs being discarded. //If this happens, only uninitialized //Lazy values are discarded. Only the Lazy that actually //made it into the dictionary is materialized by accessing //its Value property. private ConcurrentDictionary&lt;TKey, Lazy&lt;TValue&gt;&gt; dictionary = new ConcurrentDictionary&lt;TKey, Lazy&lt;TValue&gt;&gt;(); public TValue GetOrAdd(TKey key, Func&lt;TValue&gt; valueGenerator) { var lazyValue = dictionary.GetOrAdd(key, k =&gt; new Lazy&lt;TValue&gt;(valueGenerator)); return lazyValue.Value; } } </code></pre> <p>ActionDisposable:</p> <pre><code>public sealed class ActionDisposable:IDisposable { //useful for making arbitrary IDisposable instances //that perform an Action when Dispose is called //(after a using block, for instance) private Action action; public ActionDisposable(Action action) { this.action = action; } public void Dispose() { var action = this.action; if(action != null) { action(); } } } </code></pre> <p>Now, if you keep a static instance of this somewhere:</p> <pre><code>static AsyncLocker&lt;string&gt; userLock = new AsyncLocker&lt;string&gt;(); </code></pre> <p>you can use it in an <code>async</code> method, leveraging the delights of <code>LockAsync</code>'s <code>IDisposable</code> return type to write a <code>using</code> statement that neatly wraps the critical section:</p> <pre><code>using(await userLock.LockAsync(userId)) { //user with userId only allowed in this section //one at a time. } </code></pre> <p>If we need to wait before entering, it's done asynchronously, freeing up the thread to service other requests, instead of blocking until the wait is over and potentially messing up your server's performance under load.</p> <p>Of course, when you need to scale to more than one webserver, this approach will no longer work, and you'll need to synchronize using a different means (probably via the DB).</p>
How do you email a query result as a csv using sp_send_dbmail stored procedure with SQL? <p>I would like to send an email containing the results of a query as a csv attachment.</p> <p>So far I have this;</p> <pre><code>EXEC msdb.dbo.sp_send_dbmail @recipients='me@myself.com', @subject='CSV Extract', @profile_name = 'Valid profile', @body='See attachment', @query ='SELECT TOP 10 c.* FROM MyDb.dbo.Customers c', @attach_query_result_as_file = 1, @query_attachment_filename = 'CSV_Extract.csv', @query_result_separator = ',' </code></pre> <p>I receive the email with a csv attachment but when opened in Excel the results are horribly formatted (e.g. all values are in a single column with seemingly random indentation)</p> <p>What should I be doing to get a correctly formatted result with correct column headers etc?</p> <p><strong>EDIT</strong></p> <p>I have added the following parameters to the query;</p> <pre><code>@query_result_width = 32767, @query_result_no_padding = 1 </code></pre> <p>This improved things a lot however I am still getting each record in a single column when opened inside Excel. How can I place each value within a record into it's own column?</p> <p>This is what I currently get;</p> <p><a href="http://i.stack.imgur.com/wKauv.png" rel="nofollow"><img src="http://i.stack.imgur.com/wKauv.png" alt="enter image description here"></a></p> <p>This is what I'm after;</p> <p><a href="http://i.stack.imgur.com/SZHBS.png" rel="nofollow"><img src="http://i.stack.imgur.com/SZHBS.png" alt="enter image description here"></a></p>
<p>The problem is that Excel doesn't understand the columns. To fix this you need to send instructions to Excel explaining the csv file.</p> <p>The instruction needs to be the first part of the file, before the data so you have to create an alias for the first field in the query that contains the Excel instructions along with the actual name you want</p> <p>The instruction is “sep=,”, to ensure that excel will understand comma field separator.</p> <pre><code>DECLARE @column1name varchar(50) -- Create the column name with the instrucation in a variable SET @Column1Name = '[sep=,' + CHAR(13) + CHAR(10) + 'Name]' DECLARE @qry varchar(8000) -- Create the query, concatenating the column name as an alias SELECT @qry='set nocount on; SELECT TOP 10 c.CCustName ' + @column1name + ' ,c.CID Id FROM MyDb.dbo.Customers c' EXEC msdb.dbo.sp_send_dbmail @recipients='me@myself.com', @subject='CSV Extract', @profile_name = 'Valid Profile', @body='See attachment', @query =@qry, @attach_query_result_as_file = 1, @query_attachment_filename = 'CSV_Extract.csv', @query_result_separator = ',', @query_result_width = 32767, @query_result_no_padding = 1 </code></pre> <p>These are the final results;</p> <p><a href="http://i.stack.imgur.com/KKG83.png" rel="nofollow"><img src="http://i.stack.imgur.com/KKG83.png" alt="enter image description here"></a></p> <p>It's not perfect (Line two is annoying) but it is certainly good enough for my purposes</p>
ios - SocketMobile SocketScan Carrier Name <p>I implemented <code>socket scan API</code> in iOS to scan and get the bar code and that seems to be working fine. I wanted to know if there is a way to find out the carrier name via the <code>socket scan API</code> ?</p>
<p>ScanAPI only provides the data that is encoded in the barcode and the barcode type. For example, the 12 digits of a UPC-A barcode - which are often printed below the barcode too.</p> <p>However, different carriers use different barcode types or format the encoded data differently. For example, UPS uses Aztec barcodes. USPS uses Code 128, which is quite common, but the barcode contains the tracking number which will start with a particular prefix depending on which service was used to send the letter/parcel.</p> <p>You can probably detect the carrier using this information, but you'd need to figure out the pattern for each carrier yourself.</p>
Switch Derived class of a shared pointer to base class <p>I am currently trying to switch the type of a derived class stored in a shared pointer to base class. The problem is that the Derived class inherit from the Base class and is also templated as follow:</p> <p>Base class:</p> <pre><code>#define PRINT(s) std::cout &lt;&lt; s &lt;&lt; std::endl class Base { public: Base() : m_a(1) {} virtual ~Base() = default; virtual void print() { PRINT("BASE"); } int m_a; }; </code></pre> <p>The derived class depend on an enumeration template:</p> <pre><code>enum eType { e0, e1 }; template&lt;eType et&gt; class Derived : public Base { }; template&lt;&gt; class Derived&lt;e0&gt; : public Base { public: Derived() { this-&gt;m_a = e0; } void print() { PRINT("Derived e0, m_a value: " &lt;&lt; e0 ); } }; template&lt;&gt; class Derived&lt;e1&gt; : public Base { public: Derived() { this-&gt;m_a = e1; } void print() { PRINT("Derived e1, m_a value: " &lt;&lt; e1 ); } }; </code></pre> <p>My objective is to have a shared pointer to the Base class so it would be possible to switch from the 2 derived classes as follow:</p> <pre><code>int main() { std::shared_ptr&lt;Base&gt; sp_00 = std::make_shared&lt;Derived&lt;e0&gt;&gt; (); std::shared_ptr&lt;Base&gt; sp_01 = sp_00; sp_01-&gt;print(); std::shared_ptr&lt;Base&gt; sp_10 = std::make_shared&lt;Derived&lt;e1&gt;&gt; (); *sp_01 = *sp_10; sp_01-&gt;print(); sp_10-&gt;print(); } </code></pre> <p>The only problem as on the line <code>*sp_01 = *sp_10;</code> I expect that the pointer to base class switch from the derived type <code>Derived&lt;e0&gt;</code> to the derived type <code>Derived&lt;e1&gt;</code>. However in my example I get a different result for the line <code>sp_01-&gt;print();</code> and the line <code>sp_10-&gt;print();</code> indicating that <code>sp_01</code> stays as a <code>Derived&lt;e0&gt;</code> type.</p> <p>I want to avoid <code>sp_01 = sp_10;</code> because it will change the pointer. In the above example, it would lead to <code>sp_00 != sp_01</code> and I want both <code>sp_00</code> and <code>sp_01</code> to share the same object.</p> <p>I tried to replace the template derived class by a non template derived class as follow:</p> <pre><code>class Derived_e0 : public Base { public: Derived() { this-&gt;m_a = e0; } void print() { PRINT("Derived e0, m_a value: " &lt;&lt; e0 ); } }; class Derived_e1 : public Base { public: Derived() { this-&gt;m_a = e1; } void print() { PRINT("Derived e1, m_a value: " &lt;&lt; e1 ); } }; </code></pre> <p>and the following code give the same result as the one with template.</p> <pre><code>int main() { std::shared_ptr&lt;Base&gt; sp_00 = std::make_shared&lt;Derived_e0&gt; (); std::shared_ptr&lt;Base&gt; sp_01 = sp_00; sp_01-&gt;print(); std::shared_ptr&lt;Base&gt; sp_10 = std::make_shared&lt;Derived_e1&gt; (); *sp_01 = *sp_10; sp_01-&gt;print(); sp_10-&gt;print(); } </code></pre> <p>So my question is, how to switch the derived object pointed by a shared pointer without changing the shared_ptr itself (which is used in other part of the program ?)</p> <p>Thanks, if you need any more information, please let me know</p>
<p>You cannot change the runtime type of <code>sp_01</code> without re-assigning it because you cannot assign <code>Derived&lt;e1&gt;</code> to <code>Derived&lt;e0&gt;</code> (think of what would happen if these do not have the same size - you have allocated enough size for a <code>Derived&lt;e0&gt;</code>, not for a <code>Derived&lt;e1&gt;</code>!).</p> <p>In my opinion, your design (or what you are trying to do with it) is flawed somewhere. However, if you really want to keep a "link" between <code>sp_00</code> and <code>sp_01</code>, you probably need another "level" of pointer:</p> <pre><code>int main() { std::shared_ptr&lt;Base&gt; *psp_01; std::shared_ptr&lt;Base&gt; sp_00 = std::make_shared&lt;Derived&lt;e0&gt;&gt; (); psp_01 = &amp;sp_00; (*psp_01)-&gt;print(); std::shared_ptr&lt;Base&gt; sp_10 = std::make_shared&lt;Derived&lt;e1&gt;&gt; (); psp_01 = &amp;sp_10; (*psp_01)-&gt;print(); sp_10-&gt;print(); } </code></pre> <p>But again, I would analyze my design twice before using this.</p>
How to integrate Typescript into Jenkins/SonarQube <p>Does anybody have experience integrating a project using typescript code in Jenkins and SonarQube? I would like to know if there are any plugins for the usual tasks, as I have been unable to find them. I am specifically interested in the following aspects:</p> <ul> <li>Unit and e2e testing statistics (errors and failure counts, number of tests executed, etc)</li> <li>Typescript code coverage</li> <li>Static code analysis</li> </ul> <p>Thanks in advance</p>
<p>No there is currently no support for Typescript projects in SonarQube. </p>