problem
stringlengths
26
131k
labels
class label
2 classes
static uint32_t rtas_set_dr_indicator(uint32_t idx, uint32_t state) { sPAPRDRConnector *drc = spapr_drc_by_index(idx); if (!drc) { return RTAS_OUT_PARAM_ERROR; } trace_spapr_drc_set_dr_indicator(idx, state); drc->dr_indicator = state; return RTAS_OUT_SUCCESS; }
1threat
Parse error: syntax error, unexpected end of file Issue : <p>I am getting the <code>Parse error: syntax error, unexpected end of file</code> regardless of what I change/add to my code, the error constantly tells me that there is something wrong with my last line.</p> <p>My PHP file should be saving form input to the database but this error seems to be getting in the way and I cannot figure out what is causing it.</p> <p>PHP Code</p> <pre><code>&lt;?php function so56917978_upload_callback() { //Register variables $adddate = $_POST['adddate']; $addcontact = $_POST['addcontact']; $adda = $_POST['adda']; $addb = $_POST['addb']; $addincome = $_POST['addincome']; $addpayment = $_POST['adddate']; $addsubbie = $_POST['addsubbie']; $addcust = $POST['addcust']; //connect with Database $host_name = 'zzz.hosting-data.io'; $database = 'zzz'; $user_name = 'zysql_connect($host_name, $user_name, $password); if(!$connect) { die('Not Connected To Server'); } //Connection to database if(!mysql_select_db($connect, $database)) { echo 'Database Not Selected'; } $query = mysql_query($connect,"SELECT * FROM table WHERE adddate = '$adddate' OR addcontact = '$addcontact' OR adda= '$adda' OR addb = '$addb' OR addincome = '$addincome' OR addpayment = '$addpayment' OR addsubbie = '$addsubbie' OR addcust = '$addcust'"); $sql = "INSERT INTO table (adddate, addcontact, adda, addb, addincome, addpayment, addsubbie, addcust) VALUES ('$adddate', '$addcontact', '$adda', '$addb', '$addincome', '$addpayment', '$addsubbie', '$addcust')"; if (!mysql_query($connect,$sql)) { die('Error: ' . mysql_error($connect)); } echo "1 record added"; mysql_close($connect); </code></pre>
0debug
TypeError: 'tuple' object is not callable Python : <p>Currently coding for some machine learning in which I am using sklearn, numpy and scipy. I am able to parse my database and prepare data-sets. However when coming to prediction and outputting results, I am getting the following error:</p> <p><em>Type Error: 'tuple' object is not callable</em></p> <p>My code is below:</p> <pre><code>from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import SGDClassifier from sklearn import tree from sklearn import gaussian_process from sklearn import neural_network from sklearn import preprocessing from time import time import numpy as np t0 = time() classifier = int(input( """ Enter number corresponding to classifier you would like to use: 1. Support Vector Machines 2. Gaussian Naive Bayes 3. Multinomial Naive Bayes 4. Stochastic Gradient Descent with Logistic Regression loss function """)) dataset = int(input( """ Enter number corresponding to data set you would like to use: 1. First half and second half 2. Alternating 3. Alternating with attack type 4. Alternating with attack type and target type """)) # Assign appropriate datasets input_files = ['half', 'alternating', 'alternating-with-attacktype', 'alternating-all'] filename = input_files[dataset-1] # Instantiate arrays for inputs and outputs train_inputs = [] train_outputs = np.array([]) test_inputs = [] test_expected_outputs = np.array([]) test_actual_outputs = [] X = np.array([]) # Read training file print ('Reading training file') t = time() for line in open('datasets/%s-train.txt' % filename): inputs = line.split(' ') outputs = inputs.pop() train_outputs = np.append(train_outputs, int(outputs)) print ('Done. Time taken: %f secs.\n' % (time()-t)) # for line in open('datasets/%s-train.txt' % filename): # inputs = line.split(' ') # output = inputs.pop() # train_outputs = np.append(train_outputs, int(output)) # print ('Done. Time taken: %f secs.\n' % (time()-t)) print ('Create classifier') t = time() clf = None # No preprocessing for SVMs # Otherwise, scale inputs (preprocessing to make more amenable for machine learning) if classifier == 1: # Support vector machines clf = SVC() elif classifier == 2: # Gaussian Naive Bayes train_inputs = preprocessing.scale(np.array(train_inputs)) clf = GaussianNB() elif classifier == 3: # Multinomial Naive Bayes clf = MultinomialNB() elif classifier == 4: # Stochastic gradient descent with logistic regression train_inputs = preprocessing.scale(np.array(train_inputs)) clf = SGDClassifier(loss='log') print ('Done. Time taken: %f secs.\n' % (time()-t)) print ('Fit classifier') t = time() X.shape(1 -1) clf.fit(train_inputs, train_outputs) print ('Done. Time taken: %f secs.\n' % (time()-t)) # Read test file and scale inputs print ('Reading test file') t = time() for line in open('datasets/%s-test.txt' % filename): inputs = line.split(' ') output = inputs.pop() test_expected_outputs = np.append(test_expected_outputs, int(output)) test_inputs.append(map(float, inputs)) # Same here: no preprocessing for SVMs # Otherwise, scale inputs (preprocessing to make more amenable for machine learning) if classifier != 1: test_inputs = preprocessing.scale(np.array(test_inputs)) print ('Done. Time taken: %f secs.\n' % (time()-t)) print ('Predict for test file') t = time() test_actual_outputs = [clf.predict(i)[0] for i in test_inputs] print ('Done. Time taken: %f secs.\n' % (time()-t)) print ('Compare outputs') t = time() right = sum(test_actual_outputs == test_expected_outputs) wrong = len(test_actual_outputs) - right print ('Done. Time taken: %f secs.\n' % (time()-t)) print ('Number right: %d\nNumber wrong: %d' % (right, wrong)) print ('Prediction rate: %.2f%%' % (100.0 * right/len(test_actual_outputs))) print ('Total time taken: %f secs.\n' % (time()-t0)) </code></pre> <p>I know that I need to add array.reshape(-1 1) or array.reshape(1 -1) but not sure what this will do.</p> <p>Any advice on how to solve this would be welcome. </p>
0debug
EditText inside TextInputLayout onclick requires 2 click ?! Android : <p>I am simply trying to have an onlick listen on an Edit text inside a TextInputLayout. It works but I need to click on the EditText twice for it to trigger I dont understand why. Here is my code:</p> <p>xml:</p> <pre><code> &lt;android.support.design.widget.TextInputLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"&gt; &lt;EditText android:id="@+id/start_date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Starting Date*: " android:inputType="textPersonName" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; </code></pre> <p>Listenner:</p> <pre><code> private void setListenners() { EditText startDate = (EditText) mView.findViewById(R.id.start_date); startDate.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onClick(View v) { Calendar mcurrentDate=Calendar.getInstance(); int mYear = mcurrentDate.get(Calendar.YEAR); int mMonth = mcurrentDate.get(Calendar.MONTH); int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker=new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { Log.d("DEBUG", "year: " + year + " month: " + month + " day: " + day); } },mYear, mMonth, mDay); mDatePicker.show(); } }); } </code></pre>
0debug
static int cmp_intervals(const void *a, const void *b) { const Interval *i1 = a; const Interval *i2 = b; int64_t ts_diff = i1->start_ts - i2->start_ts; int ret; ret = ts_diff > 0 ? 1 : ts_diff < 0 ? -1 : 0; return ret == 0 ? i1->index - i2->index : ret; }
1threat
how to read an MP3 file for audio processing in Delphi? : <p>When I want to process an audio in a byte level, I always convert it in .wav format and then do my processing. For example in my last project, I was trying to generate a kind of special waveform image of my audio file to use it in a video clip. Then I converted my .mp3 file to .wav file (mono, 8 bit, 6KHz) using an online tool and then I maked my waveform picture programmatically.</p> <p>Now I want to be able to do my processing on an .mp3 file directly without conversion, like the code below:</p> <pre><code>aFrom := 60000; // From 00:01:00.000 aLength := 20000; // 20 Second aChannels := 1; // mono aBitsPerChannel := 8; aFreq := 6000; aBufSize := Open_MP3_As('d:\Until The Last Moment.mp3', aBuffer, aFrom, aLength, aChannels, aBitsPerChannel, aFreq); for i := 0 to aBufSize - 1 do begin // Processing aBuffer[i] end; </code></pre> <p>this is just an example of showing what in my mind is. As you can see, the metadata and the details of the .mp3 file is not important for me.</p> <p>This would be very useful because I can embed this ability to my audio tools and let the user use my tools very faster and easier. I know that it could be a very complicated code because at the first time, the .mp3 file must be converted to .wav file (with the specific given parameters), then it must remove the header, slice it and put it in the aBuffer and return the amount of samples in aBuffer.</p>
0debug
React: Use environment variables : <p>How can I use environment variables defined in <code>.bash_profile</code> in a React application? I have two React apps in production (they're the same project, so they have the same code), but they need to request to different API hosts, and I figured env variables could do the trick.</p>
0debug
int32_t HELPER(sdiv)(int32_t num, int32_t den) { if (den == 0) return 0; return num / den; }
1threat
TensorFlow: How can I evaluate a validation data queue multiple times during training? : <h2>tl;dr</h2> <p>How can I evaluate a validation set after every K training iterations, using separate queues for training and validation data, without resorting to separate <code>tf.Sessions</code> in multiple processes? There doesn't seem to be a clean way to achieve this, given my particular problem, and my current workaround (which I thought would work) gives me undefined behavior. Help!</p> <h2>The whole story</h2> <p>I want to evaluate a validation set every K training iterations, and I cannot figure out how to implement this properly in TensorFlow. This should be one of the most common operations, yet it feels that TensorFlow's API/architecture is working against me here or is at least making things unnecessarily difficult.</p> <p>My assumptions are:</p> <ul> <li>[A1] The multi-process model for training/validation as described here <a href="https://www.tensorflow.org/how_tos/reading_data/#multiple_input_pipelines" rel="noreferrer">https://www.tensorflow.org/how_tos/reading_data/#multiple_input_pipelines</a> is not applicable to my problem, as I have to assume there is not enough GPU memory available to load the variables twice.</li> <li>[A2] I want to evaluate on the validation set every K training iterations.</li> <li>[A3] Both training and validation data cannot be simply read from disk, but are generated on-the-fly. This makes it impossible to reliably pre-compute the size of the validation set in advance.</li> <li>[A4] The validation set is too large to pre-compute and store onto disk.</li> <li>[A5] The effective validation set size is not necessarily a multiple of the batch size.</li> </ul> <p>The training input pipeline is set up as follows:</p> <ul> <li>A <code>tf.train.slice_input_producer()</code> generates a (shuffled) list of filenames, each referring to raw input data.</li> <li>A custom data generation function generates a variable number of training exemplars/labels from each chunk of raw input data.</li> <li>The generated training exemplars/labels are queued via <code>tf.train.shuffle_batch()</code> before being fed into the network.</li> </ul> <p>Due to [A3], [A4], [A5], the validation input pipeline is set up in an almost identical way, except that the final input queue is generated via <code>tf.train.batch()</code>, since shuffling is not desirable. Due to the above assumptions, a feed_dict based approach is also infeasible, and also seemingly incompatible with using a higher level function such as <code>tf.train.batch</code>.</p> <p>However, a straightforward implementation using two different sets of queues for training and validation does not work. As far as I understand, I have two options:</p> <ul> <li><p>[B1] Set the <code>num_epochs</code> argument of the validation <code>tf.train.slice_input_producer</code> to <code>None</code>.</p> <p>In this case, the validation set is cycled through endlessly, but I would need to know the size of the validation set in advance to explicitly limit the number of batches to evaluate per run through the validation set. Furthermore, if the validation set size is not divisible by the batch size, I will always pull a bit more in the last batch. As this would shift the order of evaluation of the validation data each time, this is not acceptable.</p></li> <li><p>[B2] Set the <code>num_epochs</code> argument of the validation <code>tf.train.slice_input_producer</code> to <code>1</code>, and additionally set the <code>allow_smaller_final_batch</code> argument of the <code>tf.train.batch</code> function to <code>True</code>.</p> <p>In this case, the validation set is cycled through exactly once, after which the respective queue is closed forever. By default, this will make evaluating the validation set two or more times impossible. Since I do not know of a good way to reopen a queue in TensorFlow, I need to work around this limitation. </p></li> </ul> <p>Due to the greater limitations of option [B1], I chose to work around the issues of option [B2] instead. The (pseudo-)code outlining my current approach is as follows:</p> <p>The training loop should be fairly canonical. Every K iterations, a function to evaluate the validation set is called. Note that I only start the queues that have a name starting with "train_"; these is the queue set up for collecting generated training data. In order to do this, I created two helper functions, <code>get_queues_by_name</code> and <code>start_queue_runners</code>. </p> <pre><code>def train_loop(train_ops, vali_ops, ...): with tf.Session() as sess: coord = tf.train.Coordinator() sess.run([tf.initialize_all_variables(), tf.initialize_local_variables()]) load_latest_snapshot(sess, loader, snapshot_file) # Launch the queue runners queues = get_queues_by_name("train") threads = start_queue_runners(sess, coord, queues) try: for step in range(start_iteration, num_train_iterations): # Runs the session on validation set if step % K == 0: validation_results = run_validation(vali_ops, snapshot_file) # TRAINING: # ... except Exception as e: coord.request_stop(e) finally: coord.request_stop() coord.join(threads) </code></pre> <p>The helper functions look like this:</p> <pre><code>def get_queues_by_name(name): """Retrieves all queues that contain the string given by 'name'""" all_queues = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS) return [q for q in all_queues if name in q.name] def start_queue_runners(session, coordinator, queues): """Similar to tf.train.start_queue_runners but now accepts a list of queues instead of a graph collection""" with session.graph.as_default(): threads = [] for queue in queues: log("Queue", "Starting queue '%s'" % queue.name, level=2) threads.extend(queue.create_threads(session, coordinator, daemon=True, start=True)) return threads </code></pre> <p>In the <code>run_validation</code> function, my chosen workaround against the issue of a closed queue is to create a new <code>tf.Session</code>. I also only start the threads associated with the queue collecting validation set data.</p> <pre><code>def run_validation(ops, snapshot_file): # Called inside train_loop() results = None loader = tf.train.Saver() with tf.Session() as sess: coord = tf.train.Coordinator() sess.run([tf.initialize_local_variables()]) load_latest_snapshot(sess, loader, snapshot_file) # Launch the queue runners queues = get_queues_by_name("eval") threads = start_queue_runners(sess, coord, queues) # Performs the inference in batches try: # Evaluate validation set: results = eval_in_batches(ops, sess) except Exception as e: coord.request_stop(e) finally: coord.request_stop() coord.join(threads) return results </code></pre> <p>I do not know whether creating a new <code>tf.Session</code> here is a good idea, but it seems like the only way to accomplish restarting the validation queue. Ideally, I also wouldn't want to re-load the model snapshot, as this seems conceptually unnecessary.</p> <p>The issue with this code is that I see erratic/undefined behavior during running, such as NaN's or Inf's appearing inside the network during validation set evaluation. This seems to occur predominantly when the validation set queue is being filled at the same time as the training set queue is still being filled (since the training queue is open during validation set evaluation). For example, this very often happens if I evaluate the validation set at iteration 0 (when both queues still need to be filled). It almost seems as if the training/validation queues share some global state, although they are running in a different session.</p> <p>Can someone explain why this is happening, and how I can solve this more cleanly while taking my above assumptions [A1]-[A5] into account?</p>
0debug
MVC5 Multiple types were found that match the controller named 'Home' : <p>I was trying to clone a project called IdentitySample but I wanted to rename it to RecreationalServicesTicketingSystem. I've followed a few guides as to how to rename everything but it seems the application is still picking up <code>IdentitySample.Controllers.HomeController</code> . I've tried using the find function to look through codes to see if IdentitySample was still in our application but I've found none.</p> <p>Can give me a few pointers as too where I might have missed renaming the solution?</p> <blockquote> <p>Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.</p> <p>The request for 'Home' has found the following matching controllers: RecreationalServicesTicketingSystem.Controllers.HomeController IdentitySample.Controllers.HomeController</p> </blockquote> <p><a href="https://i.stack.imgur.com/FF8kk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FF8kk.png" alt="enter image description here"></a></p> <p>HomeController.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using RecreationalServicesTicketingSystem.Models; namespace RecreationalServicesTicketingSystem.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [Authorize] public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } } </code></pre> <p>View\Home\Index.cshtml</p> <pre><code>@{ ViewBag.Title = "Home Page"; } &lt;div class="jumbotron"&gt; &lt;h1&gt;ASP.NET Identity&lt;/h1&gt; &lt;p class="lead"&gt;ASP.NET Identity is the membership system for ASP.NET apps. Following are the features of ASP.NET Identity in this sample application.&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.asp.net/identity" class="btn btn-primary btn-large"&gt;Learn more &amp;raquo;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Initialize ASP.NET Identity&lt;/dt&gt; &lt;dd&gt; You can initialize ASP.NET Identity when the application starts. Since ASP.NET Identity is Entity Framework based in this sample, you can create DatabaseInitializer which is configured to get called each time the app starts. &lt;strong&gt;Please look in App_Start\IdentityConfig.cs&lt;/strong&gt; This code shows the following &lt;ul&gt; &lt;li&gt;When should the Initializer run and when should the database be created&lt;/li&gt; &lt;li&gt;Create Admin user&lt;/li&gt; &lt;li&gt;Create Admin role&lt;/li&gt; &lt;li&gt;Add Admin user to Admin role&lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Add profile data for the user&lt;/dt&gt; &lt;dd&gt; &lt;a href="http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx"&gt;Please follow this tutorial.&lt;/a&gt; &lt;ul&gt; &lt;li&gt;Add profile information in the Users Table&lt;/li&gt; &lt;li&gt;Look in Models\IdentityModels.cs for examples&lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Validation&lt;/dt&gt; &lt;dd&gt; When you create a User using a username or password, the Identity system performs validation on the username and password, and the passwords are hashed before they are stored in the database. You can customize the validation by changing some of the properties of the validators such as Turn alphanumeric on/off, set minimum password length or you can write your own custom validators and register them with the UserManager. &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Register a user and login&lt;/dt&gt; &lt;dd&gt; Click @Html.ActionLink("Register", "Register", "Account") and see the code in AccountController.cs and Register Action. Click @Html.ActionLink("Log in", "Login", "Account") and see the code in AccountController.cs and Login Action. &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Social Logins&lt;/dt&gt; &lt;dd&gt; You can the support so that users can login using their Facebook, Google, Twitter, Microsoft Account and more. &lt;/dd&gt; &lt;dd&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="http://www.windowsazure.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/"&gt;Add Social Logins&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx"&gt;Get more data about the user when they login suing Facebook&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Basic User Management&lt;/dt&gt; &lt;dd&gt; Do Create, Update, List and Delete Users. Assign a Role to a User. Only Users In Role Admin can access this page. This uses the [Authorize(Roles = "Admin")] on the UserAdmin controller. &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Basic Role Management&lt;/dt&gt; &lt;dd&gt; Do Create, Update, List and Delete Roles. Only Users In Role Admin can access this page. This authorization is doen by using the [Authorize(Roles = "Admin")] on the RolesAdmin controller. &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Account Confirmation&lt;/dt&gt; &lt;dd&gt; When you register a new account, you will be sent an email confirmation. You can use an email service such as &lt;a href="http://www.windowsazure.com/en-us/documentation/articles/sendgrid-dotnet-how-to-send-email/"&gt;SendGrid&lt;/a&gt; which integrate nicely with Windows Azure and requires no configuration or set up an SMTP server to send email. You can send email using the EmailService which is registered in App_Start\IdentityConfig.cs &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Two-Factor Authentication&lt;/dt&gt; &lt;dd&gt; This sample shows how you can use Two-Factor authentication. This sample has a SMS and email service registered where you can send SMS or email for sending the security code. You can add more two-factor authentication factors such as QR codes and plug them into ASP.NET Identity. &lt;ul&gt; &lt;li&gt; You can use a SMS using &lt;a href="https://www.twilio.com/"&gt;Twilio&lt;/a&gt; or use any means of sending SMS. Please &lt;a href="https://www.twilio.com/docs/quickstart/csharp/sms/sending-via-rest"&gt;read&lt;/a&gt; for more details on using Twilio. You can send SMS using the SmsService which is registered in App_Start\IdentityConfig.cs &lt;/li&gt; &lt;li&gt; You can use an email service such as &lt;a href="http://www.windowsazure.com/en-us/documentation/articles/sendgrid-dotnet-how-to-send-email/"&gt;SendGrid&lt;/a&gt; or set up an SMTP server to send email. You can send email using the EmailService which is registered in App_Start\IdentityConfig.cs &lt;/li&gt; &lt;li&gt; When you login, you can add a phone number by clicking the Manage page. &lt;/li&gt; &lt;li&gt; Once you add a phone number and have the Phone service hooked to send a SMS, you will get a code through SMS to confirm your phone number. &lt;/li&gt; &lt;li&gt; In the Manage page, you can turn on Two-Factor authentication. &lt;/li&gt; &lt;li&gt; When you logout and login, after you enter the username and password, you will get an option of how to get the security code to use for two-factor authentication. &lt;/li&gt; &lt;li&gt; You can copy the code from your SMS or email and enter in the form to login. &lt;/li&gt; &lt;li&gt; The sample also shows how to protect against Brute force attacks against two-factor codes. When you enter a code incorrectly for 5 times then you will be lockedout for 5 min before you can enter a new code. These settings can be configured in App_Start\IdentityConfig.cs by setting DefaultAccountLockoutTimeSpan and MaxFailedAccessAttemptsBeforeLockout on the UserManager. &lt;/li&gt; &lt;li&gt; If the machine you are browsing this website is your own machine, you can choose to check the "Remember Me" option after you enter the code. This option will remember you forever on this machine and will not ask you for the two-factor authentication, the next time when you login to the website. You can change your "Remember Me" settings for two-factor authentication in the Manage page. &lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Account Lockout&lt;/dt&gt; &lt;dd&gt; Provide a way to Lockout out the user if the user enters their password or two-factor codes incorrectly. The number of invalid attempts and the timespan for the users are locked out can be configured. A developer can optionally turn off Account Lockout for certain user accounts should they need to. &lt;/dd&gt; &lt;ul&gt; &lt;li&gt;Account LockOut settings can be configured in the UserManager in IdentityConfig.cs&lt;/li&gt; &lt;/ul&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Security Token provider&lt;/dt&gt; &lt;dd&gt; Support a way to regenerate the Security Token for the user in cases when the User changes there password or any other security related information such as removing an associated login(such as Facebook, Google, Microsoft Account etc). This is needed to ensure that any tokens generated with the old password are invalidated. In the sample project, if you change the users password then a new token is generated for the user and any previous tokens are invalidated. This feature provides an extra layer of security to your application since when you change your password, you will be logged out from everywhere (all other browsers) where you have logged into this application. &lt;/dd&gt; &lt;dd&gt; &lt;ul&gt; &lt;li&gt;The provider is registered when you add CookieAuthentication in StartupAuth to your application.&lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Password Reset&lt;/dt&gt; &lt;dd&gt; Allows the user to reset their passwords if they have forgotten their password. In this sample users need to confirm their email before they can reset their passwords. &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Custom Storage providers&lt;/dt&gt; &lt;dd&gt; You can extend ASP.NET Identity to write your own custom storage provider for storing the ASP.NET Identity system and user data in a persistance system of your choice such as MondoDb, RavenDb, Azure Table Storage etc. &lt;/dd&gt; &lt;dd&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="http://www.asp.net/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity"&gt; learn more on how to implement your own storage provider &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;dl&gt; &lt;dt&gt;Documentation&lt;/dt&gt; &lt;dd&gt; &lt;ul&gt; &lt;li&gt; Tutorials: &lt;a href="www.asp.net/identity"&gt;www.asp.net/identity&lt;/a&gt; &lt;/li&gt; &lt;li&gt; StackOverflow: &lt;a href="http://stackoverflow.com/questions/tagged/asp.net-identity"&gt;http://stackoverflow.com/questions/tagged/asp.net-identity&lt;/a&gt; &lt;/li&gt; &lt;li&gt; Twitter: #identity #aspnet &lt;/li&gt; &lt;li&gt; &lt;a href="http://curah.microsoft.com/55636/aspnet-identity"&gt;ASP.NET Identity on curah&lt;/a&gt; &lt;/li&gt; &lt;li&gt; Have bugs or suggestions for ASP.NET Identity &lt;a href="http://aspnetidentity.codeplex.com/"&gt;http://aspnetidentity.codeplex.com/&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
0debug
static av_cold int asv_encode_close(AVCodecContext *avctx) { av_frame_free(&avctx->coded_frame); return 0; }
1threat
phpmyadmin - count(): Parameter must be an array or an object that implements Countable : <p>I've uploaded the backup to a table, opening the table I see this:</p> <pre><code>Warning in ./libraries/sql.lib.php#601 count(): Parameter must be an array or an object that implements Countable Backtrace ./libraries/sql.lib.php#2038: PMA_isRememberSortingOrder(array) ./libraries/sql.lib.php#1984: PMA_executeQueryAndGetQueryResponse( array, boolean true, string 'alternativegirls', string 'tgp_photo', NULL, NULL, NULL, NULL, NULL, NULL, string '', string './themes/pmahomme/img/', NULL, NULL, NULL, string 'SELECT * FROM `tgp_photo`', NULL, NULL, ) ./sql.php#216: PMA_executeQueryAndSendQueryResponse( array, boolean true, string 'alternativegirls', string 'tgp_photo', NULL, NULL, NULL, NULL, NULL, NULL, string '', string './themes/pmahomme/img/', NULL, NULL, NULL, string 'SELECT * FROM `tgp_photo`', NULL, NULL, ) ./index.php#53: include(./sql.php) </code></pre> <p>Inside phpMyAdmin...</p> <p>PHP is 7.2, the server is Ubuntu 16.04, installed yesterday.</p> <p>Looking for I saw that some have this error in their code, but I did not find anyone who received it in phpMyAdmin...</p> <p>What should I do? Is that my error? A phpmyadmin error? wait update ? I go back to PHP 7.1?</p>
0debug
How to add style to webp images : <p>my code looks like</p> <pre><code>&lt;picture&gt; &lt;source type="image/webp" srcset="img/photo.webp"&gt; &lt;source type="image/jpg" srcset="img/photo.jpg"&gt; &lt;img src="img/photo.jpg" alt=""&gt; &lt;/picture &gt; </code></pre> <p>I want to add class to this picture so I can use border-radius. how can I do that?</p>
0debug
Need a help on truncating : <p>Hellow Guys,</p> <p>I need to give an idea on a simple program.</p> <p>Write a function which shortens a string to n characters. If the string is already shorter than n, the function should not change the string. Assume the prototype is</p> <pre><code>void truncate(char *str, int inLen); </code></pre> <p>just give a simple explanation ..</p> <p>Thanks</p>
0debug
static void init_proc_750gx (CPUPPCState *env) { gen_spr_ne_601(env); gen_spr_7xx(env); spr_register(env, SPR_L2CR, "L2CR", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, NULL, 0x00000000); gen_tbl(env); gen_spr_thrm(env); spr_register(env, SPR_750_THRM4, "THRM4", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, 0x00000000); spr_register(env, SPR_HID0, "HID0", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, 0x00000000); spr_register(env, SPR_HID1, "HID1", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, 0x00000000); spr_register(env, SPR_750FX_HID2, "HID2", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, 0x00000000); gen_low_BATs(env); gen_high_BATs(env); init_excp_7x0(env); env->dcache_line_size = 32; env->icache_line_size = 32; ppc6xx_irq_init(env); }
1threat
int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs) { BlockDriverAIOCB *acb; MultiwriteCB *mcb; int i; if (num_reqs == 0) { return 0; } mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks)); mcb->num_requests = 0; mcb->num_callbacks = num_reqs; for (i = 0; i < num_reqs; i++) { mcb->callbacks[i].cb = reqs[i].cb; mcb->callbacks[i].opaque = reqs[i].opaque; } num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb); for (i = 0; i < num_reqs; i++) { acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov, reqs[i].nb_sectors, multiwrite_cb, mcb); if (acb == NULL) { if (mcb->num_requests == 0) { reqs[i].error = -EIO; goto fail; } else { mcb->error = -EIO; break; } } else { mcb->num_requests++; } } return 0; fail: free(mcb); return -1; }
1threat
static int ffmmal_fill_input_port(AVCodecContext *avctx) { MMALDecodeContext *ctx = avctx->priv_data; while (ctx->waiting_buffers) { MMAL_BUFFER_HEADER_T *mbuffer; FFBufferEntry *buffer; MMAL_STATUS_T status; mbuffer = mmal_queue_get(ctx->pool_in->queue); if (!mbuffer) return 0; buffer = ctx->waiting_buffers; mmal_buffer_header_reset(mbuffer); mbuffer->cmd = 0; mbuffer->pts = buffer->pts; mbuffer->dts = buffer->dts; mbuffer->flags = buffer->flags; mbuffer->data = buffer->data; mbuffer->length = buffer->length; mbuffer->user_data = buffer->ref; mbuffer->alloc_size = ctx->decoder->input[0]->buffer_size; if ((status = mmal_port_send_buffer(ctx->decoder->input[0], mbuffer))) { mmal_buffer_header_release(mbuffer); av_buffer_unref(&buffer->ref); } ctx->waiting_buffers = buffer->next; if (ctx->waiting_buffers_tail == buffer) ctx->waiting_buffers_tail = NULL; av_free(buffer); if (status) { av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending input\n", (int)status); return AVERROR_UNKNOWN; } } return 0; }
1threat
How to setup mysql with utf-8 using docker compose? : <p>I am trying to get my mysql image running with utf-8 encoding. My docker-compose file looks like:</p> <pre><code>version: '2' services: db: container_name: zoho-grabber-db-development image: mysql:5.7 environment: - MYSQL_ROOT_PASSWORD=topsecret - MYSQL_DATABASE=development - MYSQL_USER=devuser - MYSQL_PASSWORD=secure ports: - "3306:3306" command: mysqld --character-set-server=utf8 --collation-server=utf8_general_ci </code></pre> <p>When i run it, it says</p> <pre><code>$ docker-compose -f docker-compose.development.yml up Removing zoho-grabber-db-development Recreating 1b341fd7916e_1b341fd7916e_zoho-grabber-db-development ERROR: for db Cannot start service db: oci runtime error: container_linux.go:247: starting container process caused "exec: \"mysqld\": executable file not found in $PATH" ERROR: Encountered errors while bringing up the project. </code></pre> <p>Why is mysqld not found? And how to achieve my goal?</p>
0debug
I cant connect to sql server : I cant connect to sql server using vb.net. Here is the code Imports system.data.sqlclient PUBLIC CLASS- customer typer Dim connectionstring as string = "data source = wisdon; initial catalog = stock_management; user id = sa; password = managerz " Dim mycommand as new sqlcommand Dim myconnection = new sqlcomma d (connectionstring) PRIVATE SUB CUSTOMER_BT dim sqlstr as string Sqlstr = (" insert into customer_type(customer_type) value" - &"(' " & customertyper_txt.text & " ') Mycommand = new sqlclient.sqlcommand (sqlstr, myconnection) Mycommand.executeNonQuery () Myconnection.close Customer_type is the button i am writing the code Customertype_txt is the textbox
0debug
What is a fast and proper way to refresh/update plots in Bokeh (0.11) server app? : <p>I have a bokeh (v0.11) serve app that produces a scatter plot using (x,y) coordinates from a data frame. I want to add interactions such that when a user either selects points on the plot or enters the name of comma-separated points in the text box (ie. "p55, p1234"), then those points will turn red on the scatter plot. </p> <p>I have found one way to accomplish this (Strategy #3, below) but it is terribly slow for large dataframes. I would think there is a better method. Can anyone help me out? Am I missing some obvious function call?</p> <ul> <li><strong>Strategy 1</strong> (&lt;1ms for 100 points) drills into the ColumnDataSource data for the exist plot and attempts to change the selected points. </li> <li><strong>Strategy 2</strong> (~70ms per 100 points) overwrites the plot's existing ColumnDataSource with a newly created ColumnDataSource. </li> <li><strong>Strategy 3</strong> (~400ms per 100 points) is Strategy 2 and then it re-creates the figure.</li> </ul> <p>Code is deposited on pastebin: <a href="http://pastebin.com/JvQ1UpzY">http://pastebin.com/JvQ1UpzY</a> Most relevant portion is copied below.</p> <pre><code>def refresh_graph(self, selected_points=None, old_idxs=None, new_idxs=None): # Strategy 1: Cherry pick current plot's source. # Compute time for 100 points: &lt; 1ms. if self.strategy == 1: t1 = datetime.now() for idx in old_idxs: self.graph_plot.data_source.data['color'][idx] = 'steelblue' for idx in new_idxs: self.graph_plot.data_source.data['color'][idx] = 'red' print('Strategy #1 completed in {}'.format(datetime.now() - t1)) else: t3 = datetime.now() self.coords['color'] = 'steelblue' self.coords.loc[selected_points, 'color'] = 'red' new_source = bkmodels.ColumnDataSource(self.coords) self.graph_plot = self.graph_fig.scatter('x', 'y', source=new_source, color='color', alpha=0.6) print('Strategy #3 completed in {}'.format(datetime.now() - t3)) return </code></pre> <p>Ideally, I would like to be able to use <strong>Strategy #1</strong>, but it does not seem to allow the points to refresh within the client browser.</p> <p>Thanks for any help!</p> <p>FYI: I am using RHEL 6.X</p>
0debug
validation for +1(320)-924-2043 phone number in laravel regex rule : i have written like this regex:/^\+1\(?([0-9]{3})\)-[0-9]{3}-[0-9]{4}$/ but it's not working
0debug
Hash Table vs Dictonary : As far as I know hash table uses has key to store any item whereas dictionary uses simple key value pair to store item.it means that dictionary is a lot faster than hash table . **Does this mean i should never use hash table.**
0debug
static void test_visitor_in_union_flat(TestInputVisitorData *data, const void *unused) { Visitor *v; Error *err = NULL; UserDefFlatUnion *tmp; UserDefUnionBase *base; v = visitor_input_test_init(data, "{ 'enum1': 'value1', " "'integer': 41, " "'string': 'str', " "'boolean': true }"); visit_type_UserDefFlatUnion(v, &tmp, NULL, &err); g_assert(err == NULL); g_assert_cmpint(tmp->enum1, ==, ENUM_ONE_VALUE1); g_assert_cmpstr(tmp->string, ==, "str"); g_assert_cmpint(tmp->integer, ==, 41); g_assert_cmpint(tmp->u.value1->boolean, ==, true); base = qapi_UserDefFlatUnion_base(tmp); g_assert(&base->enum1 == &tmp->enum1); qapi_free_UserDefFlatUnion(tmp); }
1threat
Im getting error "deprecated pixel format used, make sure you did set range correctly using ffmpeg".. can someone check my code below? : <p>This is my code using ffmpeg i want to have video thumbnail but im not familiar in ffmpeg can someone know the error i got.</p> <pre><code>[swscaler @ 0x7ff8da028c00] deprecated pixel format used, make sure you did set range correctly Output #0, mjpeg, to 'image.jpg': Metadata: major_brand : mp42 minor_version : 0 compatible_brands: isommp42 encoder : Lavf56.36.100 Stream #0:0(und): Video: mjpeg, yuvj420p(pc), 320x240 [SAR 4:3 DAR 16:9], q=2-31, 200 kb/s, 1 fps, 1 tbn, 1 tbc (default) Metadata: creation_time : 2016-11-06 09:40:22 handler_name : ISO Media file produced by Google Inc. encoder : Lavc56.41.100 mjpeg Stream mapping: Stream #0:0 -&gt; #0:0 (h264 (native) -&gt; mjpeg (native)) Press [q] to stop, [?] for help frame= 1 fps=0.0 q=4.8 Lsize= 16kB time=00:00:01.00 bitrate= 129.5kbits/s video:16kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.000000% </code></pre> <p>Also This is my code:</p> <pre><code>$video_url ='https://URL/upload/4b8acab123563649f19e07450d810df6.mp4'; $ffmpeg = '/opt/local/bin/ffmpeg'; $image = 'image.jpg'; $interval = 5; $size = '320x240'; shell_exec($tmp = "$ffmpeg -i $video_url -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $image 2&gt;&amp;1"); </code></pre>
0debug
Elasticsearch cluster 'master_not_discovered_exception' : <p>i have installed elasticsearch 2.2.3 and configured in cluster of 2 nodes</p> <p>Node 1 (elasticsearch.yml)</p> <pre><code>cluster.name: my-cluster node.name: node1 bootstrap.mlockall: true discovery.zen.ping.unicast.hosts: ["ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com", "ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com"] discovery.zen.minimum_master_nodes: 1 discovery.zen.ping.multicast.enabled: false indices.fielddata.cache.size: "30%" indices.cache.filter.size: "30%" node.master: true node.data: true http.cors.enabled: true script.inline: false script.indexed: false network.bind_host: 0.0.0.0 </code></pre> <p>Node 2 (elasticsearch.yml)</p> <pre><code>cluster.name: my-cluster node.name: node2 bootstrap.mlockall: true discovery.zen.ping.unicast.hosts: ["ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com", "ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com"] discovery.zen.minimum_master_nodes: 1 discovery.zen.ping.multicast.enabled: false indices.fielddata.cache.size: "30%" indices.cache.filter.size: "30%" node.master: false node.data: true http.cors.enabled: true script.inline: false script.indexed: false network.bind_host: 0.0.0.0 </code></pre> <p>If i get <code>curl -XGET 'http://localhost:9200/_cluster/state?pretty'</code> i have:</p> <pre><code>{ "error" : { "root_cause" : [ { "type" : "master_not_discovered_exception", "reason" : null } ], "type" : "master_not_discovered_exception", "reason" : null }, "status" : 503 } </code></pre> <p>Into log of node 1 have:</p> <pre><code>[2016-06-22 13:33:56,167][INFO ][cluster.service ] [node1] new_master {node1}{Vwj4gI3STr6saeTxKkSqEw}{127.0.0.1}{127.0.0.1:9300}{master=true}, reason: zen-disco-join(elected_as_master, [0] joins received) [2016-06-22 13:33:56,210][INFO ][http ] [node1] publish_address {127.0.0.1:9200}, bound_addresses {[::]:9200} [2016-06-22 13:33:56,210][INFO ][node ] [node1] started [2016-06-22 13:33:56,221][INFO ][gateway ] [-node1] recovered [0] indices into cluster_state </code></pre> <p>Into log of node 2 instead:</p> <pre><code>[2016-06-22 13:34:38,419][INFO ][discovery.zen ] [node2] failed to send join request to master [{node1}{Vwj4gI3STr6saeTxKkSqEw}{127.0.0.1}{127.0.0.1:9300}{master=true}], reason [RemoteTransportException[[node2][127.0.0.1:9300][internal:discovery/zen/join]]; nested: IllegalStateException[Node [{node2}{_YUbBNx9RUuw854PKFe1CA}{127.0.0.1}{127.0.0.1:9300}{master=false}] not master for join request]; ] </code></pre> <p>Where the error?</p>
0debug
ISADevice *pc_find_fdc0(void) { int i; Object *container; CheckFdcState state = { 0 }; for (i = 0; i < ARRAY_SIZE(fdc_container_path); i++) { container = container_get(qdev_get_machine(), fdc_container_path[i]); object_child_foreach(container, check_fdc, &state); } if (state.multiple) { error_report("warning: multiple floppy disk controllers with " "iobase=0x3f0 have been found"); error_printf("the one being picked for CMOS setup might not reflect " "your intent\n"); } return state.floppy; }
1threat
Android : Add 4 views to 4 corners programatically using ALIGN_PARENT : I am trying to add 4 views to 4 corners of the screen programatically, But its not working as required. Kindly help me. View[] TchBoxAryVar = new View[4]; int LyoRulAryVar[] = {RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.ALIGN_PARENT_TOP | RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.ALIGN_PARENT_BOTTOM | RelativeLayout.ALIGN_PARENT_RIGHT}; int ClrAryVar[] = {Color.RED, Color.GREEN, Color.GRAY, Color.MAGENTA}; for(int IdxVal = 0; IdxVal < TchBoxAryVar.length; IdxVal++) { Log.d("TAG", "onCreate: " + IdxVal); TchBoxAryVar[IdxVal] = new View(this); RelativeLayout.LayoutParams LyoRulVar = new RelativeLayout.LayoutParams(200, 200); LyoRulVar.addRule(LyoRulAryVar[IdxVal]); TchBoxAryVar[IdxVal].setLayoutParams(LyoRulVar); TchBoxAryVar[IdxVal].setBackgroundColor(ClrAryVar[IdxVal]); MainViewVav.addView(TchBoxAryVar[IdxVal]); }
0debug
void ff_snow_vertical_compose97i_sse2(IDWTELEM *b0, IDWTELEM *b1, IDWTELEM *b2, IDWTELEM *b3, IDWTELEM *b4, IDWTELEM *b5, int width){ long i = width; while(i & 0x1F) { i--; b4[i] -= (W_DM*(b3[i] + b5[i])+W_DO)>>W_DS; b3[i] -= (W_CM*(b2[i] + b4[i])+W_CO)>>W_CS; b2[i] += (W_BM*(b1[i] + b3[i])+4*b2[i]+W_BO)>>W_BS; b1[i] += (W_AM*(b0[i] + b2[i])+W_AO)>>W_AS; } asm volatile ( "jmp 2f \n\t" "1: \n\t" "mov %6, %%"REG_a" \n\t" "mov %4, %%"REG_S" \n\t" snow_vertical_compose_sse2_load(REG_S,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_add(REG_a,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_move("xmm0","xmm2","xmm4","xmm6","xmm1","xmm3","xmm5","xmm7") snow_vertical_compose_sse2_sra("1","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_r2r_add("xmm1","xmm3","xmm5","xmm7","xmm0","xmm2","xmm4","xmm6") "pcmpeqd %%xmm1, %%xmm1 \n\t" "psllw $15, %%xmm1 \n\t" "psrlw $14, %%xmm1 \n\t" "mov %5, %%"REG_a" \n\t" snow_vertical_compose_sse2_r2r_add("xmm1","xmm1","xmm1","xmm1","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_sra("2","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_load(REG_a,"xmm1","xmm3","xmm5","xmm7") snow_vertical_compose_sse2_sub("xmm0","xmm2","xmm4","xmm6","xmm1","xmm3","xmm5","xmm7") snow_vertical_compose_sse2_store(REG_a,"xmm1","xmm3","xmm5","xmm7") "mov %3, %%"REG_c" \n\t" snow_vertical_compose_sse2_load(REG_S,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_add(REG_c,"xmm1","xmm3","xmm5","xmm7") snow_vertical_compose_sse2_sub("xmm1","xmm3","xmm5","xmm7","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_store(REG_S,"xmm0","xmm2","xmm4","xmm6") "mov %2, %%"REG_a" \n\t" snow_vertical_compose_sse2_add(REG_a,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_sra("2","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_add(REG_c,"xmm0","xmm2","xmm4","xmm6") "pcmpeqd %%xmm1, %%xmm1 \n\t" "psllw $15, %%xmm1 \n\t" "psrlw $14, %%xmm1 \n\t" "mov %1, %%"REG_S" \n\t" snow_vertical_compose_sse2_r2r_add("xmm1","xmm1","xmm1","xmm1","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_sra("2","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_add(REG_c,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_store(REG_c,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_add(REG_S,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_move("xmm0","xmm2","xmm4","xmm6","xmm1","xmm3","xmm5","xmm7") snow_vertical_compose_sse2_sra("1","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_r2r_add("xmm1","xmm3","xmm5","xmm7","xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_add(REG_a,"xmm0","xmm2","xmm4","xmm6") snow_vertical_compose_sse2_store(REG_a,"xmm0","xmm2","xmm4","xmm6") "2: \n\t" "sub $32, %%"REG_d" \n\t" "jge 1b \n\t" :"+d"(i) : "m"(b0),"m"(b1),"m"(b2),"m"(b3),"m"(b4),"m"(b5): "%"REG_a"","%"REG_S"","%"REG_c""); }
1threat
Can't erase digits from c++ string by using the 'erase' function : <p>Using c++ 14. I'm prompting the user for a string containing both letters and integers, and trying to "strip" the integers from the string itself via the string.erase() function.</p> <p>The problem i'm facing is when there are 2 or more sequential numbers, than the function seems to erase the first but delete the latter.</p> <p><strong>Example:</strong></p> <pre><code> input: H23ey Th2e3re St01ack O34verflow output: H3ey There St1ack O4verflow </code></pre> <p>I can do it another way by using a new string, looping through the existing one and adding only what isalpha or isspace, but it seems messier.</p> <p><strong>code:</strong></p> <pre><code>string digalpha {}; cout &lt;&lt; "Enter string containing both numbers and letters: "; getline(cin, digalpha); for (size_t i {}; i &lt; digalpha.size(); i++) if (isdigit(digalpha.at(i))) digalpha.erase(i,1); cout &lt;&lt; digalpha &lt;&lt; endl; cout &lt;&lt; endl; return 0; </code></pre>
0debug
Finding Day for given Date : I have worked with a simple C program to find the Day for Given Date. For it I have wrote lot of lines to calculate the day and month and to find the kind of the given year. While Surfing I came to know about a single line code to find the day for given date. The code is as below ( d += m < 3 ? y --: y- 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7 ; // 0 - Sunday, 6 - saturday It gave correct answer for all inputs, but I couldn't understand the values used in this expression. 1. Why the sum of day and month is checked for less than 3. 2. Why the year is reduced by one and the condition fails it decreases the year by 2. 3. Why the number 3, 23 and 9 are used in this expression. Please let me know what is the logic behind this, I'm tried of seacrching the solutions.
0debug
I'm just beginning to learn C: Can someone explain what the pointers and typecasting are doing in this code? : <p>//Beginning of a Function:</p> <pre><code>char *encrypt(char *string, size_t length) { } </code></pre> <p>I am beginning a simple encryption function, and I'm wondering what exactly the above code is carrying out? I am assuming I'm initializing an encrypt function as char pointer, with a memory destination 'string' and size of 'length'</p> <p>Am I correct?</p>
0debug
How to save canvas animation as gif or webm? : <p>i have written this function to capture each frame for the GIF but the output is very laggy and crashes when the data increases. Any suggestions ?</p> <p>Code :</p> <pre><code> function createGifFromPng(list, framerate, fileName, gifScale) { gifshot.createGIF({ 'images': list, 'gifWidth': wWidth * gifScale, 'gifHeight': wHeight * gifScale, 'interval': 1 / framerate, }, function(obj) { if (!obj.error) { var image = obj.image; var a = document.createElement('a'); document.body.append(a); a.download = fileName; a.href = image; a.click(); a.remove(); } }); } ///////////////////////////////////////////////////////////////////////// function getGifFromCanvas(renderer, sprite, fileName, gifScale, framesCount, framerate) { var listImgs = []; var saving = false; var interval = setInterval(function() { renderer.extract.canvas(sprite).toBlob(function(b) { if (listImgs.length &gt;= framesCount) { clearInterval(interval); if (!saving) { createGifFromPng(listImgs, framerate, fileName,gifScale); saving = true; } } else { listImgs.push(URL.createObjectURL(b)); } }, 'image/gif'); }, 1000 / framerate); } </code></pre>
0debug
game with moving balls doesn't work with javascript : <p>I created this game using javascript and sublime. In theory I should visualize two balls moving around the canvas but actually I see only one yellow ball stopped in the middle of the canvas. Why the ball doesn't move?</p> <p>This is the code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Canvas Tutorial&lt;/title&gt; &lt;script type="text/javascript"&gt; window.onload = draw; function draw() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "black"; ctx.fillRect(0, 0, 400, 300); ctx.fillStyle = "yellow"; ctx.beginPath(); for (var i = 0; i &lt; circles.length; i++) { ctx.arc(circles[i].x, circles[i].y, circles[i].r, 0, Math.PI * 2, false); ctx.fill(); if ((circles[i].y &gt; 300 - circles[i].r) &amp;&amp; circles[i].direction === 1) { circles[i].direction = 2; } else if ((circles[i].x &gt; 400 - circles[i].r) &amp;&amp; (circles[i].direction === 2)) { circles[i].direction = 3; } else if ((circles[i].y &gt; 300 - circles[i].r) &amp;&amp; (circles[i].direction === 4)) { circles[i].direction = 3; } else if ((circles[i].y &lt;= circles[i].r) &amp;&amp; circles[i].direction === 3) { circles[i].direction = 4; } else if ((circles[i].x &lt; circles[i].r) &amp;&amp; circles[i].direction === 4) { circles[i].direction = 1; } else if ((circles[i].y &lt; circles[i].r) &amp;&amp; circles[i].direction === 2) { circles[i].direction = 1; } if (circles[i].direction === 1) { circles[i].x += circles[i].speedX; circles[i].y += circles[i].speedY; } else if (circles[i].direction === 2) { circles[i].x += circles[i].speedX; circles[i].y -= circles[i].speedY; } else if (circles[i].direction === 3) { circles[i].x -= circles[i].speedX; circles[i].y -= circles[i].speedY; } else { circles[i].x -= circles[i].speedX; circles[i].y += circles[i].speedY; } } } var circles = [{ x: 200, y: 150, r: 40, direction: 1, speedX: 1, speedY: 2 }, { x: 200, y: 150, r: 70, direction: 1, speedX: 2, speedY: 1 }]; setTimeout(draw, 10); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="canvas" width="400" height="300"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0debug
What is the required programming language to develop Wordpress Templates? : <p>i want to know that which is the best programming language to develop Wordpress Templates?</p>
0debug
static int config_input_props(AVFilterLink *inlink) { AVFilterContext *ctx = inlink->dst; Frei0rContext *s = ctx->priv; if (!(s->instance = s->construct(inlink->w, inlink->h))) { av_log(ctx, AV_LOG_ERROR, "Impossible to load frei0r instance"); return AVERROR(EINVAL); } return set_params(ctx, s->params); }
1threat
Incorrect path file reference to packages when sharing solution between mac and windows : <p>I have solution/flutter app running on <strong>windows</strong> fine. Within the .packages file vscode is referencing the package via </p> <pre><code>analyzer:file:///c:/flutter/.pub-cache/hosted/pub.dartlang.org/analyzer-0.31.2-alpha.2/lib/ args:file:///c:/flutter/.pub-cache/hosted/pub.dartlang.org/args-1.4.3/lib/ async:file:///c:/flutter/.pub-cache/hosted/pub.dartlang.org/async-2.0.7/lib/ ... </code></pre> <p>I have the flutter sdk installed c:\flutter directory on windows.</p> <p>I copied this solution via dropbox to the <strong>mac</strong> and when running </p> <p>"Warning! This package referenced a Flutter repository via the .packages file that is no longer available". </p> <p>In an effort to isolate/locate the problem, I created a new Flutter project on the mac and found that the .packages file referenced packages via </p> <pre><code>analyzer:file:///flutter/.pub-cache/hosted/pub.dartlang.org/analyzer-0.31.2-alpha.2/lib/ args:file:///flutter/.pub-cache/hosted/pub.dartlang.org/args-1.4.3/lib/ async:file:///flutter/.pub-cache/hosted/pub.dartlang.org/async-2.0.7/lib/ ... </code></pre> <p><strong>Notice</strong> the different paths used on both systems.</p> <p>I suspect I can search/replace the references file:///c:/flutter to file:///flutter and it should work but I would like to avoid always manually swapping out locations. Is there an easier approach when sharing solutions across mac and windows? </p> <p>thx</p>
0debug
static int rpza_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { RpzaContext *s = avctx->priv_data; int ret; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n"); return ret; } rpza_decode_stream(s); if ((ret = av_frame_ref(data, s->frame)) < 0) return ret; *got_frame = 1; return avpkt->size; }
1threat
static void pc_q35_machine_options(MachineClass *m) { m->family = "pc_q35"; m->desc = "Standard PC (Q35 + ICH9, 2009)"; m->hot_add_cpu = pc_hot_add_cpu; m->units_per_default_bus = 1; m->default_machine_opts = "firmware=bios-256k.bin"; m->default_display = "std"; m->no_floppy = 1; }
1threat
Splitting a string that is converted to a list with a single item into multiple items : <p>I have a string that is converted to a list using the split() function, and I want to split my single item into multiple items each containing one character.</p> <p>Here's my code:</p> <pre><code>string = "ABCDEFG" x = string.split() print(x) </code></pre> <p>Thank you for your time!:D</p>
0debug
how to get IP address and pc name of all pc's shared with me in a array using matlab script : <p>the array should be looks like below.<br> <strong>PC NAME IP ADDRESS</strong></p> <pre><code> SYSTEM1 192.168.12.45 SYSTEM2 192.168.12.4 SYSTEM3 192.168.12.5 SYSTEM4 192.168.12.15 </code></pre>
0debug
Why Is `Export Default Const` invalid? : <p>I see that the following is fine:</p> <pre><code>const Tab = connect( mapState, mapDispatch )( Tabs ); export default Tab; </code></pre> <p>However, this is incorrect:</p> <pre><code>export default const Tab = connect( mapState, mapDispatch )( Tabs ); </code></pre> <p>Yet this is fine:</p> <pre><code>export default Tab = connect( mapState, mapDispatch )( Tabs ); </code></pre> <p>Can this be explained please why <code>const</code> is invalid with <code>export default</code>? Is it an unnecessary addition &amp; anything declared as <code>export default</code> is presumed a <code>const</code> or such? </p>
0debug
void kvm_remove_all_breakpoints(CPUState *current_env) { struct kvm_sw_breakpoint *bp, *next; KVMState *s = current_env->kvm_state; CPUState *env; QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) { if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) { for (env = first_cpu; env != NULL; env = env->next_cpu) { if (kvm_arch_remove_sw_breakpoint(env, bp) == 0) break; } } } kvm_arch_remove_all_hw_breakpoints(); for (env = first_cpu; env != NULL; env = env->next_cpu) kvm_update_guest_debug(env, 0); }
1threat
static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt) { ConcatContext *cat = avf->priv_data; int ret; int64_t delta; ConcatStream *cs; while (1) { ret = av_read_frame(cat->avf, pkt); if (ret == AVERROR_EOF) { if ((ret = open_next_file(avf)) < 0) return ret; continue; } if (ret < 0) return ret; if (cat->match_streams) { match_streams(avf); cs = &cat->cur_file->streams[pkt->stream_index]; if (cs->out_stream_index < 0) { av_packet_unref(pkt); continue; } pkt->stream_index = cs->out_stream_index; } break; } delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time, AV_TIME_BASE_Q, cat->avf->streams[pkt->stream_index]->time_base); if (pkt->pts != AV_NOPTS_VALUE) pkt->pts += delta; if (pkt->dts != AV_NOPTS_VALUE) pkt->dts += delta; return ret; }
1threat
INT_BITS = 32 def left_Rotate(n,d): return (n << d)|(n >> (INT_BITS - d))
0debug
static void icount_adjust_vm(void *opaque) { timer_mod(icount_vm_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + NANOSECONDS_PER_SECOND / 10); icount_adjust(); }
1threat
static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value) { env->cp15.c0_cssel = value & 0xf; }
1threat
static void ide_init1(IDEBus *bus, int unit, DriveInfo *dinfo) { static int drive_serial = 1; IDEState *s = &bus->ifs[unit]; s->bus = bus; s->unit = unit; s->drive_serial = drive_serial++; s->io_buffer = qemu_blockalign(s->bs, IDE_DMA_BUF_SECTORS*512 + 4); s->io_buffer_total_len = IDE_DMA_BUF_SECTORS*512 + 4; s->smart_selftest_data = qemu_blockalign(s->bs, 512); s->sector_write_timer = qemu_new_timer(vm_clock, ide_sector_write_timer_cb, s); ide_init_drive(s, dinfo, NULL); }
1threat
python ,tkinter entry widget , how to input without clicking the entry box : I want to know how to : When I write something (without clicking on the entry box) , it automatically writes in the entry box . thanks before!
0debug
Handling Eventsource using PHP and C# : <p>I have created a fileWatcher(running as a service) in C# which calls PHP script through URL whenever there is a change in Folder. </p> <p>I want to load the web page with new data when there is change in file. I have tried doing this using javascript Eventsource by calling PHP and echoing by C# whenever there is change in file but no luck.</p> <p>Any suggestions how would I tackle this problem.</p>
0debug
npm run does nothing : <p>I've been working with Node.js/npm for a while, but I never used npm scripts. I was quite surprised to find that I can't get them to work at all on my Windows/Cygwin system. With a package.json like this ...</p> <pre><code>{ "name": "demo", "scripts": { "env": "env", "hello": "echo Hello!", "crap": "I am complete nonsense." } } </code></pre> <p>... all three npm run commands do nothing. <code>npm run crap</code> executes and returns immediately with an OK status (I tested with the -dd parameter); <code>npm run doesntexist</code> throws the expected error. Testing without Cygwin on the regular Windows shell made no difference.</p>
0debug
int load_elf(const char *filename, uint64_t (*translate_fn)(void *, uint64_t), void *translate_opaque, uint64_t *pentry, uint64_t *lowaddr, uint64_t *highaddr, int big_endian, int elf_machine, int clear_lsb) { int fd, data_order, target_data_order, must_swab, ret; uint8_t e_ident[EI_NIDENT]; fd = open(filename, O_RDONLY | O_BINARY); if (fd < 0) { perror(filename); return -1; } if (read(fd, e_ident, sizeof(e_ident)) != sizeof(e_ident)) goto fail; if (e_ident[0] != ELFMAG0 || e_ident[1] != ELFMAG1 || e_ident[2] != ELFMAG2 || e_ident[3] != ELFMAG3) goto fail; #ifdef HOST_WORDS_BIGENDIAN data_order = ELFDATA2MSB; #else data_order = ELFDATA2LSB; #endif must_swab = data_order != e_ident[EI_DATA]; if (big_endian) { target_data_order = ELFDATA2MSB; } else { target_data_order = ELFDATA2LSB; } if (target_data_order != e_ident[EI_DATA]) return -1; lseek(fd, 0, SEEK_SET); if (e_ident[EI_CLASS] == ELFCLASS64) { ret = load_elf64(filename, fd, translate_fn, translate_opaque, must_swab, pentry, lowaddr, highaddr, elf_machine, clear_lsb); } else { ret = load_elf32(filename, fd, translate_fn, translate_opaque, must_swab, pentry, lowaddr, highaddr, elf_machine, clear_lsb); } close(fd); return ret; fail: close(fd); return -1; }
1threat
How to know will nuget package work on .NET Core? : <p>I would expect some kind of filter to exists on website or in console.</p>
0debug
static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; VAPICHandlers *handlers; uint8_t opcode[2]; uint32_t imm32 = 0; target_ulong current_pc = 0; target_ulong current_cs_base = 0; uint32_t current_flags = 0; if (smp_cpus == 1) { handlers = &s->rom_state.up; } else { handlers = &s->rom_state.mp; } if (!kvm_enabled()) { cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base, &current_flags); } pause_all_vcpus(); cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0); switch (opcode[0]) { case 0x89: patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); patch_call(s, cpu, ip + 1, handlers->set_tpr); break; case 0x8b: patch_byte(cpu, ip, 0x90); patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]); break; case 0xa1: patch_call(s, cpu, ip, handlers->get_tpr[0]); break; case 0xa3: patch_call(s, cpu, ip, handlers->set_tpr_eax); break; case 0xc7: patch_byte(cpu, ip, 0x68); cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0); cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1); patch_call(s, cpu, ip + 5, handlers->set_tpr); break; case 0xff: patch_byte(cpu, ip, 0x50); patch_call(s, cpu, ip + 1, handlers->get_tpr_stack); break; default: abort(); } resume_all_vcpus(); if (!kvm_enabled()) { tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1); cpu_resume_from_signal(cs, NULL); } }
1threat
static int coroutine_fn backup_do_cow(BackupBlockJob *job, int64_t sector_num, int nb_sectors, bool *error_is_read, bool is_write_notifier) { BlockBackend *blk = job->common.blk; CowRequest cow_request; struct iovec iov; QEMUIOVector bounce_qiov; void *bounce_buffer = NULL; int ret = 0; int64_t sectors_per_cluster = cluster_size_sectors(job); int64_t start, end; int n; qemu_co_rwlock_rdlock(&job->flush_rwlock); start = sector_num / sectors_per_cluster; end = DIV_ROUND_UP(sector_num + nb_sectors, sectors_per_cluster); trace_backup_do_cow_enter(job, start, sector_num, nb_sectors); wait_for_overlapping_requests(job, start, end); cow_request_begin(&cow_request, job, start, end); for (; start < end; start++) { if (test_bit(start, job->done_bitmap)) { trace_backup_do_cow_skip(job, start); continue; } trace_backup_do_cow_process(job, start); n = MIN(sectors_per_cluster, job->common.len / BDRV_SECTOR_SIZE - start * sectors_per_cluster); if (!bounce_buffer) { bounce_buffer = blk_blockalign(blk, job->cluster_size); } iov.iov_base = bounce_buffer; iov.iov_len = n * BDRV_SECTOR_SIZE; qemu_iovec_init_external(&bounce_qiov, &iov, 1); ret = blk_co_preadv(blk, start * job->cluster_size, bounce_qiov.size, &bounce_qiov, is_write_notifier ? BDRV_REQ_NO_SERIALISING : 0); if (ret < 0) { trace_backup_do_cow_read_fail(job, start, ret); if (error_is_read) { *error_is_read = true; } goto out; } if (buffer_is_zero(iov.iov_base, iov.iov_len)) { ret = blk_co_pwrite_zeroes(job->target, start * job->cluster_size, bounce_qiov.size, BDRV_REQ_MAY_UNMAP); } else { ret = blk_co_pwritev(job->target, start * job->cluster_size, bounce_qiov.size, &bounce_qiov, 0); } if (ret < 0) { trace_backup_do_cow_write_fail(job, start, ret); if (error_is_read) { *error_is_read = false; } goto out; } set_bit(start, job->done_bitmap); job->sectors_read += n; job->common.offset += n * BDRV_SECTOR_SIZE; } out: if (bounce_buffer) { qemu_vfree(bounce_buffer); } cow_request_end(&cow_request); trace_backup_do_cow_return(job, sector_num, nb_sectors, ret); qemu_co_rwlock_unlock(&job->flush_rwlock); return ret; }
1threat
Vertical align content slickslider : <p>I've been struggling to get my content vertical aligned but really don't fix it. I tried the adaptiveHeight parameter but it really didn't do what I wanted.</p> <p>Fiddle: <a href="http://jsfiddle.net/fmo50w7n/400" rel="noreferrer">http://jsfiddle.net/fmo50w7n/400</a></p> <p>This is what the code looks like HTML:</p> <pre><code>&lt;section class="slider"&gt; &lt;div style="width:500px;height:200px"&gt;slide1&lt;/div&gt; &lt;div style="width:500px;height:300px;"&gt;slide2&lt;/div&gt; &lt;div style="width:500px;height:100px;"&gt;slide3&lt;/div&gt; &lt;/section&gt; </code></pre> <p>CSS:</p> <pre><code>$c1: #3a8999; $c2: #e84a69; .slider { width: auto; margin: 30px 50px 50px; } .slick-slide { background: $c1; color: white; padding: 40px 0; font-size: 30px; font-family: "Arial", "Helvetica"; text-align: center; } .slick-prev:before, .slick-next:before { color: black; } .slick-dots { bottom: -30px; } .slick-slide:nth-child(odd) { background: $c2; } </code></pre> <p>JS:</p> <pre><code>$(".slider").slick({ autoplay: true, dots: true, variableWidth:true, responsive: [{ breakpoint: 500, settings: { dots: false, arrows: false, infinite: false, slidesToShow: 2, slidesToScroll: 2 } }] }); </code></pre>
0debug
static int query_formats(AVFilterGraph *graph, AVClass *log_ctx) { int i, j, ret; int scaler_count = 0, resampler_count = 0; int count_queried = 0, count_merged = 0, count_already_merged = 0, count_delayed = 0; for (i = 0; i < graph->nb_filters; i++) { AVFilterContext *f = graph->filters[i]; if (formats_declared(f)) continue; if (f->filter->query_formats) ret = filter_query_formats(f); else ret = ff_default_query_formats(f); if (ret < 0 && ret != AVERROR(EAGAIN)) return ret; count_queried += ret >= 0; } for (i = 0; i < graph->nb_filters; i++) { AVFilterContext *filter = graph->filters[i]; for (j = 0; j < filter->nb_inputs; j++) { AVFilterLink *link = filter->inputs[j]; int convert_needed = 0; if (!link) continue; #define MERGE_DISPATCH(field, statement) \ if (!(link->in_ ## field && link->out_ ## field)) { \ count_delayed++; \ } else if (link->in_ ## field == link->out_ ## field) { \ count_already_merged++; \ } else { \ count_merged++; \ statement \ } MERGE_DISPATCH(formats, if (!ff_merge_formats(link->in_formats, link->out_formats, link->type)) convert_needed = 1; ) if (link->type == AVMEDIA_TYPE_AUDIO) { MERGE_DISPATCH(channel_layouts, if (!ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts)) convert_needed = 1; ) MERGE_DISPATCH(samplerates, if (!ff_merge_samplerates(link->in_samplerates, link->out_samplerates)) convert_needed = 1; ) } #undef MERGE_DISPATCH if (convert_needed) { AVFilterContext *convert; AVFilter *filter; AVFilterLink *inlink, *outlink; char scale_args[256]; char inst_name[30]; switch (link->type) { case AVMEDIA_TYPE_VIDEO: if (!(filter = avfilter_get_by_name("scale"))) { av_log(log_ctx, AV_LOG_ERROR, "'scale' filter " "not present, cannot convert pixel formats.\n"); return AVERROR(EINVAL); } snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d", scaler_count++); av_strlcpy(scale_args, "0:0", sizeof(scale_args)); if (graph->scale_sws_opts) { av_strlcat(scale_args, ":", sizeof(scale_args)); av_strlcat(scale_args, graph->scale_sws_opts, sizeof(scale_args)); } if ((ret = avfilter_graph_create_filter(&convert, filter, inst_name, scale_args, NULL, graph)) < 0) return ret; break; case AVMEDIA_TYPE_AUDIO: if (!(filter = avfilter_get_by_name("aresample"))) { av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter " "not present, cannot convert audio formats.\n"); return AVERROR(EINVAL); } snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d", resampler_count++); scale_args[0] = '\0'; if (graph->aresample_swr_opts) snprintf(scale_args, sizeof(scale_args), "%s", graph->aresample_swr_opts); if ((ret = avfilter_graph_create_filter(&convert, filter, inst_name, graph->aresample_swr_opts, NULL, graph)) < 0) return ret; break; default: return AVERROR(EINVAL); } if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0) return ret; filter_query_formats(convert); inlink = convert->inputs[0]; outlink = convert->outputs[0]; if (!ff_merge_formats( inlink->in_formats, inlink->out_formats, inlink->type) || !ff_merge_formats(outlink->in_formats, outlink->out_formats, outlink->type)) ret |= AVERROR(ENOSYS); if (inlink->type == AVMEDIA_TYPE_AUDIO && (!ff_merge_samplerates(inlink->in_samplerates, inlink->out_samplerates) || !ff_merge_channel_layouts(inlink->in_channel_layouts, inlink->out_channel_layouts))) ret |= AVERROR(ENOSYS); if (outlink->type == AVMEDIA_TYPE_AUDIO && (!ff_merge_samplerates(outlink->in_samplerates, outlink->out_samplerates) || !ff_merge_channel_layouts(outlink->in_channel_layouts, outlink->out_channel_layouts))) ret |= AVERROR(ENOSYS); if (ret < 0) { av_log(log_ctx, AV_LOG_ERROR, "Impossible to convert between the formats supported by the filter " "'%s' and the filter '%s'\n", link->src->name, link->dst->name); return ret; } } } } av_log(graph, AV_LOG_DEBUG, "query_formats: " "%d queried, %d merged, %d already done, %d delayed\n", count_queried, count_merged, count_already_merged, count_delayed); if (count_delayed) { AVBPrint bp; if (count_queried || count_merged) return AVERROR(EAGAIN); av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC); for (i = 0; i < graph->nb_filters; i++) if (!formats_declared(graph->filters[i])) av_bprintf(&bp, "%s%s", bp.len ? ", " : "", graph->filters[i]->name); av_log(graph, AV_LOG_ERROR, "The following filters could not choose their formats: %s\n" "Consider inserting the (a)format filter near their input or " "output.\n", bp.str); return AVERROR(EIO); } return 0; }
1threat
Python to start from : I have multiple functions. that is in order like below: test1func() test2func() test3func() test4func() test5func() test6func() I want to ask user to enter from where to start. if he selects 3 then it should start from function test3() to test6() if he selects test5func then from test5func to test6func() like that. Code: print "1).fun1\n2).fun2\n3).fun3\n4).fun4\n5).fun5\n6).fun6" select_fun = raw_input"Choose from which function it has to start" Now i need logic or help to achieve above requirement
0debug
spring error creating different modules : - SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener java.lang.NoSuchMethodError: org.springframework.beans.factory.xml.XmlBeanDefinitionReader.setEnvironment(Lorg/springframework/core/env/Environment;)V at org.sprin`web.xml` <display-name>ems</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>ems</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ems</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/ems-servlet.xml</param-value> </context-param> </web-app>`ems-servlet`<import resource="classpath*:/ems-services.xml" /> <context:component-scan base-package="com.ems" /> <mvc:annotation-driven /> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="prefixJson" value="false" /> <property name="supportedMediaTypes" value="application/json" /> </bean> </beans>`ems-services.xml`<import resource="classpath*/:ems-data.xml" /> <context:component-scan base-package="com.ems" /> </beans>
0debug
How to remove some items from an arraylist without loop and less complexity? : I have an array list of some 1 Lakh objects. I want to remove some of the objects which is having a particular ID. Now i'm using for loop to search through the arraylist and remove each of them. Hence it is very much time consuming. Is there any possible way to do this without any looping?
0debug
def list_split(S, step): return [S[i::step] for i in range(step)]
0debug
Javascript or Jquery sum of highest 5 values : Please do not mark this question as **DUPLICATE**. I am really facing the problem. I have an array of 6 values where 6th value is optional (i.e. if user does not input 6th value, the first 5 values will be calculated). I want to sum highest 5 values of them. My Javascript Code: function calculate_merit_point(){ var s1 = eval(document.getElementById('sub_no1').value); var s2 = eval(document.getElementById('sub_no2').value); var s3 = eval(document.getElementById('sub_no3').value); var s4 = eval(document.getElementById('sub_no4').value); var s5 = eval(document.getElementById('sub_no5').value); var s6 = eval(document.getElementById('sub_no6').value); var vals = [s1,s2,s3,s4,s5,s6]; function arraySum(arr) { if (!arr) { return false; } else { var sum = 0; for (var i = 0, len = arr.length; i < len; i++) { sum += arr[i]; } return sum; } } sum = arraySum(vals.sort(function(a, b) { return b - a; }).slice(0, 5)); if(isNaN(tt)){ $('#agr').text('0'); } else { $('#agr').text(sum); } } Now suppose s1 = 30 s2 = 31 s3 = 32 s4 = 33 s5 = 34 s6 = 35 It should be `31+32+33+34+35 = 165`. but it is displaying the value 162. As per my requirement (6th value optional), if I do not give any value to `s6`, it is displaying the value **228**. I have tried [This][1], but if I do not give the 6th (optional) value, it is showing the value `0`. If I give the value 35 in s6, it is showing sum value 233. **What should I do ?** [1]: http://stackoverflow.com/questions/12019803/javascript-sum-of-highest-6-values-in-an-array
0debug
Add foreign key to table after migration has been run in laravel : I have the following migration in my laravel migrations folder that i have already run: <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAdminTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('Admin' , function($table){ $table->increments('id'); $table->mediumText('title'); $table->text('blog_content'); $table->char('tag' , 15); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('Admin'); } } The above migration is for my `admin` table, what i would really like to do is add a foreign key in my `admin` table that is associated with my `tags` table. something like: $table->foreign('tag')->references('tag')->on('tags'); How do i do this now that i have already run my migration ?? Thank you.
0debug
tensorflow: how to rotate an image for data augmentation? : <p>In tensorflow, I would like to rotate an image from a random angle, for data augmentation. But I don't find this transformation in the tf.image module. </p>
0debug
Msg 8152, Level 16, State 2, Line 1. Finding wich columns will be truncated : It's been asked hundred times, but I'm on a predicament, I was delegated to mantain a table from an external DB with the data I handle on my DB, what I'm faced now it's getting data from my DB to that table, the problem being the lengh of the values I have (data it's 90% equivalent at worst, but I also handle more precise data) and getting the classic `Msg 8152, Level 16, State 2, Line 1 Los datos de cadena o binarios se truncarían.`. I know I could check each column and comparing total lengh but we are talking about 130 columns and more than 6 joins on my procedure. I did `SET ANSI_WARNINGS OFF` and found about 10 columns conflicting with the table (data shows clearly truncated values), but I still need to compare 120 columns with abount 4k rows. With that being said is there a easier/less manual way to detect wich columns are raising errors?
0debug
What is the difference between assign and put_session in Plug.Conn of the Phoenix Framework? : <p>The documentation (<a href="https://hexdocs.pm/plug/Plug.Conn.html" rel="noreferrer">https://hexdocs.pm/plug/Plug.Conn.html</a>) names two functions that allow for storing a key-value pair in a <code>conn</code></p> <pre><code>assign(conn, key, value) </code></pre> <blockquote> <p>Assigns a value to a key in the connection</p> </blockquote> <pre><code>put_session(conn, key, value) </code></pre> <blockquote> <p>Puts the specified value in the session for the given key</p> </blockquote> <p>What is the difference between these two functions?</p>
0debug
Variable turned out to have "Inf" and "NA's" from math function : <p>Why variable "rate" turned out to have "Inf" and "NA's" from simple math function?`rate=(outcome/pop19)*100000</p> <p>I did the exact same calculation for "rate" on its parent data with no problem. "Compplot" is simply a subset of fewer variables. </p> <p><a href="https://i.stack.imgur.com/29w5A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/29w5A.png" alt="My data summary"></a></p>
0debug
static ExitStatus trans_fop_dew_0c(DisasContext *ctx, uint32_t insn, const DisasInsn *di) { unsigned rt = extract32(insn, 0, 5); unsigned ra = extract32(insn, 21, 5); return do_fop_dew(ctx, rt, ra, di->f_dew); }
1threat
java.lang.NullPointerException:image not loading : <p>Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)'. on a null object reference. i m getting this error please help.</p> <pre><code> private void loadSongs() { Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"; Cursor cursor = getContext().getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)); String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); String albumId = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); Cursor cursorm = getContext().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART}, MediaStore.Audio.Albums._ID+ "=?", new String[] {String.valueOf(albumId)}, null); assert cursorm != null; if (cursorm.moveToFirst()) { String path = cursorm.getString(cursorm.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)); Drawable img = Drawable.createFromPath(path); image = (ImageView)rootView.findViewById(R.id.albumArt); // image.setImageDrawable(img); image.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.ed)); } songInfo s = new songInfo(name, artist, url); _songs.add(s); } while (cursor.moveToNext()); cursor.close(); recyclerView.getAdapter().notifyDataSetChanged(); } } } </code></pre>
0debug
How to do editText like password : <p>I want to do this code in c to Android I dont use passwordtext I need to use editText ty</p> <pre><code> ph=getch(); if(ph!='\r'){ pass[i]=ph; printf("*"); </code></pre>
0debug
Can this code make sql injection impossible? : I found this code in DNN PortalSecurity.cs. This is supposed to make input string sql injection safe. Do you see any issues here ? private string FormatRemoveSQL(string strSQL) { const string BadStatementExpression = ";|--|create|drop|select|insert|delete|update|union|sp_|xp_|exec|/\\*.*\\*/|declare|waitfor|%|&"; return Regex.Replace(strSQL, BadStatementExpression, " ", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace("'", "''"); }
0debug
SQLSTATE[HY093]: All parameters are filled properly and the syntax is right, so what's wrong? : I am getting the following error and I can't figure out just why: `SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in` Here's the code: $transactions_sql = "INSERT INTO transactions (usr, service, txn_id, orig_amount, currency, date, description, fee_amt, fee_currency, fee_descr, fee_type, net_amt, status) VALUES "; $transactions_sql_data = array_fill(0, count($transactions) - 1, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $transactions_sql .= implode(",", $transactions_sql_data); $stmt = $conn->prepare($transactions_sql); foreach ($transactions["data"] as $tr) { $stmt->bindValue(1, $id, PDO::PARAM_INT); $stmt->bindValue(2, tr["service"], PDO::PARAM_STR); $stmt->bindValue(3, $tr["id"], PDO::PARAM_INT); $stmt->bindValue(4, $tr["amount"], PDO::PARAM_INT); $stmt->bindValue(5, $tr["currency"], PDO::PARAM_STR); $stmt->bindValue(6, $tr["created"], PDO::PARAM_STR); $stmt->bindValue(7, $tr["description"], PDO::PARAM_STR); $stmt->bindValue(8, $tr["fee_details"][0]["amount"], PDO::PARAM_INT); $stmt->bindValue(9, $tr["fee_details"][0]["currency"], PDO::PARAM_STR); $stmt->bindValue(10, $tr["fee_details"][0]["description"], PDO::PARAM_STR); $stmt->bindValue(11, $tr["fee_details"][0]["type"], PDO::PARAM_STR); $stmt->bindValue(12, $tr["net"], PDO::PARAM_INT); $stmt->bindValue(13, $tr["status"], PDO::PARAM_STR); } $stmt->execute(); Doing `var_dump($transactions_sql)` prints `"INSERT INTO balance_transactions (usr, service, txn_id, orig_amount, currency, date, description, fee_amt, fee_currency, fee_descr, fee_type, net_amt, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"`, which is correct (in terms of number of question marks - there will only be three arrays inside the `$tr` array). So what's wrong here? **EDIT: If you're going to down vote, then please tell me what's wrong. Down voting and just leaving doesn't help me or any future reader.**
0debug
static void mxf_read_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor) { int code, value, ofs = 0; char layout[16] = {}; do { code = get_byte(pb); value = get_byte(pb); dprintf(NULL, "pixel layout: code %#x\n", code); if (ofs < 16) { layout[ofs++] = code; layout[ofs++] = value; } } while (code != 0); ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt); }
1threat
javascript - Uncaught ReferenceError for a defined variable : <p>Relevant Code:</p> <pre><code>// Flag For Showing/Hiding Start Campaign Button During Alarm var blnCampaignStatusIsgood = false; do { $.ajax({ url: "includes/getCampaigns.php, dataType: "json", cache: false, aysnc: false, success: function (res) { console.log("Loaded campaign info ...includes/getCampaigns.php"); // Flag To Stop Ajax Calls blnCampaignStatusIsgood = true; }, error: function (res) { console.log("Error checking for campaign info: " + res); } }); } while ( blnCampaignStatusIsGood == false ); </code></pre> <p>When ran, I receive the error: </p> <blockquote> <p>Uncaught ReferenceError: blnCampaignStatusIsGood is not defined</p> </blockquote> <p>On the line with the while condition.</p> <p>I've tried various declarations of the variable name (with and without "var"), making it global at top of script, as well as changing the ajax request to a sync request.</p> <p>Why is it saying it's undefined when I clearly define it just prior to the do/while loop?</p>
0debug
How to slide group of division in html/css page? : I am making a website where I need to slides a group of division from right to left. this is required screen shot [I want to slide these division from left to write in a circuler way ie when division A is on the left end and about to disappear it must be show from right side][1] [1]: https://i.stack.imgur.com/tB8eA.jpg
0debug
Python: try again some block if any condition exists : <p>I need to realize next algorithm: if I get <code>False</code> more that three times, do <code>continue</code>, if this number less that <code>3</code>, try again and again.</p> <pre><code>list = [1, 2, 3, 4, 5, 6, 6, 8, 8, 64, 4, 5, 6] result = False for elem in list: trying = 0 while not result: print(elem) try: result = elem % 2 == 0 except: trying += 1 print(trying) if trying == 3: continue else: pass </code></pre> <p>it doesn't go to block <code>except</code>. Can anybody explain, what should I change to get desirable?</p>
0debug
Prime numbers with range up to 10^12 : I'm testing some algorithm in console apllication. I need to print number of prime time numbers in range from 1 to 10^15. This code works but It need to take less than a 4 seconds before timeout. It works in about when last number is somewhere about 2000000, after that it takes more time. static void Main(string[] args) { string[] s = Console.ReadLine().Split(' '); DateTime start = DateTime.Now; var first = Convert.ToInt64(s[0]); var last = Convert.ToInt64(s[1]); int counter = 0; for (long i = first; i <= last; i++) { if (i > 2 && i%2==0) { continue; } if (isPrime(i)) { counter++; } } Console.WriteLine(counter); TimeSpan duration = DateTime.Now - start; Console.WriteLine(duration.TotalMilliseconds); Console.ReadLine(); } public static bool isPrime(long number) { if (number == 1) return false; if (number == 2) return true; for (int i = 2; i <= Math.Ceiling(Math.Sqrt(number)); ++i) { if (number % i == 0) return false; } return true; } As you can see in for loop, first I examine whether number is i > 2 && i%2==0 since in that case number isn't prime. Is there any more tricks to avoid such numbers not to get to the isPrime method or what's the best solution to avoid timeouts?
0debug
How to print DataFrame on single line : <p>With:</p> <pre><code>import pandas as pd df = pd.read_csv('pima-data.csv') print df.head(2) </code></pre> <p>the print is automatically formatted across multiple lines:</p> <pre><code> num_preg glucose_conc diastolic_bp thickness insulin bmi diab_pred \ 0 6 148 72 35 0 33.6 0.627 1 1 85 66 29 0 26.6 0.351 age skin diabetes 0 50 1.3790 True 1 31 1.1426 False </code></pre> <p>I wonder if there is a way to avoid the multi-line formatting. I would rather have it printed in a single line like so:</p> <pre><code> num_preg glucose_conc diastolic_bp thickness insulin bmi diab_pred age skin diabetes 0 6 148 72 35 0 33.6 0.627 50 1.3790 True 1 1 85 66 29 0 26.6 0.351 31 1.1426 False </code></pre>
0debug
Python - How to run multiple flask apps from same client machine : <p>I have one flask application script as given below :</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/&lt;string:job_id&gt;") def main(job_id): return "Welcome!. This is Flask Test Part 1" if __name__ == "__main__": job_id = 1234 app.run(host= '0.0.0.0') </code></pre> <p>I have another flask application script as below :</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/&lt;string:ID&gt;") def main(ID): return "Welcome!. This is Flask Test Part 2" if __name__ == "__main__": ID = 5678 app.run(host= '0.0.0.0') </code></pre> <p>The only difference between both the scripts is the argument name and its value. Now my question is assume that I am executing the first script. So I will get something like </p> <pre><code>* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) </code></pre> <p>When I execute <a href="http://127.0.0.1:5000/1234" rel="noreferrer">http://127.0.0.1:5000/1234</a> in my browser I am able to see </p> <blockquote> <p>"Welcome!. This is Flask Test Part 1"</p> </blockquote> <p>Now with this server active, I am executing the second script. So again I get </p> <pre><code>* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) </code></pre> <p>But when I execute <a href="http://127.0.0.1:5000/5678" rel="noreferrer">http://127.0.0.1:5000/5678</a> in my browser I am able to see</p> <blockquote> <p>"Welcome!. This is Flask Test Part 1"</p> </blockquote> <p>instead of </p> <blockquote> <p>"Welcome!. This is Flask Test Part 2"</p> </blockquote> <p>I don't understand where I am doing mistake. Any inputs or alterations will be helpful</p>
0debug
Why is assigning a character in a string to itself a bus error? : <p>This works and produces <code>bbcd</code> as I'd expect.</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { char string[] = "abcd"; string[0] = string[1]; printf("%s\n", string); } </code></pre> <p>This is a bus error.</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { char *string = "abcd"; string[0] = string[1]; printf("%s\n", string); } </code></pre> <p>Why?</p> <p>Valgrind says:</p> <pre><code>==9909== Process terminating with default action of signal 10 (SIGBUS) ==9909== Non-existent physical address at address 0x100000FA2 ==9909== at 0x100000F65: main (test.c:6) </code></pre>
0debug
static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track) { offset_t pos = url_ftell(pb); put_be32(pb, 0); put_tag(pb, "stbl"); mov_write_stsd_tag(pb, track); mov_write_stts_tag(pb, track); if (track->enc->codec_type == CODEC_TYPE_VIDEO && track->hasKeyframes < track->entry) mov_write_stss_tag(pb, track); if (track->enc->codec_type == CODEC_TYPE_VIDEO && track->hasBframes) mov_write_ctts_tag(pb, track); mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); return updateSize(pb, pos); }
1threat
Pytorch tensor to numpy array : <p>I have a <code>pytorch</code> Tensor of size <code>torch.Size([4, 3, 966, 1296])</code></p> <p>I want to convert it to <code>numpy</code> array using the following code:</p> <p><code>imgs = imgs.numpy()[:, ::-1, :, :]</code></p> <p>Can anyone please explain what this code is doing ?</p>
0debug
I want to learn javascript : <p>I want to learn javascript soon and I would like to ask for your opinion about the online sites where I could start: Udemy, Pluralsight, Codecademy ... Which one is better? I attended a training in Angular on Pluralsight and I can say that I like it but I would like to try something new if it is worth it.</p>
0debug
Need help compiling GCC Cross-Compiler! PLEASE : I am trying to compile GCC for i586-elf but every time I run the 'configure' file with this command: ./configure --target=$TARGET --prefix=$PREFIX --disable-nls --enable languages=c --without-headers --with-gmp=$PREFIX --with-mpc=$PREFIX --with-mpfr=$PREFIX Then it gives me this error: checking for the correct version of gmp.h... yes checking for the correct version of mpfr.h... yes checking for the correct version of mpc.h... yes checking for the correct version of the gmp/mpfr/mpc libraries... no. Although I have specified where gmp, mpfr, and mpc are located. And I have the latest versions of them. Is there anything I am missing? Please answer as soon as possible :)
0debug
iOS URLRequest POST Failing Swift : <p>I am currently trying to make a POST request on the iOS platform with a JSON body. My request works in cURL, but I cannot get it to work in iOS; the request times out. Here is my swift code:</p> <pre><code> class func createNewChannel(name: String, priv: String, channelKey: String, handle: String, password: String, auth: String) { let baseURL = "http://10.0.0.220:3000/" let dict = ["name": name, "private": priv, "channelKey": channelKey, "handle": handle, "password": password, "auth": auth] as [String : Any] let jsonData = JSON(dict) do { let post = try jsonData.rawData() let postLength = String(post.count) let url = URL(string: "\(baseURL)channel/createChannel")! var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = post as Data request.setValue(postLength, forHTTPHeaderField: "Content-Length") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) in if error == nil { do { let json = try JSON(data: data!) print(json) } catch { print(error.localizedDescription) } } else { print(error!) } }) task.resume() } catch { print(error.localizedDescription) } } </code></pre> <p>When I call this function, the request does not work...I am sure I am using the right url because it works with a GET endpoint. Am I missing any headers? Please let me know if you see something wrong with the request.</p>
0debug
double dimension array dynamic c# : <p>I'm a python developer and I would like to convert this following code on C# :</p> <pre><code>#long version tab = [] for i in range(n): tab.append([]) for j in range(n): tab[i].append(0) #short version tab = [[0]*n for _ in range(n)] </code></pre> <p>Thanks for your help !</p>
0debug
trim datetime to use only HH:mm. : <p>I'm using datetime picker where I'm getting date in format like</p> <pre><code>2017-02-07 10:05 </code></pre> <p>how can I trim this to use only HH:mm. </p> <p>p.s. I dont want to change date format on datetime picker initialization</p>
0debug
static void colo_compare_finalize(Object *obj) { CompareState *s = COLO_COMPARE(obj); qemu_chr_fe_deinit(&s->chr_pri_in, false); qemu_chr_fe_deinit(&s->chr_sec_in, false); qemu_chr_fe_deinit(&s->chr_out, false); g_main_loop_quit(s->compare_loop); qemu_thread_join(&s->thread); g_queue_foreach(&s->conn_list, colo_flush_packets, s); g_queue_clear(&s->conn_list); g_hash_table_destroy(s->connection_track_table); g_free(s->pri_indev); g_free(s->sec_indev); g_free(s->outdev); }
1threat
How to do lamda operations with stream? : As for now I am doing : Map<Integer, Item> itemList = getItems(input); Iterator<Item> ItemIterator = input.getItems().iterator(); List<Item> updatedItems = Lists.newLinkedList(); for (int i = MIN; i <= input.getInputReq().getList().size(); i++) { Item item = itemList.get(i); if (item != null) { item.setFlag(false); item.setId(getId()); updatedItems.add(item); itemList.remove(i); } else { if (ItemIterator.hasNext()) { updatedItems.add(ItemIterator.next()); } } } Is there any efficient way I could do this with Streams and lambda in java8 ?
0debug
Example of neural network in keras that inputs and outputs an image : <p>Can please somebody present me with a (preferably Keras) model that inputs and outputs an image. Let's say for example a network that gets for input a color image and outputs a black and white image. Or for example a network that inputs edges of a painting image and outputs fully colored image.</p> <p>Thanks.</p>
0debug
How Android Detects Screen Size phone : When I create small,normal,large,xlarge layouts:How Android Detects Screen Size phone for use this layouts?base on dp or dpi or px?Is the result always right?
0debug
Run multiple android app instances like parallel space : <p>I want to know how parallel space <a href="https://play.google.com/store/apps/details?id=com.lbe.parallel.intl&amp;hl=en">https://play.google.com/store/apps/details?id=com.lbe.parallel.intl&amp;hl=en</a> is working. It is an app for logging in with another facebook, whatsapp etc account. You can find the detailed description in the play store link.</p> <p>I have looked at the folders that parallel space is creating using ES Explorer. They have created the following folder parallel_intl/0/</p> <p>In this folder they have DCIM, Pictures etc folder. I logged in another whatsapp account using parallel space and they created the whatsapp folder at the following location parallel_intl/0/Whatsapp </p> <p>Is it possible to achieve the same thing with Android For Work Container???</p> <p>Are they some how creating a separate space where Whatsapp etc will run???</p> <p>Kindly provide some guideline explaining how this can be achieved.</p> <p>Thanks.</p>
0debug
android margins not working when dynamically inserting views : <p>I have a simple view:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/contact_selected" android:layout_marginTop="10dp" android:layout_marginEnd="5dp" android:orientation="horizontal" android:padding="3dp"&gt; &lt;TextView android:id="@+id/txt_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Billy Bob" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>When I statically copy the LinearLayout markup into my main activity layout, the margins are as expected. However, when I add the view into the main activity layout dynamically, the margins are ignored. Here's how I insert the view</p> <pre><code>LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.test, null); TextView txt_title = (TextView)view.findViewById(R.id.txt_title); txt_title.setText("Dynamic #1"); llayout.addView(view, llayout.getChildCount()-1); View view2 = inflater.inflate(R.layout.test, null); txt_title = (TextView)view2.findViewById(R.id.txt_title); txt_title.setText("Dynamic #2"); llayout.addView(view2, llayout.getChildCount()-1); </code></pre> <p>Here's what it looks like:</p> <p><a href="https://i.stack.imgur.com/7si8I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7si8I.png" alt="enter image description here"></a></p> <p>The container in the main layout is a LinearLayout, which is a child of a HorizontalScrollView. Any insight is appreciated.</p>
0debug
ListView is not show images : This is Main_Activity Integer[] imgid = {R.drawable.frame3,R.drawable.frame3,R.drawable.frame3,R.drawable.frame3, R.drawable.frame5,R.drawable.frame6,R.drawable.frame7,R.drawable.frame8, R.drawable.frame9,}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_image_activity); Bundle extras = getIntent().getExtras(); byte[] byteArray = extras.getByteArray("image"); Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); img_img=(ImageView)findViewById(R.id.img); img_img.setImageBitmap(bmp); Adapter adapter=new Adapter(this,imgid); list=(ListView)findViewById(R.id.listview); list.setAdapter(adapter); Log.e("Your in Main","Welcome_______"); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String pos=Integer.toString(position); Toast.makeText(EditImageActivity.this, "Your Position is"+pos, Toast.LENGTH_SHORT).show(); } }); } } //This is Adapter class___________ public class Adapter extends ArrayAdapter<String> { private final Activity context; private final Integer[] images; public Adapter(Activity context, Integer[] imgid) { super(context, R.layout.list_image); this.context=context; this.images=imgid; } @Override public View getView(int position,View convertView,ViewGroup parent) { Log.e("Your in getView","Welcome"); LayoutInflater inflater=context.getLayoutInflater(); View rowView=inflater.inflate(R.layout.list_image, null,true); ImageView imageView = (ImageView) rowView.findViewById(R.id.list_img); imageView.setImageResource(images[position]); return rowView; } }
0debug
Copy file from Elastic beanstalk to local machine : <p>I have connected to Elastic Beanstalk using:</p> <blockquote> <p>eb ssh XXXXXX --profile=xx</p> </blockquote> <p>Now I want to copy a file to my local machine, how do I do that?</p>
0debug
Python3 - list() is taking every character in the string as an element, not every word : <p>I want to make a list of numbers via input When I type:</p> <pre><code>&gt;&gt;&gt; list(input()) 1 23 456 7890 ['1', ' ', '2', '3', ' ', '4', '5', '6', ' ', '7', '8', '9', '0'] </code></pre> <p>how to let it print this:</p> <pre><code>[1, 23, 456, 7890] </code></pre> <p>?</p>
0debug
What does <- mean in scala with yeild? : <p>I'm pretty new to scala and come up with the following construction:</p> <pre><code>val value= for { p1 &lt;- getList() p2 &lt;- parser.parse(p1) //parser.parse(String) Returns some useful value } yield p2 value.asJava </code></pre> <p>Where</p> <pre><code>def getList(): List[String] = { //compiled code } </code></pre> <p>I don't quite understand what's going on in the first piece of code. Searching for <strong><em>scala left arrow operator</em></strong> did't shed the light on this. Can't you explain it?</p>
0debug
TypeScript: error when using parseInt() on a number : <p>The JavaScript function <code>parseInt</code> can be used to force conversion of a given parameter to an integer, whether that parameter is a string, float number, number, etc. </p> <p>In JavaScript, <code>parseInt(1.2)</code> would yield <code>1</code> with no errors, however, in TypeScript, it throws an error during compilation saying: </p> <pre><code>error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. </code></pre> <p>Am I missing something here or is it an expected behaviour from TypeScript? </p>
0debug
Azure Portal: Bad Request - Request Too Long : <p>I just received the following error when I tried to run a <a href="https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-policies" rel="noreferrer">built-in b2c</a> edit policy from <a href="https://portal.azure.com" rel="noreferrer">portal.azure.com</a>. I have 2 tabs of the portal open. Why am I receiving this error?</p> <blockquote> <p>Bad Request - Request Too Long HTTP Error 400. The size of the request headers is too long.</p> </blockquote> <p>Note: I experienced <a href="https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/10" rel="noreferrer">this same error message</a> when testing <a href="https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi" rel="noreferrer">active-directory-b2c-dotnet-webapp-and-webapi sample project</a>. The reason provided was I was sending too many cookies. Is it the same problem?</p> <p>If it is the same problem, shouldn't stale <a href="https://stackoverflow.com/questions/2144386/how-to-delete-a-cookie">cookies be deleted</a> before creating new ones?</p> <hr> <p>I do see a lot of cookies for <a href="https://login.microsoftonline.com" rel="noreferrer">https://login.microsoftonline.com</a></p> <p><a href="https://i.stack.imgur.com/81v2e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/81v2e.png" alt="chrome cookies node"></a></p> <p><a href="https://i.stack.imgur.com/zUPY8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zUPY8.png" alt="screen shot 1 of cookies"></a> <a href="https://i.stack.imgur.com/4bRkx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4bRkx.png" alt="screen shot 2 of cookies"></a></p>
0debug
I am getting IMEI null in Android Q? : <p>I am getting the IMEI ID null from the telephonymanager. What to do?</p> <p>is there any workaround for that?</p>
0debug
static int aarch64_tr_init_disas_context(DisasContextBase *dcbase, CPUState *cpu, int max_insns) { DisasContext *dc = container_of(dcbase, DisasContext, base); CPUARMState *env = cpu->env_ptr; ARMCPU *arm_cpu = arm_env_get_cpu(env); dc->pc = dc->base.pc_first; dc->condjmp = 0; dc->aarch64 = 1; dc->secure_routed_to_el3 = arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3); dc->thumb = 0; dc->sctlr_b = 0; dc->be_data = ARM_TBFLAG_BE_DATA(dc->base.tb->flags) ? MO_BE : MO_LE; dc->condexec_mask = 0; dc->condexec_cond = 0; dc->mmu_idx = core_to_arm_mmu_idx(env, ARM_TBFLAG_MMUIDX(dc->base.tb->flags)); dc->tbi0 = ARM_TBFLAG_TBI0(dc->base.tb->flags); dc->tbi1 = ARM_TBFLAG_TBI1(dc->base.tb->flags); dc->current_el = arm_mmu_idx_to_el(dc->mmu_idx); #if !defined(CONFIG_USER_ONLY) dc->user = (dc->current_el == 0); #endif dc->fp_excp_el = ARM_TBFLAG_FPEXC_EL(dc->base.tb->flags); dc->vec_len = 0; dc->vec_stride = 0; dc->cp_regs = arm_cpu->cp_regs; dc->features = env->features; dc->ss_active = ARM_TBFLAG_SS_ACTIVE(dc->base.tb->flags); dc->pstate_ss = ARM_TBFLAG_PSTATE_SS(dc->base.tb->flags); dc->is_ldex = false; dc->ss_same_el = (arm_debug_target_el(env) == dc->current_el); dc->next_page_start = (dc->base.pc_first & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE; init_tmp_a64_array(dc); return max_insns; }
1threat