title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Tablayout+view pager is not displaying the fragment in position 0
<p>My application has 2 tabs with two different layouts. when i run the application, the fragment which is supposed to be shown in tab1(position 0) displays in tab2, and the fragment which is supposed to be in tab2(position 1) is not displaying. Also when i swipe the screen the tab focus is not changing in the tablayout</p> <p>I have given my code below</p> <p>MainActivity.java</p> <pre><code>public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { TabLayout tabLayoutTL; TabLayout.Tab linearTab, gridTab; ViewPager viewPagerVP; ViewPagerAdapter viewPagerAdapter; @Override public void onTabSelected(TabLayout.Tab tab) { viewPagerVP.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); viewPagerVP = (ViewPager)findViewById(R.id.viewPagerVP); viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPagerVP.setAdapter(viewPagerAdapter); tabLayoutTL = (TabLayout)findViewById(R.id.tabLayoutTL); linearTab = tabLayoutTL.newTab(); gridTab = tabLayoutTL.newTab(); linearTab.setText("Linear"); gridTab.setText("Grid"); tabLayoutTL.addTab(linearTab, 0); tabLayoutTL.addTab(gridTab, 1); tabLayoutTL.setOnTabSelectedListener(this); } } </code></pre> <p>MainFragment.java</p> <pre><code>public class MainFragment extends Fragment { private static final String FRAG_TYPE = "frag_type"; int fragType; RecyclerView recyclerViewRv; public MainFragment() {} public static MainFragment newInstance(int fragType) { MainFragment mainFragment = new MainFragment(); Bundle args = new Bundle(); args.putInt(FRAG_TYPE, fragType); mainFragment.setArguments(args); return mainFragment; } private void initialize() { recyclerViewRv = (RecyclerView)getActivity().findViewById(R.id.recyclerViewRv); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initialize(); new BackBone().execute(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { fragType = getArguments().getInt(FRAG_TYPE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_linear, container, false); } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); } class BackBone extends AsyncTask&lt;Void, Void, ArrayList&lt;DataRecord&gt;&gt; { ProgressDialog progressDialog; private static final String flickrUrl = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&amp;format=json&amp;nojsoncallback=1"; private String getData() { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(flickrUrl); try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String data = EntityUtils.toString(httpEntity); return data; } catch (Exception e) { return "exception"; } } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(getActivity()); progressDialog.setTitle("Loading"); progressDialog.setMessage("Please wait ......."); progressDialog.show(); } @Override protected ArrayList&lt;DataRecord&gt; doInBackground(Void... params) { ArrayList&lt;DataRecord&gt; dataRecords = new ArrayList&lt;&gt;(); try { JSONObject jsonObject = new JSONObject(getData()); JSONArray jsonArray = jsonObject.getJSONArray("items"); for (int i = 0 ; i &lt; jsonArray.length() ; i++) { JSONObject jsonObject1 = jsonArray.getJSONObject(i); DataRecord dataRecord = new DataRecord(); dataRecord.setName(jsonObject1.getString("title")); JSONObject mediaJSONObject = jsonObject1.getJSONObject("media"); dataRecord.setUrl(mediaJSONObject.getString("m")); dataRecords.add(dataRecord); } } catch (Exception e) {} return dataRecords; } @Override protected void onPostExecute(ArrayList&lt;DataRecord&gt; dataRecords) { super.onPostExecute(dataRecords); DataRecordAdapter dataRecordAdapter = new DataRecordAdapter(getActivity(), dataRecords, fragType); if (fragType == 1) { recyclerViewRv.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerViewRv.setBackgroundColor(Color.GREEN); } else if (fragType == 2){ recyclerViewRv.setLayoutManager(new GridLayoutManager(getActivity(), 2)); recyclerViewRv.setBackgroundColor(Color.BLUE); } recyclerViewRv.setAdapter(dataRecordAdapter); progressDialog.dismiss(); } } } </code></pre> <p>ViewPagerAdapter.java</p> <pre><code>public class ViewPagerAdapter extends FragmentStatePagerAdapter { public ViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0 : MainFragment mainFragment = MainFragment.newInstance(1); return mainFragment; case 1 : MainFragment mainFragment1 = MainFragment.newInstance(2); return mainFragment1; default : return null; } } @Override public int getCount() { return 2; } } </code></pre> <p>I am sure there is no problem with the fragmets. I think the problem is with the tablayout. I cant figure out where exactly the problem is.</p> <p>DataRecordAdapter.java</p> <pre><code>public class DataRecordAdapter extends RecyclerView.Adapter&lt;DataRecordAdapter.MyViewHolder&gt; { ArrayList&lt;DataRecord&gt; dataRecords; Context context; int flag; LayoutInflater layoutInflater; public DataRecordAdapter(Context context, ArrayList&lt;DataRecord&gt; dataRecords, int flag) { this.context = context; this.dataRecords = dataRecords; this.flag = flag; layoutInflater = (LayoutInflater.from(context)); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if (flag == 1) { view = layoutInflater.inflate(R.layout.linear_data_layout, parent, false); } else { view = layoutInflater.inflate(R.layout.grid_data_layout, parent, false); } MyViewHolder myViewHolder = new MyViewHolder(view); return myViewHolder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { DataRecord dataRecord = dataRecords.get(position); holder.textViewTV.setText(dataRecord.getName()); Picasso.with(context).load(dataRecord.getUrl()).into(holder.imageViewIV); } @Override public int getItemCount() { return dataRecords.size(); } class MyViewHolder extends RecyclerView.ViewHolder { TextView textViewTV; ImageView imageViewIV; public MyViewHolder(View itemView) { super(itemView); textViewTV = (TextView)itemView.findViewById(R.id.textViewTV); imageViewIV = (ImageView)itemView.findViewById(R.id.imageViewIV); } } } </code></pre> <p>DataRecord.java</p> <pre><code>public class DataRecord { String name, url; public String getName() { return name; } [![enter image description here][1]][1] public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } </code></pre> <p><a href="https://i.stack.imgur.com/wlWc2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wlWc2.png" alt="tab 1 is empty"></a></p> <p><a href="https://i.stack.imgur.com/pvtcg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pvtcg.png" alt="tab 2 is displaying the content which is supposed to be on tab1"></a></p> <p>take a look at the images guys. tab 1 is empty and tab 2 shows the content which shoud be on tab 1. tab 2 content is not displayed.</p>
2
CollapsingToolbarLayout and blank space in NestedScrollView
<p>I have a problem with the <code>CollapsingToolbarLayout</code>. I don't want to scroll the <code>NestedScrollView</code> to the end because it leaves a lot of blank space if content, text in my case, is short. Here are screenshots:</p> <p><a href="https://i.stack.imgur.com/NABfMm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NABfMm.jpg" alt="enter image description here"></a></p> <p>And:</p> <p><a href="https://i.stack.imgur.com/t5pEgm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t5pEgm.png" alt="enter image description here"></a></p> <p>Here's XML:</p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/coordinator" &gt; &lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="@dimen/app_bar_description" &gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_scrollFlags="scroll" &gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:layout_collapseMode="parallax"&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/image_pager" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/dots_holder" /&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="15dp" android:id="@+id/dots_holder" android:paddingTop="2dp" android:paddingBottom="2dp" android:gravity="center" android:layout_alignParentBottom="true" android:visibility="gone" /&gt; &lt;/RelativeLayout&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior" android:padding="8dp" android:id="@+id/nested_scrollView"&gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXT" android:id="@+id/name" android:textSize="@dimen/abc_text_size_headline_material" android:textColor="@color/abc_primary_text_material_light" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXT" android:id="@+id/othernames" android:layout_below="@+id/name" android:textSize="@dimen/abc_text_size_subhead_material" android:textColor="@color/secondary_text_default_material_light" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="first" android:id="@+id/season_head" android:layout_alignParentBottom="false" android:layout_alignParentLeft="false" android:layout_below="@+id/othernames" android:layout_marginTop="12dp" android:textSize="@dimen/abc_text_size_subhead_material" android:textColor="@color/abc_primary_text_material_light" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="second" android:id="@+id/places_head" android:layout_marginTop="12dp" android:textSize="@dimen/abc_text_size_subhead_material" android:textColor="@color/abc_primary_text_material_light" android:layout_below="@+id/season" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXT" android:id="@+id/season" android:layout_below="@+id/season_head" android:layout_marginTop="@dimen/desc_clauses_margin" android:textSize="@dimen/abc_text_size_body_1_material" android:textIsSelectable="true" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXT" android:id="@+id/places" android:layout_below="@+id/places_head" android:textSize="@dimen/abc_text_size_body_1_material" android:layout_marginTop="@dimen/desc_clauses_margin" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="third" android:id="@+id/description_head" android:textSize="@dimen/abc_text_size_subhead_material" android:textColor="@color/abc_primary_text_material_light" android:layout_below="@+id/places" android:layout_marginTop="12dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXT" android:id="@+id/description" android:layout_below="@+id/description_head" android:textSize="@dimen/abc_text_size_body_1_material" android:layout_marginTop="@dimen/desc_clauses_margin" /&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>I'd want to stop scrolling exactly when the content is over.</p>
2
How to show buy/sell signals of Amibroker on my webpage?
<p>I want to show the buy/sell signals that Amibroker generates on my website. I tried lot of things but I couldn't find a solution. </p> <p>It would be even better if I can stream the charts to the website.</p> <p>The problem is, I don't know how to access the API of Amibroker.(Do they even have it? It is mentioned in their features page, but have not seen any documentation regarding it).</p> <p>Then, I am not sure how would I connect that to my web server.</p>
2
PHP Soap Server without Soap Client
<p>There are several weeks that I'm trying to create a soap server in php that at first serves a wsdl with authentication header on it and at second it accepts only authenticated users in every request. But I' ve only made it fully working only without authentication. Every search I 've made and every solution I 've found contains a SoapClient,Zend_Soap_Client,nu_soap_client (you name it) and either some kind of wrapper class around my class or only addition of username &amp; password on the client. But at my solution only the server is in php and client are various programs written in java etc, <strong>not</strong> in php. Here is my code for (I use <a href="https://github.com/zendframework/zend-soap" rel="nofollow">zend</a> here but the idea is the same on plain php) the wsdl generation and the server part:</p> <pre><code>use Zend\Soap\AutoDiscover as Zend_Soap_AutoDiscover; use Zend\Soap\Server as Zend_Soap_Server; if (isset($_GET['wsdl'])) { $autodiscover = new Zend\Soap\AutoDiscover(); $autodiscover-&gt;setClass('MyClass'); $autodiscover-&gt;setUri('http://Myclass/path/'); $autodiscover-&gt;handle(); exit; } $server = new Zend_Soap_Server(null, array( 'uri' =&gt; 'http://Myclass/path/', )); $server-&gt;setClass('Myclass'); $server-&gt;handle(); </code></pre> <p>I also used <a href="https://github.com/piotrooo/wsdl-creator" rel="nofollow">piotrooo</a>'s wsdl generator and plain php soap library like this:</p> <pre><code>use WSDL\WSDLCreator; // use WSDL\XML\Styles\DocumentLiteralWrapped; if (isset($_GET['wsdl'])) { $wsdl = new WSDL\WSDLCreator('Myclass', 'http://Myclass/path/'); $wsdl-&gt;setNamespace("http://Myclass/path/"); $wsdl-&gt;renderWSDL(); exit; } $server = new SoapServer(null, array( 'uri' =&gt; 'http://Myclass/path/', // 'style' =&gt; SOAP_DOCUMENT, // 'use' =&gt; SOAP_LITERAL, )); $server-&gt;setClass('Myclass'); $server-&gt;handle(); </code></pre> <p>And my class:</p> <pre><code>class Myclass { public function __construct() { /*some db stuff with doctrine*/ } /** * @param string $id * @return object */ public function Id($id) { /*I'm using doctrine to fetch data from db and then return an object/or array*/ } } </code></pre> <p>At last this is the auto generated wsdl:</p> <pre><code>&lt;definitions name="Myclass" targetNamespace="http://Myclass/path/"&gt;&lt;types&gt;&lt;xsd:schema targetNamespace="http://Myclass/path/"/&gt;&lt;/types&gt;&lt;portType name="MyclassPort"&gt;&lt;operation name="Id"&gt;&lt;documentation&gt;Id&lt;/documentation&gt;&lt;input message="tns:IdIn"/&gt;&lt;output message="tns:IdOut"/&gt;&lt;/operation&gt;&lt;/portType&gt;&lt;binding name="MyclassBinding" type="tns:MyclassPort"&gt;&lt;soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/&gt;&lt;operation name="Id"&gt;&lt;soap:operation soapAction="http://Myclass/path/#Id"/&gt;&lt;input&gt;&lt;soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://Myclass/path/"/&gt;&lt;/input&gt;&lt;output&gt;&lt;soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://Myclass/path/"/&gt;&lt;/output&gt;&lt;/operation&gt;&lt;/binding&gt;&lt;service name="MyclassService"&gt;&lt;port name="MyclassPort" binding="tns:MyclassBinding"&gt;&lt;soap:address location="http://Myclass/path/"/&gt;&lt;/port&gt;&lt;/service&gt;&lt;message name="IdIn"&gt;&lt;part name="id" type="xsd:string"/&gt;&lt;/message&gt;&lt;message name="IdOut"&gt;&lt;part name="return" type="xsd:struct"/&gt;&lt;/message&gt;&lt;/definitions&gt; </code></pre> <p>Annotations vary on each generator. I also tried nusoap but I was disappointed because of it's pure class method discovery. I must add that I'm testing usage of service with soapui (that's why I don't want php's SoapClient or equivalent examples). Last I also must say that I tried solutions of adding authentication method inside my class and this worked <strong><em>BUT</em></strong> this didn't prevent unauthenticated user from accessing ws.</p> <p>A little extra information. As of my research every answer I was found was about SOAPClient for example the $client->__addheader() function etc. Please tell me if I' m wrong or if this can't be done with PHP because I ll have to find someone else to do this for me with another programming language like Java etc.</p> <p>Thanks in advance</p> <p>Dimitris</p>
2
How to can I use custom headers from CloudFront in Apache virtualhost
<p>I have been given a task that I am not really sure how to handle. What I am requested to do is add a custom header to CloudFront and make Apache use this custom header to serve the site. I also need a fallback to normal use when the header is not set. </p> <p>I have my main website: <strong>www.domain.com</strong> that is setup on CloudFront with the origin set to <strong>prod.domain.com</strong>. The site is setup on the server as <strong>www.domain.com</strong> (this cannot be changed)</p> <p>What I want to do is set a custom header in CloudFront that will define the site name and use this header in my virtualhost to load the correct site.</p> <p>For sake of example, I have added the header: <strong>company-host-name</strong> and set the value to <strong>www.domain.com</strong>. CloudFront origin is <strong>prod.domain.com</strong> and have updated the DNS to point to the server IP for this new domain. So far so good but this is now trying to load the <strong>prod.domain.com</strong> from the server. </p> <p>What I want to do is use the custom header to load the site instead of the default way Apache handles this. Although I still need the fallback if no header is set. I think simply setting this header to the HOST header should suffice.</p> <p>My Server Specs:</p> <pre><code># cat /etc/centos-release CentOS release 6.8 (Final) # httpd -v Server version: Apache/2.2.15 (Unix) Server built: May 11 2016 19:28:33 </code></pre> <p>I will need to know how to do this in Apache 2.4 also but for now 2.2 is essential.</p> <p>I have tried playing with the headers and added this to my <code>http.conf</code></p> <pre><code>&lt;IfModule mod_headers.c&gt; &lt;IfDefine company_host_name&gt; Header set Host "%{company_host_name}e" &lt;/IfDefine&gt; &lt;/ifModule&gt; </code></pre> <p>I was hoping to override the Host header with the custom header value. I think this should suffice but I cannot seem to get this to work.</p> <p>Perhaps I am over-complicating it and need to take a step back. So I am here asking for help on something I didn't think would be too difficult.</p> <p>Thanks for any help you can provide.</p> <p><strong>Virtualhost</strong></p> <pre><code>&lt;VirtualHost *:80&gt; ServerName www.domain.com ServerAlias prod.domain.com RequestHeader set Host "www.domain.com" DocumentRoot /var/www/vhosts/domain.com/public_html &lt;Directory /var/www/vhosts/domain.com/public_html&gt; Options -Indexes +FollowSymLinks -MultiViews AllowOverride All &lt;/Directory&gt; ErrorLog /var/www/vhosts/domain.com/logs/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/www/vhosts/domain.com/logs/access.log combined &lt;IfModule mod_php5.c&gt; php_value error_log /var/www/vhosts/domain.com/logs/php_error.log php_value newrelic.appname "domain.com - PHP" &lt;/IfModule&gt; &lt;IfModule mod_headers.c&gt; Header set Access-Control-Allow-Origin "*" &lt;/IfModule&gt; #INCLUDES &lt;/VirtualHost&gt; </code></pre>
2
Adjusting PKG_CONFIG_PATH does not work
<p>I am having problems with installing a package that depends on another package - <code>poppler-glib</code>. I have <code>poppler-glib</code> (newest version) installed with the prefix <code>/home/user/local/poppler-glib</code> with <code>*.pc</code> files present in <code>/home/user/local/poppler-glib/lib/pkgconfig</code>. I have added that path to the <code>PKG_CONFIG_PATH</code> variable (I am on <code>tcsh</code>):</p> <pre><code>setenv PKG_CONFIG_PATH /home/user/local/poppler-glib/lib/pkgconfig </code></pre> <p>Nevertheless, when I try to run the <code>./configure</code> script of the other package, I am getting the following error:</p> <pre><code>configure: error: Package requirements (poppler-glib &gt;= 0.5.4) were not met: No package 'poppler-glib' found Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables POPPLERGLIB_CFLAGS and POPPLERGLIB_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. </code></pre> <p>Therefore, question: how can I adjust the <code>PKG_CONFIG_PATH</code> variable to make it visible?</p>
2
Storing large amount of data into Core Data
<p>I'm loading a large amount of data in JSON format (more than 2000 entities) into Core Data whenever user refreshes the page. What I'm doing right now works fine but just time consuming. I was considering to use some kind of pagination, but that needs backend modifications. Hopefully someone could help me to optimize the process. Or point me to another solution of storing large amount of data in iOS.</p> <p>Here is the part that cost most of the time:</p> <pre><code>[moc performBlock:^{ for (NSDictionary *dictionary in dataObjectsArray) { NSPredicate *predicate = [ObjectA predicateWithDictionary:dictionary]; NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:ENTITY_NAME]; request.predicate = predicate; NSError *error; NSArray *fetchedObjects = [moc executeFetchRequest:request error:&amp;error]; ObjectA *objectATemp = (ObjectA *)[fetchedObjects lastObject]; if (!objectATemp) { NSEntityDescription *entityDescription = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:moc]; objectATemp = [[ObjectA alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:moc]; } [ObjectA setObjectA:objectATemp dictionary:dictionary]; // check if user already liked the ObjectA ObjectB *likedObject = [ObjectB objectBWithId:objectATemp.id]; if (likedObject &amp;&amp; !objectATemp.user_liked.boolValue) { [likedObject.managedObjectContext deleteObject:likedObject]; } } NSError *error; if ([moc hasChanges] &amp;&amp; ![moc save:&amp;error]) { NSLog(@"%@", error); } // saving Context NSManagedObjectContext *managedObjectContext = [self newManagedObjectContext]; [managedObjectContext performBlock:^{ NSError *error; if ([managedObjectContext hasChanges] &amp;&amp; ![managedObjectContext save:&amp;error]) { NSLog(@"%@", error); } if (completionHandler) { completionHandler(); } }]; }]; </code></pre> <p>Any advise is pleased.</p>
2
UITableView - Table Header View leaves spacing if view is removed
<p>I have a UITableViewController that will display a table view header (NOT section header) if certain criteria is met. Displaying the controller with or without the header view on load works just fine. But if I show the header, then remove it, the spacing (where the header's frame was) remains at the top of the table view every time.</p> <p>I have tried every combination of the following when removing the table view header with no luck:</p> <pre><code>[self.tableView beginUpdates]; self.tableView.tableHeaderView = nil; self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero]; [self.tableView reloadData]; [self.tableView endUpdates]; </code></pre> <p>Anyone else encountered this?</p> <p><strong>Table View Header code:</strong></p> <pre><code>- (void)updateTableHeaderView { if (self.alerts.count &amp;&amp; self.isViewLoaded) { [self.tableView beginUpdates]; UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), 40.0f)]; headerView.preservesSuperviewLayoutMargins = YES; self.tableView.tableHeaderView = headerView; UIButton *alertButton = [UIButton buttonWithType:UIButtonTypeCustom]; alertButton.tintColor = [UIColor whiteColor]; alertButton.translatesAutoresizingMaskIntoConstraints = NO; [alertButton setBackgroundImage:[UIImage imageWithColor:alertTintColor] forState:UIControlStateNormal]; [alertButton setBackgroundImage:[UIImage imageWithColor:alertHighlightedTintColor] forState:UIControlStateHighlighted]; [alertButton addTarget:self action:@selector(alertButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; [headerView addSubview:alertButton]; NSDictionary *views = NSDictionaryOfVariableBindings(alertButton); NSDictionary *metrics = nil; [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[alertButton]|" options:0 metrics:metrics views:views]]; [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[alertButton]|" options:0 metrics:metrics views:views]]; [self.tableView endUpdates]; } else if (self.isViewLoaded) { [self.tableView beginUpdates]; self.tableView.tableHeaderView = nil; [self.tableView endUpdates]; } } </code></pre>
2
Reset the rank in hive
<p>I want to partition the data as given below. But as given in the <a href="http://thehobt.blogspot.in/2009/02/rownumber-rank-and-denserank.html" rel="nofollow">link</a> there is no in built function which reset the Rank again staring from 1. I have tried <code>ROW_NUMBER(), RANK(), DENSE_RANK()</code>. So, can anyone tell me how to achieve this? </p> <pre><code> Col1 Col2 Rank cookie1 ABC 1 cookie1 ABC 1 cookie1 EFG 2 cookie1 EFG 2 cookie1 IJK 3 cookie1 IJK 3 cookie2 XYZ 1 cookie2 XYZ 1 cookie2 LMN 2 </code></pre>
2
Unable to read input DOM element's value
<p>i have following html/JS code :</p> <pre><code>function controller() { document.write(document.getElementById("name").value) ; document.write(document.getElementById("id").value) ; } </code></pre> <pre><code>&lt;input type="text" id="name"/&gt; &lt;input type="text" id="id"/&gt; &lt;input type="button" id="push" onclick="controller()"/&gt; </code></pre> <p><strong>Problem</strong> : when i click on push button <code>onclick</code> is fired and <code>controller</code> function is executed and i am able to retrieve value of element having id <code>name</code> but the second element having id <code>id</code>is not read and as a result i get the following error for second input element :</p> <blockquote> <p>Uncaught TypeError: Cannot read property 'value' of null</p> </blockquote> <p>I have been struggling for hours but i am unable to understand where i am making mistake can somebody help ?</p>
2
How to force PHP to take the correct php.ini?
<p>I have two PHP versions on a Windows Server -- <code>v5</code> and <code>v7</code>. The problem is, that PHP 7 tries to use the <code>php.ini</code> of PHP 5:</p> <pre><code>$ php -v PHP 7.0.2 (cli) (built: Jan 6 2016 12:59:59) ( NTS ) Copyright (c) 1997-2015 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies $ php --ini Configuration File (php.ini) Path: C:\Windows Loaded Configuration File: D:\path\to\php5\php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none) </code></pre> <p><strong>How to set the correct <code>php.ini</code> for PHP 7?</strong></p>
2
How to Stop FCM Notification in Android?
<p>I am facing a problem in FCM. I had added FCM in my Android application through the server API. Now I want to stop the notification messages on a single device. This privilege is in the hands of the user who use my app. But I don't know how to do this.</p> <p>Thanks in Advance.</p>
2
How to set password for SQL Server DB
<p>How do I set up a database so that one does not have access to it? Even with installing SQL Server Management Studio on local machine.</p> <p>In SQL Server with Windows user or <code>sa</code> can access all databases. How do you limit the access DB of the users?</p> <p>For assuming that SQL Server is installed on the local machine, not on the server</p>
2
Can I resume a Maven lifecycle from an arbritrary phase?
<p>I would like to convince Maven to "continue where it left off". I first do a <code>mvn package</code> to build the package. At a later time I may want to continue the lifecycle to do the integration test etc. by doing a <code>mvn install</code>. In this case I would prefer Maven not to start the lifecycle all over again from the start, but to actually resume at the first phase after <code>package</code> (i.e. <code>pre-integration-test</code>). Is it possible to start the lifecycle at a phase other than the first one?</p>
2
passing webmethod parameter to another web method
<p>how can we call one web method in another web method using ajax from the first web method i need to call another web method and pass the parameters from the first to second method </p> <pre><code>&lt;script type = "text/javascript"&gt; function GetCityNameArray() { var cities = ['Mumbai', 'Delhi', 'Chennai']; PageMethods.GetCityNameArray(cities, OnSuccessGetCityNameArray); } function OnSuccessGetCityNameArray(response) { for (var i in response) { alert(response[i]); } } &lt;/script&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"&gt; &lt;/asp:ScriptManager&gt; &lt;div&gt; &lt;input type = "button" onclick = "GetCityNameArray()" value = "Get City Name Array" /&gt; &lt;/div&gt; &lt;/form&gt; protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod] public static string[] GetCityNameArray(string[] cities) { return cities; } </code></pre>
2
How to cast float to string with no decimal places
<p>I'm using <code>openpyxl</code> to read values from a spreadsheet. These values are being read as floats, I am not entirely sure why.</p> <pre><code>import openpyxl as opx wb = opx.load_workbook(SKU_WORKBOOK_PATH, use_iterators=True, data_only=True) ws = wb.worksheets[0] for row in ws.iter_rows(): foo = str(int(row[1].internal_value)) </code></pre> <p>This is throwing the error:</p> <pre><code>ValueError: invalid literal for int() with base 10: '6978279.0' </code></pre> <p>Normally, openpyxl reads in integer values as <code>int</code>, but this time it has read it in a float cast as a string. In the spreadsheet, the value of this cell is <code>6978279</code>.</p> <p>I am converting this to the string I want with <code>foo = str(int(float(foo)))</code> which results in <code>'6978279'</code> as intended. I could also do <code>foo = foo[:-2]</code>, but this worries me that another cell, which may be read as an <code>int</code> or with more decimal places, would screw things up.</p> <p>This feels like a terrible, messy way of mashing what I have into what I want. Is there a more pythonic way to do this? Am I reading the <code>xlsx</code> in a way that forces floats? How can I do this without triple casting?</p>
2
Unable to connect with Azure SQL from Azure VM using Site-Site Connectivity
<p>We have created simple classic Azure VM and have Azure SQL.</p> <p>We have an application running on VM and trying to do some operation on Azure SQL, however we are not able to access it and got generic exception</p> <blockquote> <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections</p> </blockquote> <p>We already did list of things:</p> <ol> <li>Added VM's public IP in remote database server</li> <li>Added Endpoints for 1433 TCP thru Azure Dashboard</li> <li>Added Inbound rule for 1433 in VM' Firewall</li> </ol> <p><strong>EDIT</strong></p> <p>For site-to-site VPN, </p> <ol> <li>we linked our database to cloud service of VM</li> <li>traced IP of database, now we are able to telnet IP with 1433 within VM.</li> </ol> <p>But still we are logging below error on logger when trying to interact with database. </p> <blockquote> <p>A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The target principal name is incorrect.</p> </blockquote> <p>Are we missing something here</p>
2
How to dynamic deploy for standalone Spring batch using Spring Cloud Task
<p>We are planning to retire the existing legacy java batch applications and recreate it with the latest available batch framework. Given that we have a large number of batch jobs to be modernised, we are looking for a framework or architecture that would allow us to </p> <ol> <li>Develop a batch solution that would allow us to dynamically deploy a new batch as and when they are created, without disturbing the existing deployed applications. - Does Spring cloud Task provide any of this feature. Note: We are looking only to deploy the apps to our local server, and has nothing to do with cloud.</li> <li>If Spring Batch/Boot can provide us the feature we typically expect from a batch application, what is the special value add to go for Spring Cloud Task? - I wasn't able to completely understand this from the Spring documentation available online.</li> <li>From the documentation of the Spring Cloud Task, I was able to understand that it allows an application to have many tasks within it. What should I do if each of the tasks have their own library dependencies, which might contradict with the dependencies of other Tasks? So in that case, should each of these tasks moved to a new application or this there a work around for that?</li> </ol>
2
Xamarin.forms OnAppLinkRequestReceived
<p>I'm trying to use <a href="https://developer.xamarin.com/api/member/Xamarin.Forms.Application.OnAppLinkRequestReceived/p/System.Uri/" rel="nofollow">https://developer.xamarin.com/api/member/Xamarin.Forms.Application.OnAppLinkRequestReceived/p/System.Uri/</a> but can't seem to get it to be called in any way.</p> <p>Did anyone ever tried to implement this new method? I've tried several ways to implement different deeplinks, all of them open the app fine so they're correctly configured but that method never gets called.</p> <p>Thanks.</p>
2
Firebase realtime database entries expiration
<p>I am trying to remove old entries from Firebase Database automatically. Is it possible to configure Firebase to remove old entries for a specific child ?</p>
2
Using collapse/accordion to make a switchable div
<p>In Bootstrap (v3) is it possible to have two divs which are simply switchable, so one div is shown by default, and a button toggles between the two, so one div is always shown?</p> <p>It feels like "Collapse" and/or "Accordion" should be able to do this but...</p> <p>"Collapse" doesn't allow for parent elements, to switch between the two and...</p> <p>"Accordion" allows all of the panels to be hidden.</p> <p>The same thing can be accomplished with a bit of JQuery but I'm wondering if some use of the data-* attributes may allow me to avoid any JS. Also, I want to use standard Bootstrap classes as much as possible.</p>
2
Laravel phpunit always 404
<p>Environment: PHP 7.0 macOS apache</p> <p>The code is :</p> <pre><code>public function testBasicExample() { $this-&gt;visit('/'); } </code></pre> <p>Run phpunit. The result is:</p> <pre><code>1) ExampleTest::testBasicExample A request to [http://localhost] failed. Received status code [404]. </code></pre> <p>It's always normal when in Chrome.</p>
2
How to call SuperClass delegate method from SubClass delegate method
<p>I have a <code>SuperClass</code> that implements <code>&lt;UIWebViewDelegate&gt;</code>, in this class I implemented the method <code>webView:shouldStartLoadWithRequest:navigationType:</code></p> <pre><code>@interface SuperClass ... - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request1 navigationType:(UIWebViewNavigationType)navigationType { // SuperClass treatment } ... @end </code></pre> <p>Then I have a <code>SubClass</code> that extend this <code>SuperClass</code>. the <code>SubClass</code> implements <code>&lt;UIWebViewDelegate&gt;</code> too, and the method <code>webView:shouldStartLoadWithRequest:navigationType:</code> as well :</p> <pre><code>@interface SubClass: SuperClass ... - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request1 navigationType:(UIWebViewNavigationType)navigationType { // SubClass treatment } ... @end </code></pre> <p>The code works for me, because I need to do a specific treatment for the <code>SubClass</code>. But in a specific case, I need to call the <code>SuperClass</code> <code>webView:shouldStartLoadWithRequest:navigationType:</code> method. </p> <p><strong>I need the delegate to execute the <code>SuperClass</code> <code>UIWebViewDelegate</code> methods.</strong></p> <p>I tried to use <code>super</code> to call the <code>SuperClass</code> method, but with no use!</p> <p>Is that possible?</p>
2
How do I get the objective-c function call graph in a Xcode-prj
<p>I am a rookie to develop a tool to static analysis objective-c file with clang now. And I want to find a way to get the funtion call graph with text (that I can analyze in the program) in the xcode-project but I can't find a good way to do it. How do I get the graph with some tools?Or is it having a way that I can analyze the code with clang that provide for me.</p>
2
Mysql query return empty result in Codeigniter but working fine in native PHP
<p>I can't figure out why my query always return empty result in Codeigniter. The same query is works as expected when run in SQL box in phpmyadmin. </p> <p>My table (users) look something like this: </p> <pre><code>id | name | registration ------------------------------- 1 | John | 2016-06-09 12:00:08 2 | Mike | 2016-06-12 12:45:23 3 | Greg | 2016-06-13 11:50:05 4 | Anthony | 2016-06-14 02:34:08 5 | Adam | 2016-06-14 04:34:18 6 | Steven | 2016-06-15 13:55:34 7 | Joe | 2016-06-16 07:23:45 8 | David | 2016-06-17 06:19:31 9 | Richard | 2016-06-17 11:20:27 10 | Jack | 2016-06-17 12:00:08 </code></pre> <p>and so on. I just want to get a list of all people whose registration date is in the last 7 days. 'registration' column is of DATETIME type </p> <p>Here's my code in CI model using Query Builder. Already autoload database library</p> <pre><code> function get_user() { $query = $this-&gt;db-&gt;select('name') -&gt;where('registration','BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()') -&gt;get('users'); return $query-&gt;result(); } </code></pre> <p>It's return empty result without error. Next I try to put query directly like this</p> <pre><code> function get_user() { $query = $this-&gt;db&gt;query('SELECT name FROM users WHERE registration BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()'); return $query-&gt;result(); } </code></pre> <p>Also return empty result without error. So out of curiosity I tried to run the same query using native PHP outside Codeigniter. Here's the code :</p> <pre><code> &lt;?php $link = mysqli_connect("localhost", "myusername", "mypassword", "mydatabase"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT name FROM users WHERE registration BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()"; $result = mysqli_query($link, $query); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ echo $row["name"]; echo "&lt;br&gt;"; } mysqli_free_result($result); mysqli_close($link); ?&gt; </code></pre> <p>And voila...it works and return result as expected. So any idea what's the problem with Codeigniter in this case? Any input will be appreciated. Thanks all</p>
2
Setting up Vimeo SDK in iOS
<p>Trying to incorporate <a href="https://github.com/vimeo/VIMNetworking" rel="nofollow noreferrer">Vimeo SDK from github</a> into my iOS project. Xcode 7.3.1</p> <p>I have cocoa pods installed and my TestVimeo1 project setup but when I attempt target VIMNetworking, AFNetworking and VIMObjectMapper I must not be going about this correct. </p> <pre><code>ld: warning: directory not found for option '-L/Users/xxxxx/xcodebuild/_buildoutput/TestVimeo1-fktedyrxeulxmicndbpgghnbdjtn/Build/Products/Debug-iphonesimulator/AFNetworking' ld: warning: directory not found for option '-L/Users/xxxxx/xcodebuild/_buildoutput/TestVimeo1-fktedyrxeulxmicndbpgghnbdjtn/Build/Products/Debug-iphonesimulator/VIMNetworking' ld: warning: directory not found for option '-L/Users/xxxxx/xcodebuild/_buildoutput/TestVimeo1-fktedyrxeulxmicndbpgghnbdjtn/Build/Products/Debug-iphonesimulator/VIMObjectMapper' ld: library not found for -lAFNetworking clang: error: linker command failed with exit code 1 (use -v to see invocation) </code></pre> <p>Can't find the output directories. Where am I going wrong with setting up the target builds for these git submodules? Thanks!</p>
2
Getting the device ID/Handle of a mouse with Raw Input
<p>I'm working on using the raw input api to listen for key presses and mouse clicks. So far I have the keyboard presses working, I'm able to get events to fire for such and read which key was pressed. However, I'm having trouble getting the mouse events to work the same way. </p> <p>When the message comes in via <code>WndProc(ref Message)</code>, there's a device handle that doesn't ever match anything from the list of device IDs (keyboards, mice, and HIDs). Moreover, the raw input buffer is empty with all fields being zero.</p> <p>Does anyone have suggestions on how/why this would happen?</p> <p>Note, I've been trying to use: <code>private static extern uint GetRawInputDeviceInfo(IntPtr hDevice, uint command, ref DeviceInfo data, ref uint dataSize);</code> to get any data about the click event's source device, but again the data is also empty/zero.</p> <p>Thanks</p> <p>Edit:</p> <p>On startup I get a list of all devices seen by raw input:</p> <pre><code>var pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount)); GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize); </code></pre> <p>Once I have this list of devices I iterate through them and add them to a separate <code>dictionary&lt;deviceID, eventType&gt;</code>.</p> <p>Later, once I receive a message through <code>WndProc(ref Message)</code>, I grab the identifier under <code>message.LParam</code>, but this doesn't match any device ID in my original list.</p>
2
Kubelet fails to update node status
<p>On latest RHEL Atomic Host (Kubernetes 1.2) we are regularly seeing the following entries in the kubelet logs:</p> <p>kubelet.go:2761] Error updating node status, will retry: nodes "x.y.z" cannot be updated: the object has been modified; please apply your changes to the latest version and try again</p> <p>This causes the node to temporary go to NotReady. During these NotReady periods, the PODs on the node show Ready, but it looks like Kubernetes stops routing traffic to them, causing us a problem.</p> <p>In the Go sources I can see that during the heartbeat of a Kubelet it does a GET to fetch the latest status, overwrites it with its own status, and sends the PUT back to the apiserver.</p> <p>This is what we see in the logs:</p> <p><code>Jul 15 12:42:45 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:42:45.086322 3736 round_trippers.go:264] GET https://lxa160g.srv.pl.ing.net:6443/api/v1/nodes/lxa160j.srv.pl.ing.net Jul 15 12:42:45 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:42:45.091579 3736 round_trippers.go:289] Response Status: 200 OK in 5 milliseconds Jul 15 12:42:45 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:42:45.373091 3736 round_trippers.go:264] PUT https://lxa160g.srv.pl.ing.net:6443/api/v1/nodes/lxa160j.srv.pl.ing.net/status Jul 15 12:42:45 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:42:45.409752 3736 round_trippers.go:289] Response Status: 200 OK in 36 milliseconds Jul 15 12:42:55 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:42:55.411267 3736 round_trippers.go:264] GET https://lxa160g.srv.pl.ing.net:6443/api/v1/nodes/lxa160j.srv.pl.ing.net Jul 15 12:42:55 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:42:55.431056 3736 round_trippers.go:289] Response Status: 200 OK in 19 milliseconds Jul 15 12:43:38 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:43:38.020203 3736 round_trippers.go:264] PUT https://lxa160g.srv.pl.ing.net:6443/api/v1/nodes/lxa160j.srv.pl.ing.net/status Jul 15 12:43:38 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:43:38.029575 3736 round_trippers.go:289] Response Status: 409 Conflict in 9 milliseconds Jul 15 12:43:38 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:43:38.029772 3736 round_trippers.go:264] GET https://lxa160g.srv.pl.ing.net:6443/api/v1/nodes/lxa160j.srv.pl.ing.net Jul 15 12:43:38 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:43:38.034980 3736 round_trippers.go:289] Response Status: 200 OK in 5 milliseconds Jul 15 12:43:38 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:43:38.298752 3736 round_trippers.go:264] PUT https://lxa160g.srv.pl.ing.net:6443/api/v1/nodes/lxa160j.srv.pl.ing.net/status Jul 15 12:43:38 lxa160j.srv.pl.ing.net kubelet[3736]: I0715 12:43:38.320192 3736 round_trippers.go:289] Response Status: 200 OK in 21 milliseconds</code></p> <p>So it takes a long time to fire a PUT after a successful GET. Why?</p> <p>Thanks</p>
2
Error starting application in .netcore
<p>I'm getting the following error when navigating to my IIS published .netcore application:</p> <p><a href="https://i.stack.imgur.com/1444a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1444a.png" alt="enter image description here"></a></p> <p>I have set up my web.config file as so:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;!-- Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380 --&gt; &lt;system.webServer&gt; &lt;handlers&gt; &lt;add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" /&gt; &lt;/handlers&gt; &lt;aspNetCore processPath="dotnet" arguments=".\KritnerWebsite.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" /&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Not sure if this warning is relevant or just outdated:</p> <blockquote> <p>Severity Code Description Project File Line Source Suppression State Warning The element 'system.webServer' has invalid child element 'aspNetCore'. List of possible elements expected: 'asp, caching, cgi, defaultDocument, directoryBrowse, globalModules, handlers, httpCompression, webSocket, httpErrors, httpLogging, httpProtocol, httpRedirect, httpTracing, isapiFilters, modules, applicationInitialization, odbcLogging, security, serverRuntime, serverSideInclude, staticContent, tracing, urlCompression, validation, management, rewrite'. KritnerWebsite D:\gitWorkspace\KritnerWebsite\src\KritnerWebsite\web.config 12 Build </p> </blockquote> <p>The line in the web.config was as per the template, I just changed "false" to "true" for <code>stdoutLogEnabled</code>. </p> <p>I have also created an empty folder in the root directory "logs" - I wasn't sure if this should get created automatically or not. Either way, nothing is being written to the logs, so I am not sure what to try next.</p> <p>I have opened the solution in VS2015 on my host, compiled it and ran it successfully through commandline/localhost with <code>dotnet run</code>. This is running it in the production configuration, so pulling from my environment variables for insights key, and connection string. So I'm not sure why the site would run successfully on my host through <code>dotnet run</code> but not when published to IIS</p> <p>How do I get further information on what the error is?</p>
2
Chrome puts everything HTML tag between HEAD and BODY into BODY
<p>So my code goes something like</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;header&gt; something &lt;/header&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and whenever I load this in chrome, chrome puts the header tag inside the body tag which is frustrating me. I tried this in Safari and the source shows to be fine, as I intended so. </p> <p>Why is chrome doing this?</p>
2
Foreign Key Constraint Failed in Sqlite3
<p>I'm executing this script for the second time(these tables exist previously) and am getting a Foreign Key Constraint Failed error. I'm a beginner in Sqlite3 and am not able to figure out the cause behind it. </p> <p>Schema.sql </p> <pre><code>PRAGMA foreign_keys = 1; drop table if exists user; create table user(uid integer primary key autoincrement, username text not null, password text not null, email text not null, isadmin integer default 0); drop table if exists asset; create table asset(aid integer primary key autoincrement, assetname text not null, releasedate text, owner integer default 0, isreserved integer default 0, foreign key(owner) references user(uid) on delete set default); </code></pre> <p>I'm reading this file in a Python script.</p> <p>Error: </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "main.py", line 37, in create_table conn.cursor().executescript(f.read()) sqlite3.IntegrityError: foreign key constraint failed </code></pre>
2
How to optimize performance when repeatedly looping over a big list of objects
<p>I have a simple file that contains two integer values per line (a source integer and a target integer). Each line represents a relation between two values. The file is not sorted and the actual file contains about 4 million lines. After sorting it may look like this:</p> <pre><code>sourceId;targetId 1;5 2;3 4;7 7;4 8;7 9;5 </code></pre> <p>My goal is to create a new object that will represent all unique related integers in a list with a unique identifier. The expected output of this example should be the following three objects:</p> <pre><code>0, [1, 5, 9] 1, [2, 3] 2, [4, 7, 8] </code></pre> <p>So groupId 0 contains a group of relations (1, 5 and 9).</p> <p>Below is my current way to create a list of these objects. The list of Relation objects contains all the lines in memory. And the list of GroupedRelation should be the end result.</p> <pre><code>public class GroupedRelationBuilder { private List&lt;Relation&gt; relations; private List&lt;GroupedRelation&gt; groupedRelations; private List&lt;String&gt; ids; private int frameId; public void build() { relations = new ArrayList&lt;&gt;(); relations.add(new Relation(1, 5)); relations.add(new Relation(4, 7)); relations.add(new Relation(8, 7)); relations.add(new Relation(7, 4)); relations.add(new Relation(9, 5)); relations.add(new Relation(2, 3)); // sort relations.sort(Comparator.comparing(Relation::getSource).thenComparing(Relation::getTarget)); // build the groupedRelations groupId = 0; groupedRelations = new ArrayList&lt;&gt;(); for (int i = 0; relations.size() &gt; 0;) { ids = new ArrayList&lt;&gt;(); int compareSource = relations.get(i).getSource(); int compareTarget = relations.get(i).getTarget(); ids.add(Integer.toString(compareSource)); ids.add(Integer.toString(compareTarget)); relations.remove(i); for (int j = 0; j &lt; relations.size(); j++) { int source = relations.get(j).getSource(); int target = relations.get(j).getTarget(); if ((source == compareSource || source == compareTarget) &amp;&amp; !ids.contains(Integer.toString(target))) { ids.add(Integer.toString(target)); relations.remove(j); continue; } if ((target == compareSource || target == compareTarget) &amp;&amp; !ids.contains(Integer.toString(source))) { ids.add(Integer.toString(source)); relations.remove(j); continue; } } if (relations.size() &gt; 0) { groupedRelations.add(new GroupedRelation(groupId++, ids)); } } } class GroupedRelation { private int groupId; private List&lt;String&gt; relatedIds; public GroupedRelation(int groupId, List&lt;String&gt; relations) { this.groupId = groupId; this.relatedIds = relations; } public int getGroupId() { return groupId; } public List&lt;String&gt; getRelatedIds() { return relatedIds; } } class Relation { private int source; private int target; public Relation(int source, int target) { this.source = source; this.target = target; } public int getSource() { return source; } public void setSource(int source) { this.source = source; } public int getTarget() { return target; } public void setTarget(int target) { this.target = target; } } } </code></pre> <p>When I run this small example program, it takes 15 seconds to create 1000 GroupedRelation objects. To create 1 million GroupedRelation it would take 250 minutes.. </p> <p>I am looking for help in optimizing my code that does get the result I want but simply takes to long.</p> <p><strong>Is it possible to optimize the iteration in such a way that the expected result is the same but the time it takes to get the expected result is reduced significantly? If this is possible, how would you go about it?</strong></p>
2
CSS Navbar hover full height
<p>So I am new in this HTML thing and I am experimenting with a navigation bar. With when I hover over a li/a element I get another color for the full height of the navigation bar.</p> <p><a href="http://i.stack.imgur.com/GpYPK.png" rel="nofollow">This is what I get first</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>body{ margin: 0px; padding: 0px; } .header{ width: 100%; height: 55px; background-color: #ecf0f1; text-align: right; overflow: hidden; } .navbar ul{ } .navbar ul li{ list-style-type: none; display: inline-block; text-align: center; height: 100%; } .navbar ul li a{ text-decoration: none; color: black; font-family: 'Franklin Gothic'; padding: 50px; height: 100%; } .navbar ul li:hover{ background-color: #bdc3c7; }</code></pre> </div> </div> </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;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;HTML&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="style/style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="header"&gt; &lt;div class="navbar"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>And then I changed a few things in the code and came up with this (<a href="http://i.stack.imgur.com/9viEL.png" rel="nofollow">Here is the second experiment result</a>) (erasing <code>overflow:hidden;</code> and changed it with <code>line-height:55px;</code>)</p> <p>I got the full height hover but there's a white gap between the browser window and my navigation bar.</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>body{ margin: 0px; padding: 0px; } .header{ width: 100%; height: 55px; background-color: #ecf0f1; text-align: right; line-height: 55px; } .navbar ul{ } .navbar ul li{ list-style-type: none; display: inline-block; text-align: center; height: 100%; } .navbar ul li a{ text-decoration: none; color: black; font-family: 'Franklin Gothic'; padding: 50px; height: 100%; } .navbar ul li:hover{ background-color: #bdc3c7; }</code></pre> </div> </div> </p> <p>I know there's a bunch of similar questions like mine and I've read them before asking here, but I still don't get the result that I want.</p>
2
There was something wrong with my password. I got an error when installing phpMyAdmin
<p>The error is shown as a screenshot by clicking the link: <a href="http://i.stack.imgur.com/qDlLe.png" rel="nofollow">The error box</a></p> <p>What can I do?</p> <p>The error in text is:</p> <blockquote> <p>An error occurred while installing the database:<br> mysql said: mysql: [Warning] mysql: Empty value for 'port' specified. Will throw an error in future versions ERROR 1819 (HY000) at line 1: Your password does not satisfy the current policy requirements . Your options are: * abort - Causes the operation to fail; you will need to downgrade, reinstall, reconfigure this package, or otherwise manually intervene to continue using it. This will usually also impact your ability to install other packages until the installation failure is resolved. * retry - Prompts once more with all the configuration questions (including ones you may have missed due to the debconf priority setting) and makes another attempt at performing the operation. * retry (skip questions) - Immediately attempts the operation again, skipping all questions. This is normally useful only if you have solved the underlying problem since the time the error occurred. * ignore - Continues the operation ignoring dbconfig-common errors. This will usually leave this package without a functional database. Next step for database installation:</p> </blockquote>
2
Google's Python Course wordcount.py
<p>I am taking Google's Python Course, which uses Python 2.7. I am running 3.5.2. </p> <p>The script functions. This was one of my exercises. </p> <pre><code>#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and complete. It calls print_words() and print_top() functions which you write. 1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. For the --topcount flag, implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ import sys # +++your code here+++ # Define print_words(filename) and print_top(filename) functions. # You could write a helper utility function that reads a fcd ile # and builds and returns a word/count dict for it. # Then print_words() and print_top() can just call the utility function. ### def word_count_dict(filename): """Returns a word/count dict for this filename.""" # Utility used by count() and Topcount(). word_count={} #Map each word to its count input_file=open(filename, 'r') for line in input_file: words=line.split() for word in words: word=word.lower() # Special case if we're seeing this word for the first time. if not word in word_count: word_count[word]=1 else: word_count[word]=word_count[word] + 1 input_file.close() # Not strictly required, but good form. return word_count def print_words(filename): """Prints one per line '&lt;word&gt; &lt;count&gt;' sorted by word for the given file.""" word_count=word_count_dict(filename) words=sorted(word_count.keys()) for word in words: print(word,word_count[word]) def get_count(word_count_tuple): """Returns the count from a dict word/count tuple -- used for custom sort.""" return word_count_tuple[1] def print_top(filename): """Prints the top count listing for the given file.""" word_count=word_count_dict(filename) # Each it is a (word, count) tuple. # Sort the so the big counts are first using key=get_count() to extract count. items=sorted(word_count.items(), key=get_count, reverse=True) # Print the first 20 for item in items[:20]: print(item[0], item[1]) # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(): if len(sys.argv) != 3: print('usage: ./wordcount.py {--count | --topcount} file') sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print ('unknown option: ' + option) sys.exit(1) if __name__ == '__main__': main() </code></pre> <p>Here are my questions that course is not answering:</p> <ol> <li><p>Where is says the following, I am unsure of what the <code>1</code> and <code>+1</code> mean. Does that mean <code>if the word is not in the list, add it to the list? (word_count[word]=1)</code>? And, I don't understand what each part of this means, where it says <code>word_count[word]=word_count[word] + 1</code>.</p> <pre><code> if not word in word_count: word_count[word]=1 else: word_count[word]=word_count[word] + 1 </code></pre></li> <li><p>When it says <code>word_count.keys()</code>, I am not sure what that does other than it calls to the key in the dictionary we defined and loaded keys and values into. I just want to understand why the <code>word_count.keys()</code> is there. </p> <pre><code> words=sorted(word_count.keys()) </code></pre></li> <li><p><code>word_count</code> is redefined in a couple of locations, and I would like to know why instead of creating a new variable name such as <code>word_count1</code>. </p> <pre><code> word_count={} word_count=word_count_dict(filename) ...and also in places outlined in my 1st question. </code></pre></li> <li><p>Does <code>if len(sys.argv) != 3:</code> mean that if my arguments are not 3, or my characters not 3 (e.g. <code>sys.argv[1]</code>, <code>sys.argv[2]</code>, <code>sys.argv[3]</code>?</p></li> </ol> <p>Thank you for your help!</p>
2
Get index of hash with hash key
<p>I have this hash with wins, and I'm sorting it based on how many wins a player has ( making a highscore list). Now I'm getting each value out based on a players id. How do I get the index of the value I got. ( So I can get the highscore placement).</p> <pre><code>#Highscore list. highscore = Hash.new @users.each_with_index do |player, index| playerTotalGames = @finishedgames.where(log_id: player.id) playerTotalWins = playerTotalGames.where(winner: true) highscore[player.id] = playerTotalWins.length.to_i end @highscore = highscore.sort_by{ |k, v| v }.reverse.to_h # Sort highscore list </code></pre>
2
YALMIP outputs "Infeasible" for an easy, feasible SDP
<p>I want to determine whether a given 3x3 matrix is positive-semidefinite or not. To do so, I write the following SDP in YALMIP</p> <pre><code>v=0.2; a=sdpvar(1); b=sdpvar(1); M=[1 a -v/4 ; b 1 0 ; -v/4 0 0.25]; x=sdpvar(1); optimize([M+x*eye(3)&gt;=0],x,sdpsettings('solver','sedumi')) </code></pre> <p>This program gives me the error "Dual infeasible, primal improving direction found". This happens for any value of v in the interval (0,1].</p> <p>Given that this problem is tractable, I diagonalized the matrix directly obtaining that the three eigenvalues are the three roots of the following polynomial</p> <pre><code>16*t^3 - 36*t^2 + (24 - 16*a*b - v^2)*t + (-4 + 4*a*b + v^2) </code></pre> <p>Computing the values of the three roots numerically I see that the three of them are positive for sign(a)=sign(b) (except for a small region in the neighborhood of a,b=+-1), for any value of v. Therefore, the SDP should run without problems and output a negative value of x without further complications.</p> <p>To make things more interesting, I ran the same code with the following matrix</p> <pre><code>M=[1 a v/4 ; b 1 0 ; v/4 0 0.25]; </code></pre> <p>This matrix has the same eigenvalues as the previous one, and in this case the program runs without any issues, confirming that the matrix is indeed positive-semidefinite.</p> <p>I am really curious about the nature of this issue, any help would be really appreciated.</p> <p>EDIT: I also tried the SDPT3 solver, and results are very similar. In fact, the program runs smoothly for the case of +v, but when i put a minus sign I get the following error</p> <pre><code>'Unknown problem in solver (Turn on 'debug' in sdpsettings) (Error using &amp; …' </code></pre> <p>Furthermore, when I add some restrictions to the variables, i.e., I run the following command</p> <pre><code>optimize([total+w*eye(3)&gt;=0,-1&lt;=a&lt;=1,-1&lt;=b&lt;=1],w,sdpsettings('solver','sdpt3')) </code></pre> <p>Then the error turns to an 'Infeasible problem' error.</p>
2
Error:No transport method defined
<p>I need to create an outlook calender event from my application where i am using express js but i am getting an error as [Error:No transport method defined] and after sometime the responde is 200 success after some 1189989 ms</p> <p>But in outlook i couldn't able to see any event</p> <p>so here is what i tried </p> <pre><code> var _ = require('lodash'); var Outlook = require('./outlook.model'); var icalToolkit = require('ical-toolkit'); var nodemailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); //Create a iCal object var builder = icalToolkit.createIcsFileBuilder(); var icsFileContent = builder.toString(); var smtpOptions = { "secureConnection": true, "from": "*****", "host": "smtp-mail.outlook.com", "secureConnection": true, "port": 587, "transportMethod": "SMTP", "auth": { user: '******', pass: '*****' }}; var builder = icalToolkit.createIcsFileBuilder(); builder.events.push({ start: new Date(), end: new Date(), }); var transporter = nodemailer.createTransport(smtpTransport(smtpOptions)); var mailOptions = { from: '******', to: '******', subject: 'Meeting to attend', html: "Anything here", text: "hiiiiiiiiiiiiiiiiii", alternatives: [{ contentType: 'text/calendar; charset="utf-8"; method=REQUEST', content: icsFileContent.toString() }]}; //send mail with defined transport object exports.send = function(req, res) { transporter.sendMail(mailOptions, function(error, info) { if (error) { console.log(error); } else { console.log('Message sent: ' + info.response); } });}; </code></pre> <p>Here is the index.js where the routing is done</p> <pre><code>'use strict'; var express = require('express'); var controller = require('./outlook.controller'); var router = express.Router(); router.get('/', controller.index); router.get('/send', controller.send); router.get('/:id', controller.show); router.post('/', controller.create); router.put('/:id', controller.update); router.patch('/:id', controller.update); router.delete('/:id', controller.destroy); module.exports = router; </code></pre> <p>I dont understand where i am going wrong</p> <p>Any help would be highly appreciated..</p>
2
Function ‘array’ has no IMPLICIT type
<p>Here is my Fortran 90 code:</p> <pre><code>program test implicit none integer*4 nxProjPad, cf, numViews, cc, index, indRad, iv, i real*4 v4, v5, SS nxProjPad=185 numViews=180 v4 = 0. v5 = 0. SS = 0. cf = NINT(nxProjPad/2.) do iv = 1, numViews do i = 1, nxProjPad v4 = v4 + array(index) v5 = v5 + array(indRad) SS = SS + ABS(array(index)) indRad = indRad + 1 index = index + 1 enddo enddo end </code></pre> <p>and I always get the errors:</p> <pre><code>test.f90:19:15: v4 = v4 + array(index) 1 Error: Function ‘array’ at (1) has no IMPLICIT type test.f90:21:15: v5 = v5 + array(indRad) 1 Error: Function ‘array’ at (1) has no IMPLICIT type test.f90:23:14: SS = SS + ABS(array(index)) 1 Error: Function ‘array’ at (1) has no IMPLICIT type </code></pre> <p>I have searched and have seen similar answers but still could not figure my problem. Any suggestion is welcome and thanks in advance!</p>
2
Allow User to edit button text on long click in Android
<p>I want to allow the App users to change the Button text in Android. When User clicks Button, it should do something but when he/she LongClicks the button, an edittext should pop-up &amp; whatever user types into it should get saved as Button Text. So far I have completed following thing.</p> <pre><code>btn1 = (Button) findViewById(R.id.button1); etLabel = (EditText) findViewById(R.id.etName); btn1.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // How to pop-up edittext from here // to allow user change Button name btn1.setText(name); return true; } }); } public void onButtonClick(View view) { switch (view.getId()) { case R.id.button1: // do something else here break; } } </code></pre>
2
How to convert a column of timestamps HH:MM:SS.xxxxxxx to milliseconds?
<p>I have been trying to figure out how to do this in Python for the better part of a week, but not been able to find anyone to specifically answer this question. I have a log file, where every line is a timestamp with an event, as such:</p> <pre><code>HH:MM:SS.xxxxxxx \t Event HH:MM:SS.xxxxxxx \t Event HH:MM:SS.xxxxxxx \t Event ... </code></pre> <p>I have managed to put all this into a list, and figured out how to manipulate that list. What I haven't been able to figure out is how to convert the timestamp (which starts at 0 (well, at one second, really, but roughly 0)) into milliseconds (something I can do in Excel). So every timestamp just represents elapsed time, not an actual o'clock. The seven x's at the end make no sense to me at all, so not sure what they are.</p> <p>Does anyone have a code snippet that I can use to convert this timestamp into milliseconds?</p>
2
Convert to gray 1-bit, alpha 8-bit with ImageMagick
<p>I am trying to convert Android app resources (icons and backgrounds) to the same format material icons are (in order save space and tint them):</p> <p><a href="https://i.stack.imgur.com/C8VId.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C8VId.png" alt="enter image description here"></a></p> <pre><code>$ identify -verbose ic_alarm_black_48dp.png Image: ic_alarm_black_48dp.png Format: PNG (Portable Network Graphics) Mime type: image/png Class: DirectClass Geometry: 192x192+0+0 Units: Undefined Type: Bilevel Base type: Bilevel Endianess: Undefined Colorspace: Gray Depth: 8-bit Channel depth: gray: 1-bit alpha: 8-bit </code></pre> <p>This image has 8-bit depth and 1-bit gray channel depth.</p> <p>Here is a test image I wanted to convert to format above (a shape with shadow on a transparent background):</p> <p><a href="https://i.stack.imgur.com/lvczI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lvczI.png" alt="icon to be converted"></a></p> <pre><code>$ identify -verbose a.png Image: a.png Format: PNG (Portable Network Graphics) Mime type: image/png Class: DirectClass Geometry: 256x256+0+0 Units: Undefined Type: TrueColorAlpha Endianess: Undefined Colorspace: sRGB Depth: 8-bit Channel depth: red: 8-bit green: 8-bit blue: 8-bit alpha: 8-bit </code></pre> <p><strong>I expect to get a 1-bit grayscale image with 8-bit alpha channel.</strong></p> <p>I feel that I need to convert a source image to a 1-bit grayscale image (with all non-transparent pixels set to 1) and apply an extracted alpha mask on top. </p> <p>Convert to 1-bit grayscale </p> <pre><code>`convert a.png -alpha extract -threshold 0 -negate -transparent white a-trans.png` </code></pre> <p>Apply mask on top</p> <pre><code>`convert a-trans.png \( a.png -alpha extract \) -alpha off -compose copy_opacity -composite a-result.png` </code></pre> <p><a href="https://i.stack.imgur.com/EBeOJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EBeOJ.png" alt="expected result"></a></p> <pre><code>$ identify -verbose a-result.png Image: a-result.png Format: PNG (Portable Network Graphics) Mime type: image/png Class: DirectClass Geometry: 256x256+0+0 Units: Undefined Type: Bilevel Base type: Bilevel Endianess: Undefined Colorspace: Gray Depth: 8-bit Channel depth: gray: 1-bit alpha: 8-bit </code></pre> <p>Last image is what I wanted to achieve. Could that conversion be optimized?</p>
2
The resource cannot be found iis
<p>I built a website with vs 2010 with net 4.0, after publishing website into localhost (iis) on my computer, the website starts normally, but after hosting website via remote hosting, it says: </p> <blockquote> <p>Server Error in '/' Application.</p> <p>The resource cannot be found.</p> <p>Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. </p> <p>Requested URL: /index.aspx</p> </blockquote> <p>here is my web.config</p> <pre><code>&lt;configuration&gt; &lt;appSettings&gt; &lt;add key="CrystalImageCleaner-AutoStart" value="true"/&gt; &lt;add key="CrystalImageCleaner-Sleep" value="60000"/&gt; &lt;add key="CrystalImageCleaner-Age" value="120000"/&gt; &lt;/appSettings&gt; &lt;connectionStrings&gt; &lt;add name="koneksi" connectionString="server=85.10.205.173;user id=dataponpes;password=iwakayam;port=3306;database=ponpes"/&gt; &lt;/connectionStrings&gt; &lt;location path="Telerik.Web.UI.WebResource.axd"&gt; &lt;system.web&gt; &lt;httpRuntime executionTimeout="999999" maxRequestLength="2000000000" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true" /&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;security&gt; &lt;requestFiltering&gt; &lt;requestLimits maxAllowedContentLength="2000000000"&gt;&lt;/requestLimits&gt; &lt;/requestFiltering&gt; &lt;/security&gt; &lt;/system.webServer&gt; &lt;/location&gt; &lt;system.web&gt; &lt;httpHandlers&gt; &lt;add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false"/&gt; &lt;add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false"/&gt; &lt;add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false"/&gt; &lt;add verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/&gt; &lt;/httpHandlers&gt; &lt;compilation debug="true"&gt; &lt;assemblies&gt; &lt;add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/&gt; &lt;add assembly="CrystalDecisions.ReportSource, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/&gt; &lt;add assembly="CrystalDecisions.Shared, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/&gt; &lt;add assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/&gt; &lt;add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;modules runAllManagedModulesForAllRequests="true"/&gt; &lt;validation validateIntegratedModeConfiguration="false"/&gt; &lt;handlers&gt; &lt;add name="Telerik_Web_UI_DialogHandler_aspx" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler"/&gt; &lt;add name="Telerik_Web_UI_SpellCheckHandler_axd" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler"/&gt; &lt;add name="Telerik_Web_UI_WebResource_axd" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource"/&gt; &lt;add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/&gt; &lt;/handlers&gt; &lt;defaultDocument&gt; &lt;files&gt; &lt;add value="index.aspx" /&gt; &lt;/files&gt; &lt;/defaultDocument&gt; &lt;/system.webServer&gt; </code></pre> <p></p>
2
Lock Auth0 for android not returning UserProfile on authentication
<p>I'm using Lock for providing Login functionality in my android App to users. </p> <p>Here is my code: private Lock lock;</p> <pre><code>private LocalBroadcastManager broadcastManager; private BroadcastReceiver authenticationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String idToken = intent.getStringExtra("com.auth0.android.lock.extra.IdToken"); String tokenType = intent.getStringExtra("com.auth0.android.lock.extra.TokenType"); Log.i(TAG, "User logged in with " + idToken + " "+ tokenType); } }; //Not sure use of this callback though its not being called anytime. private LockCallback callback = new AuthenticationCallback() { @Override public void onAuthentication(Credentials credentials) { Log.d(TAG, "Authenticated"); } @Override public void onCanceled() { Log.d(TAG, "Authentication cancelled"); } @Override public void onError(LockException error) { Log.d(TAG, "Authentication Error"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Auth0 auth0 = new Auth0(getString(R.string.auth0_clientId), getString(R.string.auth0_domain)); this.lock = Lock.newBuilder(auth0, callback) .build(); broadcastManager = LocalBroadcastManager.getInstance(this); broadcastManager.registerReceiver(authenticationReceiver, new IntentFilter("com.auth0.android.lock.action.Authentication")); startActivity(this.lock.newIntent(this)); } </code></pre> <p>I have following two questions: 1). First of all I don't understand why it needs callback though it doesn't callback even after authentication succeeded. 2). Shouldn't LocalBroadcastManager get response with UserProfile information instead of token information?</p> <p>I'm using Lock version: com.auth0.android:lock:2.0.0-beta.2</p> <p>Is there any better way to do it?</p> <p>Thanks in advance!</p>
2
Backup and restore of Azure sql database using c#
<p>I want to take backup of Azure sql database to my local system and then restore that backup to Azure sql database in c#. Can any body helps me out?Is it possible to do so?</p>
2
Uncaught ReferenceError: require is not defined(anonymous function) @ ng2-translate.ts:2
<p>Getting this error:</p> <pre><code>Uncaught ReferenceError: require is not defined(anonymous function) @ ng2-translate.ts:2 </code></pre> <p>It's the line where I import @anguar/http</p> <pre><code>import {provide} from '@angular/core'; import {Http} from '@angular/http'; </code></pre> <p>Not sure why I would get any error here since I do include the http dependency in the project:</p> <p>package.json:</p> <pre><code> "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/compiler": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", "@angular/http": "^2.0.0-rc.4", "@angular/platform-browser": "2.0.0-rc.4", "@angular/platform-browser-dynamic": "2.0.0-rc.4", "@angular/router": "3.0.0-beta.1", "core-js": "^2.4.0", "es5-shim": "^4.5.9", "es6-shim": "^0.35.1", "ng2-translate": "2.2.2", "reflect-metadata": "0.1.3", "rxjs": "5.0.0-beta.6", "systemjs": "^0.19.31", "zone.js": "^0.6.12" }, </code></pre> <p>index.html</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Focus Anbud&lt;/title&gt; &lt;base href='/'&gt; {{content-for 'head'}} &lt;link rel="icon" type="image/x-icon" href="favicon.ico"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;!-- Loading Spinner --&gt; &lt;link rel="stylesheet" href="assets/css/whirly.css"&gt; &lt;link rel="stylesheet" href="assets/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="assets/css/font-awesome.min.css"&gt; &lt;link rel="stylesheet" href="assets/css/ionicons.min.css"&gt; &lt;!-- Theme --&gt; &lt;link rel="stylesheet" href="assets/css/AdminLTE.min.css"&gt; &lt;link rel="stylesheet" href="assets/css/skins/skin-blue.min.css"&gt; &lt;link rel="stylesheet" href="assets/css/flag-icon.min.css"&gt; &lt;/head&gt; &lt;body class="hold-transition skin-blue sidebar-mini"&gt; &lt;!--&lt;div class="wrapper"&gt;--&gt; &lt;app&gt; &lt;div class="whirly-loader" style="margin-left: 50%; margin-top:20%"&gt;Loading...&lt;/div&gt; &lt;/app&gt; &lt;!--&lt;/div&gt;--&gt; &lt;!-- ./wrapper --&gt; &lt;!-- jQuery 2.1.4 --&gt; &lt;script src="plugins/jQuery/jQuery-2.1.4.min.js"&gt;&lt;/script&gt; &lt;!-- Bootstrap 3.3.6 --&gt; &lt;script src="assets/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;!-- AdminLTE App --&gt; &lt;script src="assets/js/app.js"&gt;&lt;/script&gt; &lt;!-- polyfills for older browsers --&gt; &lt;script src="vendor/core-js/client/shim.min.js"&gt;&lt;/script&gt; &lt;!-- default --&gt; &lt;script src="vendor/zone.js/dist/zone.min.js"&gt;&lt;/script&gt; &lt;script src="vendor/reflect-metadata/Reflect.js"&gt;&lt;/script&gt; &lt;script src="vendor/systemjs/dist/system.src.js"&gt;&lt;/script&gt; &lt;script src="vendor/ng2-translate/ng2-translate.js"&gt;&lt;/script&gt; &lt;script&gt; System.baseURL = '.'; System.import('system-config.js').then(function() { System.import('main'); }).catch(console.error.bind(console)); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
Highcharts Error #13 : Rendering div not found
<p>I'm working with Javascript (Meteor) and trying to implement a Highchart with drilldown. After thoroughly testing the logic part for correctness, I've verified that the data passed onto my Highchart is correct. However, I am getting Error #13 because there seems to be a problem with how I am setting the "renderTo:" field within the "chart:" options in the chart, which currently looks like this:</p> <pre><code>return chart = { chart: { renderTo: 'chart', type: 'bar' }, //other fields </code></pre> <p>In the HTML file, I use this template and invoke it in the body:</p> <pre><code>&lt;template name= "myTemplate"&gt; {{&gt; highchartsHelper chartId="chart" chartWidth="100%" charHeight="100%" chartObject=topGenresChart}} &lt;/template&gt; &lt;body&gt; //other stuff {{&gt; myTemplate}} &lt;/body&gt; </code></pre>
2
Difference between web client and web service?
<p>Recently, I'm developing android app which must be connected to server (retrieve data from database and write data to database). Directly connecting app with database is obviously too risky (considering security) so I have been searching for another solution. To connect with database I have to use web service but I have found tutorial that uses web client and uri, "calls" PHP files on server and retrieves information with them. So, now I'm wondering what is the difference between this approach and web service. Are they both good solutions or one is better?</p> <p>Thank you in advance.</p>
2
Why run ASP.NET Core on .NET Core over .NET on Windows Server
<p>Ever since I heard about <code>ASP.NET Core</code> and <code>.NET Core</code> I have been wondering why you would want to develop an <code>ASP.NET Core web application</code> running on <code>.NET Core</code> over <code>.NET</code> if you are running a Windows server, like <code>Windows Server 2012</code>? I can understand that if you are developing for cross platform for something else like <code>Ubuntu</code> but if you are running a Windows server why would you want to develop going the <code>.NET Core</code> route?</p> <p>What are the benefits (if any)? I feel like I am missing something here? Is it the ideal way to do <code>ASP.NET</code> web development and deployment going forward? When would you want to use the full <code>.NET</code> framework for <code>ASP.NET</code> web development instead of the <code>.NET Core</code> framework?</p> <p>Not everyone is developing for cross platform? I have been developing for Windows servers all my life and have never needed to do anything cross platform. I don't think I will ever develop anything cross platform using .NET - I'll probably use something other than .NET (if I ever go this route).</p> <p>I hope that someone can help clarify my confusion?</p>
2
Is there any way to change default button color of message dialog in uwp?
<p>I just want to change color of default button "OK" in message dialog </p>
2
if listA== [ ] more simplified version
<p>When I type in the following code, PyCharm says "Expression can be further simplified". What is the more simplified version to this statement?</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>if listA == []: return "yes!" </code></pre> </div> </div> </p>
2
How can I get TypeScript to automatically infer the type of the result of a `yield` call?
<p>In the following code example:</p> <pre><code>function* gen() { let v = yield Promise.resolve(0); return v; } </code></pre> <p>The type of <code>v</code> is inferred to be <code>any</code>. I'm wondering if there's a way to get it to infer a different type (say, <code>number</code>) based on contextual clues.</p> <p>I know that in this specific scenario I can use <code>async</code>/<code>await</code> instead, but I'm wondering about the general case (when not working with promises).</p>
2
$(window).focus() not executed properly in Chrome
<p>I want to track clicks on AdSense elements on my page. To achieve that I put the focus on the window object and if it loses focus, I check if the mouse was in the area of the AdSense iFrame. Then i put the focus back on the window again. </p> <p>This works. But in Chrome it works only once. So if I click on an adSense ad (opening in a new tab) and then I click on another one, the event doesn't fire anymore. </p> <p>If I execute $(window).focus() in the console, the onBlur event fires again - but the $(window).focus() executed from within my code doesn't show any effect. I tried it with a Timeout too, without success. </p> <p>Any ideas?</p> <pre><code>trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense"); function trackElements (elementsToTrack) { var isOverElement = false; $(window).focus(); $(elementsToTrack).mouseenter(function(e){ isOverElement = e.currentTarget.id; }); $(elementsToTrack).mouseleave(function(e){ isOverElement = false; }); $(window).blur(function(e){ windowLostBlur(); }); function windowLostBlur () { if (isOverElement) { console.log(isOverElement); $(window).focus(); } }; </code></pre> <p>};</p> <p>Simplified version: <a href="https://jsfiddle.net/327skdns/2/" rel="nofollow">https://jsfiddle.net/327skdns/2/</a></p>
2
MaxPermSize vs MaxMetaspaceSize
<p>I am reading about the difference between PermGen and Metaspace and one of the disadvantages of the former is that there is a fixed size at startup. I do not understand why is it fixed if you have two parameters to tune it:</p> <pre><code>-XX:PermSize -XX:MaxPermSize </code></pre> <p>It seems to me that we can say the same about Metaspace, it is also fixed at startup by MaxMetspaceSize (I know that by default it is unlimited but it seems not a good practice to leave it as such).</p> <p>Am I misunderstanding something? What is the difference between MaxPermSize and MaxMetaspaceSize ?</p>
2
How to get and store parent table id into its child laravel
<p>I have searched alot to find a better way. I already read on <a href="https://laravel.com/docs/5.1/eloquent-relationships#one-to-many" rel="nofollow">Laravel docs</a> that </p> <blockquote> <p>Eloquent will try to match the parent id from the child model to an id on the parent model.</p> </blockquote> <p>I have and <code>Idea</code> and <code>Document</code> tables. And they have 1:M relationship. an <code>Idea</code> can have many documents and a document can only relate to one <code>Idea</code>.</p> <p>I am unable to get parent table id to store.</p> <p><strong>Controller Function:</strong></p> <pre><code>public function storeDocuments(DocumentRequest $request) { if($request-&gt;hasFile('doc_name')) { $filename = $request-&gt;file('doc_name')-&gt;getClientOriginalName(); $moveFile = $request-&gt;file('doc_name')-&gt;move('documents/', $filename); } $doc = new Document(); $doc-&gt;doc_name = $moveFile; $doc-&gt;save(); } </code></pre> <p><strong>Document Model:</strong></p> <pre><code>public function idea() { return $this-&gt;belongsTo('App\Idea'); } </code></pre> <p><strong>Idea Model:</strong></p> <pre><code>public function documents() { return $this-&gt;hasMany('App\Document'); } </code></pre> <p>Please explain the procedure of storing id of parent table into child table.Thanks!</p> <p><strong>Edit:</strong></p> <pre><code>public function storeDocuments(DocumentRequest $request) { if($request-&gt;hasFile('doc_name')) { $filename = $request-&gt;file('doc_name')-&gt;getClientOriginalName(); $moveFile = $request-&gt;file('doc_name')-&gt;move('documents/', $filename); } $doc = new Document(); $doc-&gt;doc_name = $moveFile; $idea = Idea::find(1); //how to get idea_id here??????? $idea-&gt;documents()-&gt;save($doc); return back(); } </code></pre> <p>I am very confused about this relation. working for while now and cant figure out.</p> <p><strong>Idea Schema:</strong></p> <pre><code>public function up() { // Schema::create('ideas', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;integer('user_id')-&gt;unsigned(); $table-&gt;string('idea_title'); $table-&gt;string('idea_info', 150); $table-&gt;string('idea_image'); $table-&gt;string('selection'); $table-&gt;longText('idea_description'); $table-&gt;string('idea_location'); $table-&gt;integer('idea_goal')-&gt;unsigned(); $table-&gt;integer('pledge_amount')-&gt;unsigned(); $table-&gt;string('set_equity')-&gt;nullable(); $table-&gt;boolean('status')-&gt;default(0); $table-&gt;rememberToken(); $table-&gt;timestamps(); $table-&gt;softDeletes(); }); } </code></pre> <p><strong>Document Schema:</strong></p> <pre><code>public function up() { // Schema::create('documents', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;integer('idea_id')-&gt;unsigned(); $table-&gt;string('doc_name'); $table-&gt;rememberToken(); $table-&gt;timestamps(); $table-&gt;softDeletes(); }); } </code></pre>
2
Access First Firebase Node Data in Firebase Query
<p>I have a Firebase database query returning 100 child nodes. Then I put the nodes into a FirebaseRecyclerAdapter so the data is displayed on a recycler view. This is all working fine. Now I need to access the latest element and its Firebase key, but haven't been able to figure it out (should be easy, I must have missed something obvious). How do I get the latest element and its Firebase key in the returned query or adapter?</p> <p>To get the 100 child nodes, I use:</p> <pre><code>Query publishedPostsQuery = mFirebaseDatabase.child("posts").limitToFirst(100); </code></pre> <p>I then populate a Firebase recycler adapter:</p> <pre><code>FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter&lt;Post, PostViewHolder&gt;(Post.class, R.layout.post_items, PostViewHolder.class, postsQuery) { ... }; </code></pre> <p>This adapter is then used in a recycler view.</p> <p>How do I get to the first Post object and its Firebase key through either Query or FirebaseRecyclerAdapter?</p> <p>My firebase database structure looks like:</p> <pre><code>-posts -KLRDgtNht0iSB6RUGGz - author: "author 1" - title: "some post" - detail: "blah blah" -HGze53Sd4RRpFikdIKD - author: "author 2" - title: "great post" - detail: "blah blah blah blah" </code></pre> <p>The version of Firebase I am using is:</p> <pre><code>compile 'com.firebaseui:firebase-ui-database:0.4.0' compile 'com.google.firebase:firebase-database:9.0.2' </code></pre>
2
Getting Empty Response from Google Vision API
<p>I am testing some features of the Google Vision API and getting Empty response for images which I have clicked from my camera(5MP camera). However when I download any image from web for Example, an image of a delivery guy (with the plain background such as white) I get a meaningful response with labels. Both the sets of images are present on my local disk. Below is the code which I have written by taking reference from google's documentation,</p> <pre><code>public class ImageAnalyzer { final static String APPLICATION_NAME ="My_APP/1.0"; final static String IMAGE_PATH = "E:/Vision/SampleImages/IMAG0013.jpg"; final static int maxResults =3; private Vision vision; public ImageAnalyzer(Vision vision){ this.vision=vision; } /** * Connects to the Vision API using Application Default Credentials. */ public static Vision getVisionService() throws IOException, GeneralSecurityException { GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all()); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential) .setApplicationName(APPLICATION_NAME) .build(); } public Map&lt;String, List&lt;String&gt;&gt; labelImage(String imagePath){ final Map&lt;String,List&lt;String&gt;&gt; labels = new HashMap&lt;String, List&lt;String&gt;&gt;(); final Path path = Paths.get(imagePath); try { final byte[] raw = Files.readAllBytes(path); /*final AnnotateImageRequest request =new AnnotateImageRequest().setImage(new Image().encodeContent(raw)) .setFeatures(ImmutableList.of(new Feature().setType("LABEL_DETECTION").setMaxResults(3) , new Feature().setType("LOGO_DETECTION").setMaxResults(3)));*/ AnnotateImageRequest request = new AnnotateImageRequest() .setImage(new Image().encodeContent(raw)).setFeatures(ImmutableList.of( new Feature() .setType("LABEL_DETECTION") .setMaxResults(maxResults), new Feature() .setType("LOGO_DETECTION") .setMaxResults(1), new Feature() .setType("TEXT_DETECTION") .setMaxResults(maxResults), new Feature() .setType("LANDMARK_DETECTION") .setMaxResults(1))); final Vision.Images.Annotate annotate = vision.images().annotate( new BatchAnnotateImagesRequest(). setRequests(ImmutableList.of(request))); final BatchAnnotateImagesResponse batchResponse = annotate.execute(); //assert batchResponse.getResponses().size() == 1; System.out.println("Size of searches"+batchResponse.getResponses().size()); //final AnnotateImageResponse response = batchResponse.getResponses().get(0); if (batchResponse.getResponses().get(0).getLabelAnnotations() != null) { final List&lt;String&gt; label = new ArrayList&lt;String&gt;(); for (EntityAnnotation ea: batchResponse.getResponses().get(0).getLabelAnnotations()) { label.add(ea.getDescription()); } labels.put("LABEL_ANNOTATION", label); } if (batchResponse.getResponses().get(0).getLandmarkAnnotations() != null) { final List&lt;String&gt; landMark = new ArrayList&lt;String&gt;(); for (EntityAnnotation ea : batchResponse.getResponses().get(0).getLandmarkAnnotations()) { landMark.add(ea.getDescription()); } labels.put("LANDMARK_ANNOTATION", landMark); } if (batchResponse.getResponses().get(0).getLogoAnnotations() != null) { final List&lt;String&gt; logo = new ArrayList&lt;String&gt;(); for (EntityAnnotation ea : batchResponse.getResponses().get(0).getLogoAnnotations()) { logo.add(ea.getDescription()); } labels.put("LOGO_ANNOTATION", logo); } if (batchResponse.getResponses().get(0).getTextAnnotations() != null) { List&lt;String&gt; text = new ArrayList&lt;String&gt;(); for (EntityAnnotation ea : batchResponse.getResponses().get(0).getTextAnnotations()) { text.add(ea.getDescription()); } labels.put("TEXT_ANNOTATION", text); } return labels; } catch (IOException e) { e.printStackTrace(); } return null; } public static void printAnnotations(final List&lt;EntityAnnotation&gt; entityAnnotations) { if(entityAnnotations!=null &amp;&amp; !entityAnnotations.isEmpty()) { for (final EntityAnnotation entityAnnotation : entityAnnotations) { final String desc = entityAnnotation.getDescription(); final Float score = entityAnnotation.getScore(); System.out.println(desc+" "+score); } } } public static void main(String[] args) throws IOException, GeneralSecurityException { // TODO Auto-generated method stub final ImageAnalyzer analyzer = new ImageAnalyzer(getVisionService()); final Map&lt;String, List&lt;String&gt;&gt; labels = analyzer.labelImage(IMAGE_PATH); for (Entry&lt;String, List&lt;String&gt;&gt; entry : labels.entrySet()) { final String key = entry.getKey(); final List&lt;String&gt; value = entry.getValue(); if(value!=null &amp;&amp; !value.isEmpty()) { System.out.println("Printing for key"+key); for (final String myLebel : value) { System.out.println(" "+myLebel); } } } //System.out.println(System.getenv("GOOGLE_APPLICATION_CREDENTIALS")) } </code></pre> <p>}</p> <p>Can anyone help me out?</p>
2
YouTube is not working after V10.45 version in Android 4.4.2
<p>I have Amlogic s802 TVbox which have Android 4.4.2. I'm using latest version of YouTube app from Playstore and its not working while downgrading YouTube to V10.45 its working fine.</p> <p>I have another Amlogic s802 development which have 4.4.2 and inside that latest YouTube app is working fine with no issue. </p> <p>while comparing with both board's logs, I continuously got below error message and there is no <strong>android.hardware.ICameraService</strong> service in TVbox.</p> <blockquote> <p>"I/ServiceManager( 3079): Waiting for service media.camera..."</p> </blockquote> <p>So, my question is: </p> <p>Does the TVbox require <strong>android.hardware.ICameraService</strong> service to run latest version of YouTube?</p>
2
How to dynamically connect to databases in Sails.js
<p>I am rebuilding a legacy PHP application using nodejs and I choose sailsjs after about a week of exploration. Everything was fine until I realised that in sails you only have access to session variables in your controllers. Thus, I cannot make dynamic connections with the model. </p> <p>The legacy app uses PHP session global variables to connect to different postgresql databases after authentication and I can't seem to find a work around on the web. I have seen similar questions on sails around the web. Any node/sails/database geeks around?</p> <p>I am thinking of using sails for authentication since it already works and using expressjs to implement services that my sails app would then call by sending db connection params in some form of microservice architecture. </p> <p>Currenttly running sails on localhost:1337 and my express on localhost:3000. Is this a good way to go about? </p>
2
Load DB data(to Rest API) through postman
<p>We have been using postman for our Rest API testing but to make it more of an e2e data driven tool, we have a requirement to: - Make postman grab data from our database and feed it to the API calls - Run some api calls based on that data - Query DB again to check the sanity of the data after REST POST requests for example</p> <p>I know postman is for client side interactions. Is there a way to make postman to talk to DB somehow? I have came across "<a href="https://www.npmjs.com/package/volos-mysql#database-connection-profile" rel="nofollow">volos-mysql</a>" and "<a href="http://blog.dreamfactory.com/add-a-rest-api-to-any-sql-db-in-minutes" rel="nofollow">dreamFactory</a>" but problem is how to load an external module inside postman script?</p>
2
How to convert AngularJS scope object into simple JS array?
<p>How to convert AngularJS scope object into simple JS array?</p> <p>This function checks if any checkbox is checked and adds corresponding value to an object. Now I want to transfer the object values to an array and alert it after press the button. But the result is undefined, why?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var formApp = angular.module('formApp', []) .controller('formController', function($scope) { // we will store our form data in this object $scope.formData = {}; }); var array = Object.keys(formData).map(function(k) { return obj[k] }); function test(){ alert(array); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;-- index.html --&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!-- CSS --&gt; &lt;!-- load up bootstrap and add some spacing --&gt; &lt;link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"&gt; &lt;style&gt; body { padding-top:50px; } form { margin-bottom:50px; } &lt;/style&gt; &lt;!-- JS --&gt; &lt;!-- load up angular and our custom script --&gt; &lt;script src="http://code.angularjs.org/1.2.13/angular.js"&gt;&lt;/script&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;!-- apply our angular app and controller --&gt; &lt;body ng-app="formApp" ng-controller="formController"&gt; &lt;div class="col-xs-12 col-sm-10 col-sm-offset-1"&gt; &lt;h2&gt;Angular Checkboxes &lt;/h2&gt; ... &lt;!-- MULTIPLE CHECKBOXES --&gt; &lt;label&gt;Favorite Colors&lt;/label&gt; &lt;div class="form-group"&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red"&gt; Red &lt;/label&gt;&lt;br&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.blue"&gt; Blue &lt;/label&gt; &lt;br&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.green"&gt; Green &lt;/label&gt; &lt;/div&gt; ... &lt;!-- SHOW OFF OUR FORMDATA OBJECT --&gt; &lt;h2&gt;formData_object_is_not_empty-test&lt;/h2&gt; &lt;pre&gt; {{formData}} &lt;/pre&gt; &lt;button onclick="test()"&gt;Click me&lt;/button&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
2
Firebase database rule - How to check if login already exists?
<p>I have read a lot of topics and search around but still have problems with the followings:</p> <p>The structure of my database:</p> <pre><code>users -userKEY login: value password: value </code></pre> <p>Firebase rules:</p> <pre><code>{ "rules": { ".read": "true", "users": { "$uid": { ".write": "true", ".validate": "root.child('users').child('login').val() != newData.child('login').val()" } } } } </code></pre> <p>I guess <code>root.child('users').child('login')</code> is probably wrong, but still don't know how.</p> <p><strong>I would like to iterate through all rows of <code>users</code> and check whether the login value of <code>newData.child('login').val()</code> has been used.</strong></p>
2
How do you create public extensions, in a shared framework, for XCTest?
<p>For example, I never use the description of <code>XCTestCase.expectation</code>, so I'd like to use a function to provide a default for it, and make it clear via naming that I'm initializing the expectation, as you can't really use an initializer for <code>XCTestExpectation</code>. But if the extension is not in a test target, then it can't compile:</p> <blockquote> <p>Cannot load underlying module for 'XCTest'</p> </blockquote> <pre><code>import XCTest public extension XCTestCase { func makeExpectation() -&gt; XCTestExpectation { return expectation(withDescription: "") } } </code></pre>
2
Amazon AWS - Upload files to multiple instances under single LB
<p>I need to upload the updated files into multiple ec2 instace which is under single LB. My problem is I missed some ec2 instance and it broke my webpage. Is there any tool available to upload the multiple files to multiple EC2 windows server in a single click. </p> <p>I will update my files weekly or some times daily. I checked with Elastic beanstalk , Amazon Code Deploy and Amazon EFS. But the are hard to use. Anyone please help</p>
2
How to keep a session authenticated while crawling with scrapy?
<p>I have followed the response for this question (<a href="https://stackoverflow.com/questions/5851213/crawling-with-an-authenticated-session-in-scrapy">Crawling with an authenticated session in Scrapy</a>) to use scrapy with an authenticated session. The problem is that it seems to log in successfully, but when I make a request it seems to be unauthenticated. Any idea on where the problem is?</p> <p>Here is my python script:</p> <pre><code>enter code here import scrapy from scrapy.spiders.init import InitSpider from scrapy.utils.response import open_in_browser class LoginSpider(InitSpider): name = demo login_page = #login page inquery = #search query start_urls = #urls with queries def init_request(self): return scrapy.Request(url=self.login_page, callback=self.login) def login(self, response): open_in_browser(response) return [scrapy.FormRequest.from_response(response, formid='login-form', formdata={'username': 'username', 'password': 'password'}, callback=self.after_login)] def after_login(self, response): # check login succeed before going on open_in_browser(response) if "invalid username or password" in response.body: self.log("Login failed", level=log.ERROR) print "FAILED" return else: self.log('authentication succeed') return scrapy.Request(url=self.inquery, callback=self.parsse) def parsse(self, response): for result in response.xpath('//div[@class="span9"]/div[@class="search-result"]/div/a[@class="details"]/@href'): print 'new resutl' url = response.urljoin(result.extract()) yield scrapy.Request(url, callback=self.parse_details_contents) def parse_details_contents(self, response): item = ShodanItem() for details in response.xpath('//ul[@class="services"]/li'): item['ip'] = response.xpath('/html/body/div[3]/div/div[2]/div/div[1]/div/h2/text()').extract() item['services_arr'][0] = details.xpath('/div[1]/div[1]/text()').extract() item['services_arr'][1] = details.xpath('/div[1]/div[2]/text()').extract() item['services_arr'][2] = details.xpath('/div[1]/div[3]/text()').extract() item['services_arr'][3] = details.xpath('/div[2]/h3/text()').extract() item['services_arr'][4] = details.xpath('/div[2]/pre/text()').extract() print item['services_arr'][4] yield item </code></pre> <p>Here is the log, I assume it does log in as it redirects to the main page, but afterwards, using the <code>open_in_browser()</code> command I get a page that asks for authentication in order to use the query:</p> <pre><code>dsds 2016-07-06 15:07:51 [scrapy] INFO: Spider opened 2016-07-06 15:07:51 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-07-06 15:07:51 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023 2016-07-06 15:07:52 [scrapy] DEBUG: Crawled (404) &lt;GET https://account.shodan.io/robots.txt&gt; (referer: None) 2016-07-06 15:07:52 [scrapy] DEBUG: Crawled (200) &lt;GET https://account.shodan.io/login&gt; (referer: None) 2016-07-06 15:07:52 [scrapy] DEBUG: Redirecting (302) to &lt;GET https://www.shodan.io/?language=en&gt; from &lt;POST https://account.shodan.io/login&gt; 2016-07-06 15:07:53 [scrapy] DEBUG: Crawled (200) &lt;GET https://www.shodan.io/robots.txt&gt; (referer: None) 2016-07-06 15:07:53 [scrapy] DEBUG: Crawled (200) &lt;GET https://www.shodan.io/?language=en&gt; (referer: https://account.shodan.io/login) 2016-07-06 15:07:53 [shodan.io] DEBUG: authentication succeed 2016-07-06 15:07:54 [scrapy] DEBUG: Crawled (200) &lt;GET https://www.shodan.io/search?query=org%3A%22Instituto+Tecnol%C3%B3gico+y+de+Estudios+Superiores+de%22&gt; (referer: https://www.shodan.io/?language=en) ASDASDASDASDASDASDASDASDASD 2016-07-06 15:07:54 [scrapy] INFO: Closing spider (finished) 2016-07-06 15:07:54 [scrapy] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 2231, 'downloader/request_count': 6, 'downloader/request_method_count/GET': 5, 'downloader/request_method_count/POST': 1, 'downloader/response_bytes': 11759, 'downloader/response_count': 6, 'downloader/response_status_count/200': 4, 'downloader/response_status_count/302': 1, 'downloader/response_status_count/404': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 7, 6, 20, 7, 54, 214825), 'log_count/DEBUG': 8, 'log_count/INFO': 7, 'request_depth_max': 2, 'response_received_count': 5, 'scheduler/dequeued': 4, 'scheduler/dequeued/memory': 4, 'scheduler/enqueued': 4, 'scheduler/enqueued/memory': 4, 'start_time': datetime.datetime(2016, 7, 6, 20, 7, 51, 797093)} </code></pre>
2
Responsive breadcrumbs with max crumb width
<p>I'm attempting to create a responsive breadcrumb trail where the overall trail width is restricted and each crumb width is also restricted. Additionally, I'd like to allow for the last crumb to take up any additional space. I've managed to put the following together that mostly demonstrates what I'm going for, but the JQuery solution is less than idea:</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>$(document).ready(function() { var $crumbs = $(".container .breadcrumb li"); var overallWidth = $(".container").width(); var crumbWidth = (100 / $crumbs.length) + '%'; $crumbs.css('max-width', crumbWidth); var totalWidth = 0; $crumbs.each(function(elt) { var width = $(this).width(); totalWidth += width; }); var adjustment = overallWidth - totalWidth; var $lastCrumb = $(".container .breadcrumb li:last"); var lastCrumbWidth = $lastCrumb.width(); lastCrumbWidth = lastCrumbWidth + adjustment; $lastCrumb.css('max-width', lastCrumbWidth - 25); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { border: 1px solid; width: 70%; } .container .breadcrumb { padding-left: 10px; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .container .breadcrumb li { display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .container .breadcrumb li:before { color: blue; content: "&gt;"; margin-right: 5px; } .container .optional, .container .optional &gt; div { display: inline-block; } .hidden { display: none !important; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;h1&gt;Breadcrumb Truncation with Ellipsis&lt;/h1&gt; &lt;div class="container"&gt; &lt;ul id="bc1" class="breadcrumb"&gt; &lt;li&gt;Home blah blah&lt;/li&gt; &lt;li&gt;about blah blah blah&lt;/li&gt; &lt;li&gt;super cali fragilistic expialidocious&lt;/li&gt; &lt;li&gt;super duper cali fragilistic expialidocious&lt;/li&gt; &lt;li&gt;UBER super duper cali fragilistic expialidocious&lt;/li&gt; &lt;/ul&gt; &lt;div class="optional"&gt; &lt;div class="hidden"&gt;&lt;button&gt;click me&lt;/button&gt;&lt;/div&gt; &lt;div class="hidden"&gt;&lt;span&gt;extra info&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I'm sure this can be accomplished in a pure CSS way, but the solution is alluding me and probably beyond me.</p> <p>Additionally, ideally this solution would also accommodate the hiding and showing of various elements via the "hidden" that are in the "optional" section.</p> <p>UPDATE: I've made some progress with the following, but it still isn't ideal since I'm blindly using a fixed max-width:</p> <pre class="lang-css prettyprint-override"><code>.truncate { max-width: 250px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; &amp;:last-child { max-width: 100%; } } </code></pre> <p>Here's a <a href="https://jsfiddle.net/fmpdmb/g823w63g/1/" rel="nofollow">jsfiddle</a> demonstrating some of the desired functionality.</p>
2
Parse to mongoDB atlas connect
<p>I'm trying to change my parse.com connection string to a mongoDB cluster and it giving me: </p> <pre><code>Server returned error on SASL authentication step: Authentication failed. </code></pre> <p>I'm using their Connection String:</p> <pre><code>mongodb://username:[email protected]:xxxx,cluster0-shard-00-01-xxxx.mongodb.net:xxxx,cluster0-shard-00-02-xxxx.mongodb.net:xxxx/admin?replicaSet=Cluster0-shard-0 </code></pre> <p>i've added their ip(54.85.224.0/20) to the trusted ips,I'm using admin to connect. I don't know what else to do, what am i missing? I'm totally new to this so please explain to me like i'm 5!</p>
2
Freeing memory allocated in simple linked list - C
<p>I'm having a problem freeing the memory allocated in a simple linked list implementation in C. Valgrind is telling me I have not freed everything but I am unable to figure out where the problem lies. My code and valgrind output is below:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct node { int value; struct node *next; } node_t; void insert(node_t *head, int num) { // Create new node to insert node_t *item = malloc(sizeof(node_t)); item = malloc(sizeof(node_t)); if (item == NULL) { exit(2); } item-&gt;value = num; // Insert new node at end of list node_t *cur = head; while (cur-&gt;next != NULL) { cur = cur-&gt;next; } cur-&gt;next = item; } int main(int argc, char *argv[]) { // Create head or root node node_t *head; head = malloc(sizeof(node_t)); head-&gt;value = 0; head-&gt;next = NULL; // Insert nodes to end of list insert(head, 1); // Traverse list and print out all node values node_t *cur = head; while (cur != NULL) { printf("%d\n", cur-&gt;value); cur = cur-&gt;next; } // Free the list cur = head; node_t *previous; while (cur != NULL) { previous = cur; cur = cur-&gt;next; free(previous); } return 0; } // EOF </code></pre> <p>Valgrid shows the following error</p> <pre><code> ==9054== Memcheck, a memory error detector ==9054== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. ==9054== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info ==9054== Command: ./linkedlist ==9054== 0 1 ==9054== Conditional jump or move depends on uninitialised value(s) ==9054== at 0x100000ED0: main (in ./linkedlist) ==9054== Uninitialised value was created by a heap allocation ==9054== at 0x100008EBB: malloc (in /usr/local/Cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so) ==9054== by 0x100000E03: insert (in ./linkedlist) ==9054== by 0x100000EBF: main (in ./linkedlist) ==9054== ==9054== Conditional jump or move depends on uninitialised value(s) ==9054== at 0x100000F0E: main (in ./linkedlist) ==9054== Uninitialised value was created by a heap allocation ==9054== at 0x100008EBB: malloc (in /usr/local/Cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so) ==9054== by 0x100000E03: insert (in ./linkedlist) ==9054== by 0x100000EBF: main (in ./linkedlist) ==9054== ==9054== ==9054== HEAP SUMMARY: ==9054== in use at exit: 26,456 bytes in 193 blocks ==9054== total heap usage: 274 allocs, 81 frees, 32,608 bytes allocated ==9054== ==9054== 16 bytes in 1 blocks are definitely lost in loss record 5 of 65 ==9054== at 0x100008EBB: malloc (in /usr/local/Cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so) ==9054== by 0x100000DF0: insert (in ./linkedlist) ==9054== by 0x100000EBF: main (in ./linkedlist) ==9054== ==9054== LEAK SUMMARY: ==9054== definitely lost: 16 bytes in 1 blocks ==9054== indirectly lost: 0 bytes in 0 blocks ==9054== possibly lost: 0 bytes in 0 blocks ==9054== still reachable: 0 bytes in 0 blocks ==9054== suppressed: 26,440 bytes in 192 blocks ==9054== ==9054== For counts of detected and suppressed errors, rerun with: -v ==9054== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 18 from 18) </code></pre>
2
Login fails after changing password ASP.NET Core
<p>I'm using ASP.NET Core 1.0 and the identity stuff to authenticate and authorize the users. It all works fine except one single thing:</p> <p>If the user resets or changes his password, he can't sign-in with the new credentials until the ASP.NET App is restarted. Means the new passwords are successfully saved in the database, but the Method <code>_signInManager.PasswordSignInAsync()</code> doesn't use the current data, but old one. It seems there is something like a cache in the EF Core or in the SignInManager/UserStore.</p> <p>Sign-in after registration works also fine, it is just a problem after reset or change of the passwords.</p>
2
How to learn android development efficiently?
<p>It's been around 1 month that I have started to work on Android to create an app, I understood the basics (Views, widgets, intent ...) and I use a lot developer.android.com to ancknowledge new things but when I try to do complex things, such as creating a camera preview inside my app, I feel like I am Ctrl+C and Ctrl+V the code that is provided without really understanding it. And most of the time my app crashes.</p> <p>So, do you have any tips for me to make things easier ? </p>
2
Yii2-user Dektrium - Registration Controller not exists error when i override
<p>I encountered a strange issue today with Yii2. </p> <p>I am using yii2-user extension and i have overridden the RegistrationController in my app folder to add few more features.</p> <p>The thing is its working fine in my XAMPP but not in the server (Cent OS).</p> <p>Im getting the below error.</p> <pre><code>**ReflectionException Class app\controllers\user\RegistrationController does not exist** </code></pre> <p>My config is...</p> <pre><code> 'modules' =&gt; [ 'user' =&gt; [ 'class' =&gt; 'dektrium\user\Module', 'layout'=&gt;'@app/views/layouts/main.php', 'mailer' =&gt; [ 'viewPath' =&gt; '@app/views/mail', ], 'modelMap' =&gt; [ 'User' =&gt; 'app\models\User', 'RegistrationForm' =&gt; 'app\models\RegistrationForm', 'Profile' =&gt; 'app\models\Profile', ], 'controllerMap' =&gt; [ 'registration' =&gt; 'app\controllers\user\RegistrationController', 'security' =&gt; [ 'class' =&gt; 'dektrium\user\controllers\SecurityController', 'layout' =&gt; '@app/views/layouts/login', ], ], ], ], </code></pre> <p>My new controller file is...</p> <pre><code>namespace app\controllers\user; use Yii; use app\models\RegistrationForm; use dektrium\user\controllers\RegistrationController as BaseRegistrationController; use yii\filters\AccessControl; class RegistrationController extends BaseRegistrationController { ....... } </code></pre> <p>Can anyone please let me know what im doing wrong?</p> <p>Thanks in advance!</p>
2
java.io.NotSerializableException: DStream checkpointing has been enabled but the DStreams with their functions are not serializable
<p>When executing this code in Spark Streaming, I got a Serialization error (see below):</p> <pre><code> val endPoint = ConfigFactory.load("application.conf").getConfig("conf").getString("endPoint") val operation = ConfigFactory.load("application.conf").getConfig("conf").getString("operation") val param = ConfigFactory.load("application.conf").getConfig("conf").getString("param") result.foreachRDD{jsrdd =&gt; jsrdd.map(jsobj =&gt; { val docId = (jsobj \ "id").as[JsString].value val response: HttpResponse[String] = Http(apiURL + "/" + endPoint + "/" + docId + "/" + operation).timeout(connTimeoutMs = 1000, readTimeoutMs = 5000).param(param,jsobj.toString()).asString val output = Json.parse(response.body) \ "annotation" \ "tags" jsobj.as[JsObject] + ("tags", output.as[JsObject]) })} </code></pre> <p>So, as I understand, the problem is with scalaj Http api. How can I resolve this issue? Obviously I cannot change the api.</p> <blockquote> <p>java.io.NotSerializableException: DStream checkpointing has been enabled but the DStreams with their functions are not serializable org.consumer.kafka.KafkaJsonConsumer Serialization stack: - object not serializable (class: org.consumer.kafka.KafkaJsonConsumer, value: org.consumer.kafka.KafkaJsonConsumer@f91da5e) - field (class: org.consumer.kafka.KafkaJsonConsumer$$anonfun$run$1, name: $outer, type: class org.consumer.kafka.KafkaJsonConsumer) - object (class org.consumer.kafka.KafkaJsonConsumer$$anonfun$run$1, ) - field (class: org.apache.spark.streaming.dstream.DStream$$anonfun$foreachRDD$1$$anonfun$apply$mcV$sp$3, name: cleanedF$1, type: interface scala.Function1) - object (class org.apache.spark.streaming.dstream.DStream$$anonfun$foreachRDD$1$$anonfun$apply$mcV$sp$3, ) - writeObject data (class: org.apache.spark.streaming.dstream.DStream) - object (class org.apache.spark.streaming.dstream.ForEachDStream, org.apache.spark.streaming.dstream.ForEachDStream@761956ac) - writeObject data (class: org.apache.spark.streaming.dstream.DStreamCheckpointData) - object (class org.apache.spark.streaming.dstream.DStreamCheckpointData, [ 0 checkpoint files </p> <p>]) - writeObject data (class: org.apache.spark.streaming.dstream.DStream) - object (class org.apache.spark.streaming.dstream.ForEachDStream, org.apache.spark.streaming.dstream.ForEachDStream@704641e3) - element of array (index: 0) - array (class [Ljava.lang.Object;, size 16) - field (class: scala.collection.mutable.ArrayBuffer, name: array, type: class [Ljava.lang.Object;) - object (class scala.collection.mutable.ArrayBuffer, ArrayBuffer(org.apache.spark.streaming.dstream.ForEachDStream@704641e3, org.apache.spark.streaming.dstream.ForEachDStream@761956ac)) - writeObject data (class: org.apache.spark.streaming.dstream.DStreamCheckpointData) - object (class org.apache.spark.streaming.dstream.DStreamCheckpointData, [ 0 checkpoint files </p> <p>])</p> </blockquote>
2
Friendly ID not updating slug
<p>Using Rails 5 with Friendly ID 5.1.0</p> <p>Trying to understand how to update the slug when a <code>Post</code> title is changed.</p> <p>In the Friendly ID documentation it says you have to update the slug to <code>nil</code> before you can save your updated slug.</p> <p>Example</p> <pre><code>post = Post.first post.title # "My first post" post.slug = "my-first=post" post.title = "My newer first post" post.save! post.slug # "my-first=post" # Setting to nil first post.slug = nil post.title = "My newer first post" post.save! post.slug # "my-newer-first-post" </code></pre> <p>In my Post model I have set <code>should_generate_new_friendly_id?</code> in hopes it will update the slug without manually setting the slug to <code>nil</code> from the console or a web form.</p> <pre><code># == Schema Information # # Table name: post # # id :integer not null, primary key # title :string default(""), not null # body :text default(""), not null # created_at :datetime not null # updated_at :datetime not null # slug :string # # Indexes # # index_posts_on_slug (slug) UNIQUE # class Post &lt; ApplicationRecord extend FriendlyId friendly_id :title, use: :history private def should_generate_new_friendly_id? title_changed? || super end end </code></pre> <p>Is it the job of the <code>should_generate_new_friendly_id?</code> method to update the slug if it's defined in your model?</p> <p>Thanks again.</p>
2
Add error message to PHP login page
<p>I am new to PHP, so please be gentle...</p> <p>I have created a PHP login page in Dreamweaver, and have set the failed login to return to the same page, but would like to display a message to say "username or password are incorrect".</p> <p>The data is stored in a MySQL database Here is the code that has been generated by Dreamweaver:</p> <pre><code>if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['email'])) { $loginUsername=$_POST['email']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "bac123_update_details.php"; $MM_redirectLoginFailed = "bac123.php"; $MM_redirecttoReferrer = true; mysql_select_db($database_connRespond, $connRespond); $LoginRS__query=sprintf("SELECT email, password FROM customer WHERE email=%s AND password=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $connRespond) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION &gt;= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) &amp;&amp; true) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } </code></pre>
2
create shadow for bitmap in custom view
<p>I have a custom view wich contain some bitmaps and I want to set shadows for them, for that, I use this code:</p> <pre><code>shadowPaints=new Paint(Paint.ANTI_ALIAS_FLAG); shadowPaints.setShadowLayer(10.0f, 3.0f, 2.0f, Color.BLACK); canvas.drawBitmap(bmp, matrix, shadowPaints); setLayerType(LAYER_TYPE_SOFTWARE, shadowPaints); </code></pre> <p>and my result is <a href="https://i.stack.imgur.com/GrTq4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GrTq4.png" alt="enter image description here" /></a> as you can see my shadow actually is another bitmap with different x and y position but what I want is my shadow be a solid color bitmap.<br /> can anyone help me about this?</p>
2
Ionic run : launch my emulator but not the app
<p>I use ionic 1.7.16 and cordova 6.2.0</p> <p>With <code>adb devices -list</code> I have no device detected whereas my phone is plugged on my PC (with USB debug)</p> <p>I have installed my java jdk, Android SDK &amp; Ant and add them to my PATH variable.</p> <p>Result of <code>cordova requirements</code> :</p> <pre><code>Requirements check results for android: Java JDK: installed . Android SDK: installed Android target: installed android-23,android-24 Gradle: installed Requirements check results for ios: Apple OS X: not installed Cordova tooling for iOS requires Apple OS X Error: Some of requirements check failed </code></pre> <p>When I launch <code>ionic run android</code> it runs automatically my emulator, instead of installing the apk on my phone plugged. Moreover, my android emulator is launched but not my app ...</p> <p>I looked for solution but I found nothing. </p> <p>This method not correspond to the version of my cordova unfortunately. <a href="https://stackoverflow.com/questions/30008842/cordova-launch-success-but-no-app-running-on-cellphone">&quot;cordova launch success&quot; but no app running on cellphone</a></p> <p>Anyone have a solution to fix my problem ?</p> <p>Thank's for your answers.</p>
2
Matplotlib/Pandas: How to plot multiple scatterplots within different locations in the same plot?
<p>I often have two pandas dataframes, which I would like to plot within the same plot. Normally these are two samples, and I would like to contrast their properties, as an example: </p> <p><a href="https://i.stack.imgur.com/IlOrO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IlOrO.png" alt="enter image description here"></a></p> <p>The x axis simply has two locations, the left for the first dataset, and the right for the second dataset. </p> <p>In matplotlib, one can plot multiple datasets within the same plot:</p> <pre><code>import matplotlib.pyplot as plt x = range(100) y = range(100,200) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first') ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/pGmmI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pGmmI.png" alt="enter image description here"></a></p> <p>However, </p> <p>(1) How do you separate your datasets into two compartmentalized locations like the first example? </p> <p>(2) How do you accomplish this with two pandas dataframes? Do you merge them and then specify two locations for plotting? </p>
2
Highchart performance slow on plotting live data
<p>I am plotting live data in Highchart's(4.2.4) Line type chart for each second data i.e. 60 points for 1 min. and requirement is to collect each second data for long duration. I am using below code to add point in series. <strong>The number of series I have is 20</strong>. And for each series I have to add point per second. The <strong>turboThreshold set for each series is also around 2000</strong>. And <strong>slicing should be done after 1000 points</strong> data. </p> <pre><code>chart.series[0].addPoint(point, false, data &gt; 1000?shift: false, false); </code></pre> <p>I see a very low performance my browser keeps hanging and also chart is very irresponsive after some time. What can I do for better performance? I have tried below stuff: 1) Off the animation for series :</p> <pre><code>plotOptions: { series: { animation:false, states: { hover: { lineWidthPlus: 0 } } } }, </code></pre> <p>2) Turn off animation and redrawing on addpoint to the chart </p> <p>3) Turn off markers for series</p> <p>4) Included boost.js module in application <pre> script src="https://code.highcharts.com/modules/boost.js"</pre> </p>
2
Return value in Prolog
<p>I find that some 'functions' in Prolog return some value, like min/2 and max/2, etc, even though vast majority return only true or false. Are these called or grouped differently than boolean ones? Also how can one identify if they are returning a value other than going through documentation of each function. Can I find a list somewhere of functions which return some value? </p>
2
Button to Add Cell with textField Text to Table Xcode/Swift 2.0
<p>My question relates specifically to the following set of actions: I would like a user to be able to input text into a textField, press a button, then have that text transferred into a cell that is then newly populated in a table. </p> <p>I have one view controller with a text field, button, and table objects. I also have an array that stores each string as the user enters the text, and my code looks as follows: </p> <p>UPDATE 1: added "self.taskTable.delegate = self" and "self.taskTable.dataSource = self" as suggested in the comments. </p> <p>UPDATE 2: forgot to add the identifier in the Storyboard editor, code is now functional, thank you everyone! The code is now as follows:</p> <pre><code>import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var textField: UITextField! @IBOutlet var taskTable: UITableView! var taskArray : NSMutableArray! = NSMutableArray() //Could be a non-NS as well @IBAction func addTask(sender: AnyObject) { //Print to alert we entered method print("task submitted") //Get input from text field let input = textField.text //Add object to array, reload table self.taskArray.addObject(input!) self.taskTable.reloadData() }//addTask override func viewDidLoad() { super.viewDidLoad() self.taskTable.delegate = self self.taskTable.dataSource = self print("application finished loading") // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return self.taskArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell:UITableViewCell = self.taskTable.dequeueReusableCellWithIdentifier("cell")! cell.textLabel?.text = self.taskArray.objectAtIndex(indexPath.row) as? String return cell } } </code></pre>
2
Testing aiohttp & mongo with pytest
<p>I have a simple coroutine <code>register</code> that accepts login and password as post arguments, then it goes into the database and so on. The problem I have is that I do not know how to test the coroutine.</p> <p>I followed examples from <a href="https://aiohttp.readthedocs.io/en/latest/testing.html" rel="nofollow">https://aiohttp.readthedocs.io/en/latest/testing.html</a>.</p> <p>And everything seemed easy until I started writing tests myself.</p> <p>Code for <code>test_register.py</code></p> <pre><code>from main import make_app pytest_plugins = 'aiohttp.pytest_plugin' @pytest.fixture def cli(loop, test_client): return loop.run_until_complete(test_client(make_app)) async def test_register(cli): resp = await cli.post('/register', data={'login': 'emil', 'password': 'qwerty'}) assert resp.status == 200 text = await resp.text() </code></pre> <p>And <code>register.py</code></p> <pre><code>from settings import db async def register(request): post_data = await request.post() print('Gotta: ', post_data) login, password = post_data['login'], post_data['password'] matches = await db.users.find({'login': login}).count() ... </code></pre> <p><code>main.py</code></p> <pre><code>from aiohttp import web from routes import routes def make_app(loop=None): app = web.Application(loop=loop) for route in routes: app.router.add_route(route.method, route.url, route.handler) return app def main(): web.run_app(make_app()) if __name__ == "__main__": main() </code></pre> <p><code>settings.py</code></p> <pre><code>from motor.motor_asyncio import AsyncIOMotorClient DBNAME = 'testdb' db = AsyncIOMotorClient()[DBNAME] </code></pre> <p>And then I ran <code>py.test test_register.py</code> and it got stuck on database operation <code>matches = await db.users.find({'login': login}).count()</code></p>
2
Get current post ID in javascript - WordPress
<p>I am making a plugin for wordpress. The plugin will add a tinymce on the edit post, and it will send the post_id to the database to do some identification later.</p> <p>In my case, I am writing a javascript, which directory in <code>wordpress\wp-content\plugins\facebook-api\js\shortcode-tinymce-button.js</code>. And now I have no idea how I can get the post_Id in javascript.</p> <p>Here is what I am doing:</p> <ol> <li>user click the <code>OK button</code> will send the post_Id and the text box value to the database. <a href="https://i.stack.imgur.com/hPe3A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hPe3A.png" alt="enter image description here"></a></li> </ol> <p>Here is my code:</p> <pre><code>(function() { tinymce.PluginManager.add('facebook_api_tinymce', function( editor, url ) { editor.addButton( 'facebook_api_tinymce', { title: 'Set friend condition', text: 'Condition', type: 'menubutton', menu: [ { text: 'Friend', onclick: function() { editor.windowManager.open( { body:[ { type: 'textbox', name: 'textboxName', label: 'Set friend', value: '20' } ],onsubmit: function( e ) { var $hi = "php echo get_the_ID();"; alert($hi); $no_friend_e = parseInt(e.data.textboxName); //Pass the value the PHP file, which is doing the database update. jQuery.ajax({ url: 'http://localhost:8080/wordpress/wp-content/plugins/facebook-api/js/databaseConnection.php', type: 'POST', data: {functionname: 'updateDatabase', post_id: '1', no_friend: $no_friend_e}, error:function(data){ //When Can't call the PHP function alert("failed"); console.log(data); }, success: function(data) { //update data successful alert("success"); console.log(data); // Inspect this in your console } }); } }); function get_post_content(id){ //Didn't use return document.getElementById("post-"+id).innerHTML; }//you should probably use textContent/innerText but I am not going to get into that here } } ] }); }); </code></pre> <p>Thanks,</p>
2
How to examine user thread call stack from windbg kernel debugger?
<p>My exe-once test program calls <code>CancelIo</code> and it blocks, I'd like to investigate in which function it is blocking, so, when it blocks, I use windbg to break into the machine, remotely, and try to find it out.</p> <p>As marked as yellow in the image, my EXE has two threads, <code>fffffa8013958b60</code> and <code>fffffa8013aa1060</code>. I already know that <code>fffffa8013aa1060</code> is the one calling <code>CancelIo</code>.</p> <p><strong>Then, how do I show current call stack of the thread <code>fffffa8013aa1060</code>?</strong></p> <p><a href="https://i.stack.imgur.com/nGWha.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nGWha.png" alt="enter image description here"></a></p> <pre><code>1: kd&gt; !process fffffa8014c25170 2 PROCESS fffffa8014c25170 SessionId: 1 Cid: 0ad4 Peb: 7fffffdf000 ParentCid: 07b8 DirBase: 2b451000 ObjectTable: fffff8a002e61620 HandleCount: 12. Image: exe-once.exe THREAD fffffa8013958b60 Cid 0ad4.0724 Teb: 000007fffffdd000 Win32Thread: 0000000000000000 WAIT: (UserRequest) UserMode Non-Alertable fffffa8013aa1060 Thread THREAD fffffa8013aa1060 Cid 0ad4.01e8 Teb: 000007fffffdb000 Win32Thread: 0000000000000000 WAIT: (DelayExecution) KernelMode Non-Alertable fffffa8013aa1420 Semaphore Limit 0x1 </code></pre>
2
Is there a way to validate an SMTP configuration using Zend-Mail?
<p>I have been working on a class in PHP to send out mail and I decided to use the Zend framework. This class sends out mail using a user's SMTP configuration. As of right now I am checking a user's SMTP configuration by using the supplied user credentials, and sending out a "dummy" email to a "dummy" email address, and catching the <code>ZendException</code> class that may be thrown on error. This is a horrible method, because of many reasons:</p> <ul> <li>The SMTP user get's banned eventually for suspected "Spamming" (GMail)</li> <li>Inefficient and time consuming</li> <li>Failed email delivery attempt is in user's mailbox</li> </ul> <p><strong>The following is an example of what I am doing right now to test if a SMTP configuration is valid:</strong></p> <pre><code>public function validSMTP () { // Get the user's SMTP configuration $config = $this-&gt;getConfiguration (); // Create a new Zend transport SMTP object $transport = new Zend_Mail_Transport_Smtp ( $config ["hostname"], [ "auth" =&gt; "login", "ssl" =&gt; $config ["protocol"], "port" =&gt; $config ["port"], "username" =&gt; $config ["from"], "password" =&gt; $config ["password"] ]); // Create a new message and send it to dummy email $mail = new Zend_Mail ("UTF-8"); $mail-&gt;setBodyText ( "null" ); $mail-&gt;setFrom ( $config ["from"] ); $mail-&gt;addTo ( "[email protected]" ); $mail-&gt;setSubject ( "Test" ); // Attempt to send the email try { // Send the email out $mail-&gt;send ( $transport ); // If all is well, return true return true; } // Catch all Zend exceptions catch ( Zend_Exception $exception ) { // Invalid configuration return false; } } </code></pre> <p>So my question is: Is there a better way of doing this? Does <strong>Zend_Mail</strong> have a built in feature like this? I have looked all over and couldn't find anything build-in into <strong>Zend_Mail</strong>. Thank you in advance to whoever answers!</p>
2
Show Vertical Graph Bar Percentage in the middle of div
<p>I have a progress bar that I need to be able to show the percentage text always in the middle of the progress bar. Currently, only the values are not vertically centered inside the progress bar. I need to do this only with html and CSS and not jQuery or javascript </p> <p><a href="https://i.stack.imgur.com/Dj3PD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dj3PD.png" alt="enter image description here"></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.vertical .progress-bar { float: left; height: 100px; width: 40px; margin-right: 10px; } .vertical .progress-track { position: relative; width: 40px; height: 100%; background: #fff; border: 1px solid #ebebeb; } .vertical .progress-fill { position: relative; height: 50%; width: 40px; color: #fff; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="vertical"&gt; &lt;div class="progress-bar"&gt; &lt;div class="progress-track"&gt; &lt;div class="progress-fill" style="height: 100%; top: 0%; background: rgb(191, 231, 178);"&gt;&lt;/div&gt; &lt;span style="color: rgb(0, 0, 0);"&gt;100%&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="progress-bar"&gt; &lt;div class="progress-track"&gt; &lt;div class="progress-fill" style="height: 80%; top: 20%; background: rgb(248, 231, 153);"&gt;&lt;/div&gt; &lt;span style="color: rgb(0, 0, 0);"&gt;80%&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="progress-bar"&gt; &lt;div class="progress-track"&gt; &lt;div class="progress-fill" style="height: 60%; top: 40%; background: rgb(248, 231, 153);"&gt;&lt;/div&gt; &lt;span style="color: rgb(0, 0, 0);"&gt;60%&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="progress-bar"&gt; &lt;div class="progress-track"&gt; &lt;div class="progress-fill" style="height: 2%; top: 98%; background: rgb(248, 138, 138);"&gt; &lt;span style="color: rgb(0, 0, 0);"&gt;0%&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
2
Delete Smartgit config directory not removing everything
<p>I'm on OSX and using SmartGit (maybe not any more because it drives me crazy). I wanted to add another github account. I could not push because somehow SmartGit was using the old one. I deleted the </p> <pre><code>~/Library/Preferences/SmartGit </code></pre> <p>folder and restarted. SmartGit asked for new license agreement and everything. When it opened my repositories where still there and it still tried to use the old credentials. Is there some magic folder not documented by syntevo? </p>
2
How to apply Local Storage to a to-do list
<p>I'm working on an app, and one section of this app is like a to-do list. The user can add and delete list-items. I've been trying to apply local storage to this list, but I can't do it.</p> <p>HTML:</p> <pre><code>&lt;input type="text" id="entrada" placeholder="" /&gt; &lt;a href="#" data-role="button" id="agregar"&gt;Add&lt;/a&gt; &lt;ul id="list" data-role="listview"&gt; &lt;/ul&gt; </code></pre> <p>JS:</p> <pre><code>$('#agregar').on('click', function() { $('#agregar').on('click', function(event) { $('#entrada').val("")}) var entrada = $('#entrada').val(); if($("#entrada").val() == '') { return false; } $('#list').append( '&lt;li&gt;&lt;a hreft="#"&gt;'+entrada+&lt;'&lt;/a&gt;&lt;/li&gt;' ); $('#list').listview( 'refresh' ); } ) </code></pre>
2
Jenkins pipeline, bitbucket hook and maven release plugin infinite loop
<p>I haven't been able to find any info about this, so i hope you guys can help me on this one</p> <p>I've a maven project hosted in bitbucket that has a BitBucket WebHook pointing to someurl/bitbucket-hook/ , this hooks triggers the build of my project that is defined by a pipeline that has this structure:</p> <pre><code>node { stage 'Checkout' git url: 'https:...' def mvnHome = tool 'M3' #Various stages here ... stage 'Release' sh "${mvnHome}/bin/mvn -B clean install release:prepare release:perform release:clean" } </code></pre> <p>the problem is that maven release plugin pushes changes to BitBucket, and this triggers again the jenkins script, making an infinite loop of builds, is there a way to prevent this? </p> <p>I've tried setting a quiet period in Jenkins with no success</p>
2
Unable to deploy lodash
<p>I'm in trouble with lodash. When I deploy using gulp I've always the same error:</p> <pre><code>vendors.min.js:3 GET http://127.0.0.1/projects/myproject/lodash 404 (Not Found) </code></pre> <p>I declare the library into my <strong>index.html</strong> file </p> <pre><code>&lt;script src="node_modules/lodash/lodash.js"&gt;&lt;/script&gt; </code></pre> <p>I import lodash into my <strong>typescript file</strong></p> <pre><code>///&lt;reference path="../../../typings/modules/lodash/index.d.ts" /&gt; import * as _ from "lodash"; </code></pre> <p>That's work when I test my website localy (by launching lite server with npm start). </p> <p>And now, I want to deploy my web site using Gulp. Here is my <strong>gulp file</strong> :</p> <pre><code>gulp.task('app-bundle', function () { var tsProject = ts.createProject('tsconfig.json', { typescript: require('typescript'), outFile: 'app.js' }); var tsResult = gulp.src([ 'node_modules/angular2/typings/browser.d.ts', 'typings/main/ambient/firebase/firebase.d.ts', 'app/**/*.ts' ]) .pipe(ts(tsProject)); return tsResult.js.pipe(addsrc.append('config-prod.js')) .pipe(concat('app.min.js')) .pipe(uglify()) .pipe(gulp.dest('./dist')); }); gulp.task('vendor-bundle', function() { gulp.src([ 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/angular2.dev.js', 'node_modules/angular2/bundles/http.dev.js', 'node_modules/angular2/bundles/router.min.js', 'node_modules/lodash/lodash.js' ]) .pipe(concat('vendors.min.js')) .pipe(uglify()) .pipe(gulp.dest('./dist')); }); gulp.task('default',[ 'app-bundle', 'vendor-bundle' ], function() { gulp.src('index.html') .pipe(htmlreplace({ 'vendor': 'vendors.min.js', 'app': 'app.min.js' })) .pipe(gulp.dest('dist')); }); </code></pre> <p>When I test my website, I have the following errors :</p> <pre><code> vendors.min.js:3 GET http://127.0.0.1/projects/myproject/lodash 404 (Not Found)r @ vendors.min.js:3e.scheduleTask @ vendors.min.js:3e.scheduleMacroTask @ vendors.min.js:3(anonymous function) @ vendors.min.js:3send @ VM3157:3L @ vendors.min.js:4(anonymous function) @ vendors.min.js:4e @ vendors.min.js:3(anonymous function) @ vendors.min.js:4(anonymous function) @ vendors.min.js:4(anonymous function) @ vendors.min.js:5(anonymous function) @ vendors.min.js:5(anonymous function) @ vendors.min.js:5(anonymous function) @ vendors.min.js:5(anonymous function) @ vendors.min.js:5(anonymous function) @ vendors.min.js:4e.invoke @ vendors.min.js:3e.run @ vendors.min.js:3(anonymous function) @ vendors.min.js:3e.invokeTask @ vendors.min.js:3e.runTask @ vendors.min.js:3o @ vendors.min.js:3invoke @ vendors.min.js:3 vendors.min.js:3 Error: XHR error (404 Not Found) loading http://127.0.0.1/projects/myproject/lodash Error loading http://127.0.0.1/projects/myproject/lodash as "lodash" from http://127.0.0.1/projects/myproject/services/base-services/base.services at o (http://127.0.0.1/projects/myproject/vendors.min.js:4:10124) at XMLHttpRequest.L.a.onreadystatechange (http://127.0.0.1/projects/myproject/vendors.min.js:4:10712) at XMLHttpRequest.t [as _onreadystatechange] (http://127.0.0.1/projects/myproject/vendors.min.js:3:12638) at e.invokeTask (http://127.0.0.1/projects/myproject/vendors.min.js:3:8519) at e.runTask (http://127.0.0.1/projects/myproject/vendors.min.js:3:5879) at XMLHttpRequest.invoke (http://127.0.0.1/projects/myproject/vendors.min.js:3:9628) </code></pre> <p>Here is my SystemJS : </p> <pre><code>System.config({ paths: { 'rxjs/add/observable/*' : 'node_modules/rxjs/add/observable/*.js', 'rxjs/add/operator/*' : 'node_modules/rxjs/add/operator/*.js', 'rxjs/*' : 'node_modules/rxjs/*.js' }, map: { '@angular' : 'angular2', 'videogular2' : 'node_modules/videogular2', 'rxjs': 'node_modules/rxjs', 'lodash': 'node_modules/lodash' }, packages: { map: { 'rxjs': 'node_modules/rxjs' }, app: { format: 'register', defaultExtension: 'js' }, node_modules: { defaultExtension: 'js' }, lodash:{ main:'lodash', defaultExtension:'js' } } }); System.import('app/boot') .then(null, console.error.bind(console)); </code></pre> <p>I search since many days a solution and I really appreciate any help :).</p> <p>When I deploy, I add that script too : </p> <pre><code>document.addEventListener('DOMContentLoaded', function () { System.import('boot') .then(null, console.error.bind(console)); }); </code></pre>
2
Dashboard tool for a custom SQL Server database
<p>For a project I'm working on I have build a reporting database in SQL Server. We are pretty much free to design the structure of the DB and what we put it in.</p> <p>However, now comes the fun part and we would need to be able to visualize the data in some nice dashboards.</p> <p>Can anybody provide me with some suggestions on an easy to use tool (end-users will need to be able to manipulate the dashboards) that is not dependent on the underlying database technology? (if its based on SQL Server I can live with that :))</p> <p>I've looked in to Kibana but seems to be only possible if you use ElasticSearch. Currently investigating Grafana to see what that brings me so anything in that realm would be appreciated!</p>
2
Find out query text before doing ExecuteNonQuery()
<p>Here is an example of using OleDbCommand and ExecuteNonQuery(I took it from a manual on msdn.microsoft.com). I would like to check out the query that was generated before executing it.</p> <pre><code>private static void OleDbCommandPrepare(string connectionString) { using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Create the Command. OleDbCommand command = new OleDbCommand(); // Set the Connection, CommandText and Parameters. command.Connection = connection; command.CommandText = "INSERT INTO dbo.Region (RegionID, RegionDescription) VALUES (?, ?)"; command.Parameters.Add("RegionID", OleDbType.Integer, 4); command.Parameters.Add("RegionDescription", OleDbType.VarWChar, 50); command.Parameters[0].Value = 20; command.Parameters[1].Value = "First Region"; // Call Prepare and ExecuteNonQuery. command.Prepare(); </code></pre> <p><b>find out the query that is being executed here</b></p> <pre><code> command.ExecuteNonQuery(); // Change parameter values and call ExecuteNonQuery. command.Parameters[0].Value = 21; command.Parameters[1].Value = "SecondRegion"; command.ExecuteNonQuery(); } } </code></pre> <p>Is there any possible way to do it? I'm using PgSqlCommand - which is PostgreSQL equivalent of OleDbCommand and getting undescribed exception. I was able to build that query and find what was the error by cycling Command.Parameters and replacing question symbols in Command.CommandText with paremeter's values, but I am hoping that there is a built-in method to get that query. </p>
2
How to adjust the label position in an Indexed X-axis on Chart
<p>I am creating a chart in WinForms in C# and the X-axis is <strong>indexed</strong>.</p> <p>I have 10000 points in the chart series</p> <p>For some reason, the X-axis labels are labeled From 1 to 10001. Which means when I set the X-value (time) for any point, it does not get displayed for the 10001th label. </p> <p>I tried setting the following parameters, none of which helped</p> <pre><code>chart1.ChartAreas[0].AxisX.MajorTickMark.IntervalOffset = -1; chart1.ChartAreas[0].AxisX.LabelStyle.IntervalOffset = -1; chart1.ChartAreas[0].AxisX.IsStartedFromZero = true; chart1.ChartAreas[0].AxisX.IsLabelAutoFit = false; </code></pre> <p>None of this did anything to help, my chart labels are still reading from 1 to 10001, and no matter how much I zoom in (with added zoom controls) the labels still read on every interval ending with 1. Like 1001, 2001, 3001, .. etc. </p> <p>How can I change this to read from 0 to 10000? And only show lines and labels on intervals ending with 0</p> <p>Thanks</p> <p>EDIT:</p> <p>The minimum and the maximum were already set, in the screenshot you see below, all the X values are correctly indexed, but for some reason the chart display value 10001</p> <p>And I do not wish to set the value to the Maximum to 10000 in this case, it will prevent the label from showing up but it will also prevent the ability to scroll the axis past the last measurement.</p> <p><a href="https://i.stack.imgur.com/kCQwi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kCQwi.jpg" alt="10001"></a></p>
2
C++: Debug assertion failed, afx.inl line 122
<p>here is the description of the problem.</p> <p>I have the following class defined..</p> <pre><code>class classA { public: CString aString; }; extern classA theApp; </code></pre> <p>in another class function, I do this </p> <pre><code>theApp.aString = "test string"; </code></pre> <p>then I get the runtime error debug assertion failed, afx.inl line 122; please advise.</p> <p>I tried to do the allocation inside the class as well but it fails flagging the same runtime error.</p> <pre><code> class classA { public: CString aString; void set_string() { aString = "test string 2"; } }; extern classA theApp; //in another class function theApp.set_string(); </code></pre> <p>visual c++ version: VC++ 6.0</p>
2
Nginx reverse proxy disable listing directories - autoindex
<p>I have a reverse nginx proxy</p> <pre><code> location / { autoindex off; proxy_set_header HOST $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://owncloud/; } </code></pre> <p>Now I want to prevent that users can go to <a href="https://url.tld/data" rel="nofollow noreferrer">https://url.tld/data</a> and view the folder content... autoindex off; is not working.</p> <p>I want to achieve this without changing the (owncloud) .htaccess because it's inside a docker container.</p> <p>In which way is this possible?</p>
2
Incorrect syntax near outer join in sql server
<p>I am trying this query to fetch data from two table. I am getting the error on join.</p> <pre><code>select bundlechecklist.Bundle_TXN_ID, documentchecklist.Bundle_TXN_ID, documentchecklist.Doc_Type_Name from bundle_checklist_txn bundlechecklist outer join Document_Checklist_TXN documentchecklist on documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID where bundlechecklist.originating_tran_id = "AMD1256" and bundle_name = "Line" </code></pre> <p>Please help me in fixing the error</p>
2
WCF Error: System.ServiceModel.AddressAccessDeniedException:
<p>When I try to run a demo WCF Service Project (Windows 7 Enterprise Machine) I get the following:</p> <pre><code>&gt; Please try changing the HTTP port to 8733 or running as Administrator. System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL http://+:8080/helloworld/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details). ---&gt; System.Net.HttpListenerException: Access is denied at System.Net.HttpListener.AddAllPrefixes() at System.Net.HttpListener.Start() at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen() --- End of inner exception stack trace --- at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen() at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener) at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback) at System.ServiceModel.Channels.TransportChannelListener.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.HttpChannelListener`1.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Channels.DatagramChannelDemuxer`2.OnOuterListenerOpen(ChannelDemuxerFilter filter, IChannelListener listener, TimeSpan timeout) at System.ServiceModel.Channels.SingletonChannelListener`3.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.NegotiationTokenAuthenticator`1.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) at System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelListener`1.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) at System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelListener`1.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info) System.Net.HttpListenerException (0x80004005): Access is denied at System.Net.HttpListener.AddAllPrefixes() at System.Net.HttpListener.Start() at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen() </code></pre> <p>At home it works, but at work it seems I might need some type of pemissions elevated. I have tried running VS as administrator and changing the port to 8733 but I still get the problem. Also in command promopt I tried "netsh http add urlacl url=<a href="http://+:8080/MyUri" rel="nofollow">http://+:8080/MyUri</a> user=DOMAIN\user", but got the error "url reservation add failed error 5" I'm thinking maybe admin needs to elevate some type of permission.</p> <p>Here is service:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace HelloWorldService { [DataContract] public class Name { [DataMember] public string First; [DataMember] public string Last; } [ServiceContract] public interface IHelloWorld { [OperationContract] string SayHello(Name person); } public class HelloWorldService : IHelloWorld { #region IHelloWorldMembers public string SayHello(Name person) { return string.Format("Hello {0} {1}", person.First, person.Last); } #endregion } } </code></pre> <p>Here is the app.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;appSettings&gt; &lt;add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /&gt; &lt;/appSettings&gt; &lt;system.web&gt; &lt;compilation debug="true" /&gt; &lt;/system.web&gt; &lt;!-- When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries. --&gt; &lt;system.serviceModel&gt; &lt;services&gt; &lt;service name="HelloWorldService.HelloWorldService"&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress = "http://localhost:8080/helloworld" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;!-- Service Endpoints --&gt; &lt;!-- Unless fully qualified, address is relative to base address supplied above --&gt; &lt;endpoint address="ws" binding="wsHttpBinding" contract="HelloWorldService.IHelloWorld"/&gt; &lt;endpoint address="basic" binding="basicHttpBinding" contract="HelloWorldService.IHelloWorld"/&gt; &lt;endpoint address="net.tcp://localhost:8081/helloworld" binding="netTcpBinding" contract="HelloWorldService.IHelloWorld"/&gt; &lt;!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. --&gt; &lt;!--&lt;identity&gt; &lt;dns value="localhost"/&gt; &lt;/identity&gt;--&gt; &lt;!-- Metadata Endpoints --&gt; &lt;!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --&gt; &lt;!-- This endpoint does not use a secure binding and should be secured or removed before deployment --&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior&gt; &lt;!-- To avoid disclosing metadata information, set the values below to false before deployment --&gt; &lt;serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/&gt; &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt; &lt;serviceDebug includeExceptionDetailInFaults="False" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre>
2
TeamCity Agents 64-bit fail to start
<p>I am trying to get the 64-bit version of a TeamCity (9.1.1) agent running. I can install the service, but as soon as I start it, I get the following in the wrapper.log:</p> <pre><code>ERROR | wrapper | .... | Stdout pipe creation failed ERROR | wrapper | .... | The TeamCity Build Agent service was launched, but failed to start. </code></pre> <p>I can't find any other log entries providing info regarding this.</p> <p>Any suggestions? I literally only found two similar posts online, which makes me think it is more related to the Java service wrapper than TeamCity...</p> <p>(Update: The 64-bit version is required to execute tests specific to a 64-bit version of a built assembly)</p>
2
Removing empty key from RDD
<p>I am reading a text file and implementing a word count example. The problem is I am getting an RDD with empty Key.</p> <p>Here is code:</p> <pre><code>val tokens = sc.textFile("test.txt").flatMap(line =&gt; line.split(",")).map(_.trim) val tableForFrequency = tokens.map(word =&gt; (word, 1)) .reduceByKey((a, b) =&gt; a + b) tableForFrequency.saveAsTextFile("file.txt") </code></pre> <p>I am not sure why I am getting an empty and how do I remove it.</p> <p>Please note: I am a newbie in Scala/Spark and have already looked for related question before posting this one.</p>
2
RXSwift flatMap two methods
<p>I'm having 2 methods like this:</p> <pre><code>func rxGetAllTonicsForLanguage(language: Language) -&gt; Observable&lt;AnyObject?&gt; func saveTonics(list: [Tonic]) -&gt; Observable&lt;AnyObject?&gt; </code></pre> <p>Now I want to first do the getAllTonics call and then with the result of that call I want to do the next action. So I thought this was something I could do with FlatMap. But I'm stuck I can't figure out how to chain these.</p> <p>I tried like follows:</p> <pre><code> self.remoteService.rxGetAllTonicsForLanguage(language) .subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background)) .flatMap{tonics -&gt; Observable&lt;[Tonic]&gt; in print("Tonics: \(tonics)") let x = tonics as! [Tonic] return TonicAdapter.sharedInstance.saveTonics(x) }.observeOn(MainScheduler.instance) .subscribe({ e in switch e { case .Next(let element): if let result = element as? String { DDLogDebug("Saved something \(result)") } case .Error(let e): DDLogError("Error in save tonics \(e)") case .Completed: DDLogDebug("Completed save tonics") } } ).addDisposableTo(self.disposeBag) </code></pre> <p>It gives me this error on the line of return TonicAdapter:</p> <pre><code>Cannot convert return expression of type 'Observable&lt;AnyObject?&gt;' (aka 'Observable&lt;Optional&lt;AnyObject&gt;&gt;') to return type 'Observable&lt;[Tonic]&gt;' (aka 'Observable&lt;Array&lt;Tonic&gt;&gt;') </code></pre> <p>I don't see the problem because both methods are returning Observables?</p>
2
how to align to right and middle in height in layout
<p>I have a Switch, witch is aligned to the left of a layout, I want to align a TextView to the right of it AND to the middle of the height of it. I have done two example pictures to explain it more clearly.</p> <p>This is what i have (where A is the Switch, and b is the TextView):</p> <p><a href="https://i.stack.imgur.com/DgIoi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DgIoi.jpg" alt="enter image description here"></a></p> <p>This is what i want to achieve:</p> <p><a href="https://i.stack.imgur.com/rjK5o.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rjK5o.jpg" alt="enter image description here"></a></p> <p>My layout code for the switch is: </p> <pre><code>&lt;Switch android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CIR" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:checked="true" android:gravity="center" android:id="@+id/newProject_switch" android:layout_below="@+id/newProject_networkId" android:layout_marginTop="10dp" android:layout_alignParentLeft="true" /&gt; </code></pre> <p>My layout code for the TextView is:</p> <pre><code>&lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Best Effort" android:textSize="15dp" android:id="@+id/textView2" android:layout_alignBottom="@+id/newProject_switch" android:gravity="right|center_vertical" android:layout_toRightOf="@+id/newProject_switch" /&gt; </code></pre>
2