Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from 2018-01-24T04:53:46Z
Updated: 2 hours 38 min ago

Get Hold of the View of an item inside RecyclerView at given position

Tue, 10/17/2017 - 08:07

I have RecyclerView using GridLayout . Each item view consists an Image and name.

UseCase: On click of any item , a bottom sheet should which will have certain number of actions to do on the selected item . One of the action is 'Rename' . On click of Rename , bottom sheet should close and TextView of that particular item should become editable.

My Attempt : I created an Observer , which will be triggered on click of the rename action. inside this observer i am trying to get hold of the view from position .

RecyclerView.ViewHolder vh = mElementListView.findViewHolderForAdapterPosition(position); if(vh == null) { Log.d("AssetList","Null at position-"+position); } else { View view = vh.itemView; EditText editText = view.findViewById(; editText.setVisibility(View.VISIBLE); }

But I am getting null pointer for some of the item, even though the item clicked is visible in the list.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setVisibility(int)' on a null object reference

Can Anyone help me with this ?

ExtJS 6 - Store $binding is undefined

Tue, 10/17/2017 - 08:07

I need to perform certain operations when a store is loaded. The problem is when the 'load' event of the store is triggered, '$binding' is undefined, and thus the 'owner' property is unavailable.

The store and its listener for the 'load' event are defined in the ViewModel:

Ext.define('App.view.TSegmentacionFrmViewModel', { extend: '', alias: 'viewmodel.TSegmentacionFrm', requires: [ '', '', '' ], stores: { oStoreSegmentacion: { autoLoad: true, model: 'App.model.oGrid', proxy: { type: 'ajax', extraParams: { cmd: 'Get', cCodClass: 'SegmentacionBrw' }, url: "TGlobalData.ashx", useDefaultXhrHeader: false, reader: { type: 'json', rootProperty: 'aResultado', totalProperty: 'nRows' } }, listeners: { load: 'onJsonstoreLoad' } } } });

The store binding is defined in the View (line 58 of the following code):

Ext.define('App.view.TSegmentacionFrm', { extend: '', alias: 'widget.TSegmentacionFrm', requires: [ 'App.view.TSegmentacionFrmViewModel', 'App.view.TSegmentacionFrmViewController', '', 'Ext.toolbar.Toolbar', 'Ext.toolbar.Separator', 'Ext.grid.Panel', 'Ext.view.Table', 'Ext.grid.column.Action', 'Ext.form.Label', 'Ext.grid.column.RowNumberer' ], config: { [...] }, controller: 'TSegmentacionFrm', viewModel: { type: 'TSegmentacionFrm' }, cls: 'CustomTabs', itemId: 'TSegmentacionFrm', activeTab: 0, deferredRender: false, initConfig: function(instanceConfig) { var me = this, config = { items: [ { xtype: 'panel', itemId: 'oPnlHist', layout: { type: 'vbox', align: 'stretch' }, bind: { title: '{lbl_ListadoHist}' }, dockedItems: [ { [...] } ], items: [ { xtype: 'TMainBrowseGrid', cBrwName: 'oBrwSegmentacion', cCodForm: 'SegmentacionFrm', cls: 'CustomGrid', flex: 1, itemId: 'oGridHistorico', bind: { store: '{oStoreSegmentacion}' }, listeners: { selectionchange: 'onOGridProductosSelectionChange' }, columns: [...] } ] }, ] }; [...] }, });

And this is the onJsonstoreLoad method, in the ViewController:

Ext.define('App.view.TSegmentacionFrmViewController', { extend: '', alias: 'controller.TSegmentacionFrm', onJsonstoreLoad: function (store, records, successful, operation, eOpts) { // This '$binding' is undefined // Uncaught TypeError: Cannot read property 'owner' of undefined at g.onJsonstoreLoad var oView = store.$binding.owner.getView(); [...] } });

What am I doing wrong? The person who wrote this some time ago says it worked, but now it seems to be broken. Thank you.

How to decrypt md5 passwords in php with substr?

Tue, 10/17/2017 - 08:07

I am sharing my 2 file's code.for insert username and passwords and to retrieve data. My scenario is something different. if username : abc and password: 123456789

on login screen user have to enter only 3 digits from his password.But that will be random numbers from his password. if now system will ask me for 1st,3rd and 9th digit from password.after reload page it will change randomly. it will display 2nd,5th and 4th etc etc.

I am done this task earlier with my code. but now i am thinking to insert password with md5 encryption method.

I am stuck here if i used md5 for encryption then how to retrive password.

insert.php :

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <form action="" method="post"> <label>username</label> <input type="text" name="username"> <label>pin</label> <input type="password" name="pin"> <label>password</label> <input type="password" name="password"> <button name="submit">Submit</button> </form> </body> </html> <?php include 'conn.php'; if (isset($_POST['submit'])) { $name = $_POST['username']; $pass = md5($_POST['password']); $sql = mysqli_query($conn,'INSERT INTO `emp`(`name`, `pass`) VALUES ("'.$name.'","'.$pass.'")'); if ($sql>0) { header('Location: index.php'); } } ?>


<!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php include 'conn.php'; if (isset($_POST['submit'])) { $name = $_POST['username']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; $pass3 = $_POST['pass3']; $char1 = $_POST['char1']; $char2 = $_POST['char2']; $char3 = $_POST['char3']; $sql = 'SELECT name,pass,pin from `emp` ' . 'where `name` = "'.$name.'" ' . 'AND SUBSTR(pass, '.($char1).', 1) = \''.$pass1.'\' ' . 'AND SUBSTR(pass, '.($char2).', 1) = \''.$pass2.'\' ' . 'AND SUBSTR(pass, '.($char3).', 1) = \''.$pass3.'\' '; $sql = mysqli_query($conn,$sql); $data = mysqli_fetch_assoc($sql); if ($data) { echo 'success'; } else { echo 'Fail'; } } // generate unique, not equal numbers $char_pos = range(1, 9); shuffle($char_pos); $char_pos = array_slice($char_pos, 0, 3); sort($char_pos); ?> <form action="" method="post"> <input type="hidden" name="char1" value="<?php echo $char_pos[0]; ?>"> <input type="hidden" name="char2" value="<?php echo $char_pos[1]; ?>"> <input type="hidden" name="char3" value="<?php echo $char_pos[2]; ?>"> Username: <input type="text" name="username" value=""> Password: <input type="password" class="inputs" maxlength="1" name="pass1" placeholder='<?php echo $char_pos[0]; ?>st' value=""> <input type="password" class="inputs" maxlength="1" name="pass2" placeholder='<?php echo $char_pos[1]; ?>th' value=""> <input type="password" class="inputs" maxlength="1" name="pass3" placeholder='<?php echo $char_pos[2]; ?>th' value=""> <button name="submit">Submit</button> </form> <script src=""></script> <script> $(".inputs").keyup(function () { if (this.value.length == this.maxLength) { $(this).next('.inputs').focus(); } }); </script> </body> </html>

Unable to send Image in BirthDay Notification using Firebase Cloud Messaging

Tue, 10/17/2017 - 08:07

Problem Statement

I need to send Birthday Notifications to users each Day. I have to solve this problem using SpringBoot,MongoDb and FCM.


1)I first retrieved all users from Database and then checked their DateOfBirth with Current Date,If it matches then store these user details in a list.

2)Now,I have to send these users Notification using fcm.

How can I pass notification Image so that each User can see this Image. Can anyone guide how can i proceed?

Below is my Code :

@Scheduled(fixedRate = 86400) public void scheduleBirthdayNotification() { int pageSize=2000; Page<User> users=null; int page=0; users = userService.getAllUsers(new PageRequest(page,pageSize)); List<User> birthdays=new ArrayList(); LocalDate currentDate = new LocalDate(); for (User user : users) { Date dob=user.getDob(); LocalDate dobInFormat = new LocalDate(dob); if(currentDate.toString().equals(dobInFormat.toString())){ birthdays.add(user); } } sendBirthDayNotificationToUser(birthdays); } @Service public class FcmNotificationServiceImpl implements NotificationService{ private static final String API_KEY = "XYZ"; Sender fcm = new Sender(API_KEY); @Override public void sendBirthDayNotificationToUser(List<User> users) { List<String> registrationIds = new ArrayList<>(); for (User user : users) { registrationIds.add(user.getFcmId()); //Every user is having fcm id. } Message message = new Message.MessageBuilder() .addRegistrationToken(registrationIds) .addData("type", "Default") .addData("imageId", imageId) .addData("title","Birthday Message") .addData("content","Happy Birthday") .build(); sendNotification(registrationIds,message); } private void sendNotification(List<String> registrationIds,Message message) { for (int i=0;i<registrationIds.size();i=+1000) { fcm.send(message, new Callback() { @Override public void onResponse(Call call, Response response) { if(response.isSuccessful()) System.out.print("Notification Sent"); } @Override public void onFailure(Call call, Throwable t) { t.printStackTrace(); } }); } }

How to get description in this json format using php?

Tue, 10/17/2017 - 08:07

How to get description in this json format using php ?

This is json data

{ "items": [ { "id": "DHHlQxea3Pg", "snippet": { "description": "Private Jet trip to the Rocky Mountains 1080p" } } ] }

and this is my code

$curl_json_video_description = curl_init('some url'); curl_setopt($curl_json_video_description, CURLOPT_RETURNTRANSFER, true); $json_video_description = curl_exec($curl_json_video_description); $result_json_video_description = json_decode($json_video_description); $video_description = $result_json_video_description->items->snippet->description; echo $video_description;

When i test my code it's not echo anything, how can i do for get description in json ?

How can i call xaml button from mainactivity.cs on xamarin?

Tue, 10/17/2017 - 08:07

I'm working on a project to play a sound. I found out that to play sound I've to use, so I'm trying to shift all my work to mainactivity.cs. The problem I'm facing is I have no idea how to call xaml button from mainactivity.cs. I have read somewhere that we will have to create an interface. But I can't understand from the example provided. So any solution is really appreciated Thanks

Display cumulative value of each column in balloon text

Tue, 10/17/2017 - 08:07

I built a cumulative line graph using context.cumulativeCol() in the Value field and I am interested in displaying the cumulated value of the current column in the ballon text.

Here is what I have, which only shows the value of the column.

I tried to change the default value [[Row]], [[Column]]: [[Value]] from the Ballon Text field and tried to use something like context.cumulativeCol() but I could not achieve my goal.

If it is possible, how am I supposed to do it? I hope someone can help. Thanks.

No compiler working in Code Runner VSCode

Tue, 10/17/2017 - 08:07

I can't run anything in the VSCode. I've checked the java version also and the configuration for the CodeRunner and everything seems fine.

Can I update calculated field in the query

Tue, 10/17/2017 - 08:05

I have two tables. In table1 I have 2 columns like below, Doc No is (pk)

Doc No Title -------- ----------- Doc-0001 test-0001 Doc-0002 test-0002

In table 2 I also have two columns Doc No (pk), Transmittal (pk)

Doc No Transmittal -------------------------- Doc-0001 TT-0001 Doc-0001 TT-0002 Doc-0002 TT-1000

Now I want to create a form that has 3 fields based on table 1 like below, if I have related record for each Doc No in table2 it shows in the form with ticked check box in the form and when un ticked check box it deleted related records table2.

I have thought about that with steps like below but I have some doubt:

  1. I have to write a query based on table1 and it has a calculated column that returns (0) or (-1) if find related record in table 2.

    Doc No title checkbox
  2. I have to write a before update event for check box of the form for deleting related records in table 2 when untick the checkbox.

My question is about the calculated column in the query. Can I update that?

I mean can I untick that in the form? Or just it is a read only field and I cannot tick or untick that and so event procedure does not work on that?

What is the solution please?

NSInvalidArgumentException in swift

Tue, 10/17/2017 - 08:04

I 'm developing an iOS app. The app is at App Store already. In my crash reports i received such strange exception. My app name is NewGoMapV2.0.

NSInvalidArgumentException: -[_UITintColorVisitor _guideClass]: unrecognized selector sent to instance 0x154dcae50 1 CoreFoundation __exceptionPreprocess + 1202432 2 libobjc.A.dylib objc_exception_throw + 32636 3 CoreFoundation -[NSObject(NSObject) doesNotRecognizeSelector:] + 1230360 4 CoreFoundation ___forwarding___ + 1217972 5 CoreFoundation _CF_forwarding_prep_0 + 185992 6 UIKit existingAppearancesNodeInNodeForClass + 7554204 7 UIKit +[_UIAppearance _hasCustomizationsForClass:guideClass:] + 116052 8 UIKit -[UIView(Internal) _applyAppearanceInvocations] + 106648 9 UIKit __88-[UIView(Internal)_performUpdatesForPossibleChangesOfIdiom:orScreen:traverseHierarchy:]_block_invoke + 3310392 10 UIKit -[UIView(Internal) _performUpdatesForPossibleChangesOfIdiom:orScreen:traverseHierarchy:] + 3310256 11 UIKit -[UIView(Internal) _didChangeFromIdiomOnScreen:traverseHierarchy:] + 3310028 12 UIKit -[UIView(Internal) _didMoveFromWindow:toWindow:] + 61504 13 UIKit -[UIView(Internal) _didMoveFromWindow:toWindow:] + 60792 14 UIKit __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 58124 15 UIKit -[UIView(Hierarchy) _postMovedFromSuperview:] + 57716 16 UIKit -[UIView(Internal) _addSubview:positioned:relativeTo:] + 113532 17 UIKit -[UITableView _addContentSubview:atBack:] + 986196 18 UIKit __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 1447964 19 UIKit +[UIView(Animation) performWithoutAnimation:] + 141664 20 UIKit -[UITableView _configureCellForDisplay:forIndexPath:] + 1445572 21 UIKit -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 1686808 22 NewGoMapV2.0 specialized LeftSideViewController.tableView(UITableView, cellForRowAt : IndexPath) -> UITableViewCell (LeftSideViewController.swift:172) 23 NewGoMapV2.0 @objc LeftSideViewController.tableView(UITableView, cellForRowAt : IndexPath) -> UITableViewCell (LeftSideViewController.swift) 24 UIKit -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 3560216 25 UIKit -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 3560576 26 UIKit -[UITableView _updateVisibleCellsNow:isRecursive:] + 3491812 27 UIKit -[UITableView _performWithCachedTraitCollection:] + 3579820 28 UIKit -[UITableView layoutSubviews] + 1044616 29 UIKit -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 63348 30 QuartzCore -[CALayer layoutSublayers] + 60200 31 QuartzCore CA::Layer::layout_if_needed(CA::Transaction*) + 38708 32 QuartzCore CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 38388 33 QuartzCore CA::Context::commit_transaction(CA::Transaction*) + 35984 34 QuartzCore CA::Transaction::commit() + 35288 35 QuartzCore CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 8392 36 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 902532 37 CoreFoundation__CFRunLoopDoObservers + 893736 38 CoreFoundation CFRunLoopRunSpecific + 38556 39 UIKit -[UIApplication _run] + 533884 40 UIKit UIApplicationMain + 511372 41 NewGoMapV2.0 main (AppDelegate.swift:13) 42 libdyld.dylib start + 10420

As i understood it shows to the following point in source

let mycell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) as! LeftMenuTableViewCell

I cant understand, why this happened. I did not define any selector in even whole class.

Any suggestion. Thank you for attention.

Jenkins: Monitoring for JUnit test execution time?

Tue, 10/17/2017 - 08:01

In order to prevent performance degradation in my project, I would like to introduce some monitoring on the runtime of JUnit tests in jenkins. Ideally, I would like to see the execution time of tests over time as a diagram in Jenkins (i.e. a test execution time trend graph). The runtime of a single test (or test category) over time would also be interesting. RAM usage monitoring per test would be a nice-to-have too. I've seen some approaches online, people even go as far as using the SonarQube plugin just to have this kind of test execution time monitoring.

My question is: how do you tackle this problem? It seems like a very basic and straight-forward thing to do, but there doesn't seem to be a clear solution in Jenkins.

checkable item in android PopupMenu not working probably

Tue, 10/17/2017 - 07:52

I have a problem in my app when I'm using popup menu whith checkable item.

I wanted to implement multi check item in my popup menu but when clicking one item the menu disappear although I have set the checkable behavior to all

this is the menu layout

<menu xmlns:android=""> <group android:checkableBehavior="all"> <item android:id ="@+id/sun" android:checkable="true" android:title="@string/sun"/> <item android:id ="@+id/Mon" android:title="@string/Mon"/> <item android:id ="@+id/Tus" android:title="@string/Tus"/> <item android:id ="@+id/Wed" android:title="@string/wed"/> <item android:id ="@+id/Thu" android:title="@string/Thu"/> <item android:id ="@+id/fri" android:title="@string/fri"/> <item android:id ="@+id/Sat" android:title="@string/Sat"/> </group>

and this is the switch statement where I guess that the error is here but I cant find it

PopupMenu popupMenu = new PopupMenu(getBaseContext(), ch_specificDay); MenuInflater inflater = popupMenu.getMenuInflater(); inflater.inflate(, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case if(item.isChecked()) { item.setChecked(false); sunCheck = false; }else { item.setChecked(true); sunCheck = true; } break; case if(item.isChecked()) { item.setChecked(false); monCheck = false; }else { item.setChecked(true); monCheck = true; } break; case if(item.isChecked()) { item.setChecked(false); TusCheck = false; }else { item.setChecked(true); TusCheck = true; } break; case if(item.isChecked()) { item.setChecked(false); ThrChec= false; }else { item.setChecked(true); ThrChec = true; } break; case if(item.isChecked()) { item.setChecked(false); wenCheck= false; }else { item.setChecked(true); wenCheck = true; } break; case if(item.isChecked()) { item.setChecked(false); satCheck = false; }else { item.setChecked(true); satCheck = true; } break; case if(item.isChecked()) { item.setChecked(false); FriCheck = false; }else { item.setChecked(true); FriCheck = true; } break; default: break; } return true ; } });; break; default:

Why is my code for calculating derivatives using central difference method keep returning 0s and 1s?

Tue, 10/17/2017 - 07:52

I'm trying to run a program that will calculate the first and second derivative of a linear function f(x)=x and a cubic function f(x)=x^3 using central difference. I need to use function prototypes to write both of those as functions that take a double as an argument and return a double. The program is supposed to feed the functions into the same derivative operator and then calculate the derivatives at x=0.5 and x=1. When I run the code and enter in a value for x, no matter what I enter I keep getting back 1 as the first derivative and 0 as the second (for both the linear and cubic function). I've been trying to figure out what I'm doing wrong for hours now and no matter what I try to do I still get back only 1s and 0s.

I figure I could write this without using the function prototype, but I'm not supposed to do that and it's neater using the prototypes. I've been trying to find examples and nothing has really helped me because all of the functions declared (in the examples) have multiple parameters and are using if/else statements, and I don't, I also don't know if those would even help me.

What am I doing wrong? (Sorry for the long code, I'm not sure where I've gone wrong so I didn't want to exclude anything).

Edit: I excluded that the first and second derivative need to be calculated.

double linearFunctionPrime(double f1Prime); double linearFunctionDoublePrime(double f1DoublePrime); double cubicFunctionPrime(double f2Prime); double cubicFunctionDoublePrime(double f2DoublePrime); int main() { double x; double f1P, f1PP; double f2P, f2PP; cout << "Enter a number to calculate the derivatives for f(x)=x and\ f(x)=x^3" << endl; cin >> x; cout << setprecision(10); f1P = linearFunctionPrime(x); cout << "f'(x) = " << f1P << endl; f1PP = linearFunctionDoublePrime(x); cout << "f''(x) = " << f1PP << endl; f2P = cubicFunctionPrime(x); cout << "f'(x^3) = " << f2P << endl; f2PP = cubicFunctionDoublePrime(x); cout << "f''(x^3) = " << f2PP << endl; return 0; } double h = pow(10, -5); double linearFunctionPrime(double x) { double f1, f1Prime; f1 = x; f1Prime = ((f1+h)-(f1-h))/(2.0*h); return f1Prime; } double linearFunctionDoublePrime(double x) { double f1, f1DoublePrime; f1 = x; f1DoublePrime = ((f1+h)+(f1-h)-2.0*(x))/(pow(h, 2.0)); return f1DoublePrime; } double cubicFunctionPrime(double x) { double f2, f2Prime; f2 = pow(x, 3.0); f2Prime = ((f2+h)-(f2-h))/(2.0*h); return f2Prime; } double cubicFunctionDoublePrime(double x) { double f2, f2DoublePrime; f2 = pow(x, 3.0); f2DoublePrime = ((f2+h)+(f2-h)-2.0*(f2))/(pow(h, 2.0)); return f2DoublePrime; }

Why can an (irrelevant) using declaration reconcile overload ambiguity with Argument-Dependent Lookup?

Tue, 10/17/2017 - 07:48

This is a follow up of the question here on function overload with Argument-Dependent Lookup (ADL). I wanted to check my understanding of the rules under these circumstances so I wrote some test code.

First, there is no swap for HasPtr class in std, of course, so I wrote a namespace of my own which contains a HasPtr version of swap in addition to the one already defined in global scope. The using declaration works as what I expected -- an error of ambiguity was produced because there is a HasPtr version of swap already defined as does in "C++ Primer", 5ed.

Then I want to see what will happen if I change using declaration to using directive. The book says the compiler will keep silent until the function is actually called. I wanna verify that so the code is as follows:

#include <string> class HasPtr { public: friend void swap(HasPtr&, HasPtr&); std::string *ps; }; void swap(HasPtr &lhs, HasPtr &rhs) { swap(,; // swap the pointers, not the string data } namespace myNS { void swap(HasPtr &lhs, HasPtr &rhs) { std::string s = "in my name space"; swap(,; // swap the pointers, not the string data } } class Foo { friend void swap(Foo &lhs, Foo &rhs); HasPtr h; }; void swap(Foo &lhs, Foo &rhs) { using std::swap; //<- commenting this line will cause error using namespace myNS; swap(lhs.h, rhs.h); } int main() { Foo f1, f2; swap(f1, f2); }

Strange thing happened in line 27 (using std::swap;). If I commented it out, the name myNS::swap which has exactly the same signature as the one already defined in global scope was lifted to global scope and consequently causes an error of overloading ambiguity, as I expected.

But, if I do not comment line 27 and compile, no error of ambiguity is reported. And the program executes the ::swap originally defined in global scope as if the using directive using namespace myNS; does not lift myNS::swap so that it is not added to the candidate set for overloading. I just couldn't understand this phenomenon. Why can a using declaration from an irrelevant namespace (std certainly does not contain a HasPtr version of swap) reconcile overload ambiguity under ADL? Why is it the original ::swap, instead of its rival in myNS, that is selected to execute? Does the line 27 have any side effects to overloading process (say, suppressing names from lifted namespace so original names have a higher priority)? Thank you for your answers.

The problem can be reproduced in Visual Studio 2015 Update 3 on Windows 7 and in GCC 4.8.4 on ubuntu 14.04, both 64-bit.

Which occasion does trigger GC in Java?

Tue, 10/17/2017 - 07:45

I'm trying to learn how Parallel GC works and now I'm reading this article:

Trying it myself I found the following line:

[GC (GCLocker Initiated GC) [PSYoungGen: 4000739K->93296K(4034048K)] 5488394K->1629174K(6578176K), 0.0492402 secs] [Times: user=0.40 sys=0.00, real=0.05 secs]

It means the minor GC was triggered. But the reason was not allocation faulire? So what was actually the cause of that GC? Is it possible to turn it off?

Laravel migration in different branches

Tue, 10/17/2017 - 07:42

In my app builded with laravel 5.1, I have a branch dev.

I had to implement 2 new feature, so I created first branch (starting from dev) that needed 2 tables (so new migrations), then, when I finished it, I created second branch (starting to dev) and also this feature needed a different table so new migration.

So my situation is something like:

branch 1 -> migration1 branch 2 -> migration2, migration3

But now I need to change (many columns) the table related to branch1 so I should rollback migration, because I would not make new migration for change but I would rollback migration and recreate.

But My problem now is that if I return in my branch1 and try to do:

php artisan:migrate rollback

The latest migrations (on my db) are the tables for branch2 (migration2, migration3) and not the table related to branch1 (migration1).

So what is the right way for manage migration beetwen many branch?

How to take First later from the string with comma separated?

Tue, 10/17/2017 - 07:35

I have one array and I store comma separated strings in the array. Now I want to take in the string every first later take from the string with comma separated.
For ex => Abc, Xyz, Hji so now I want A, X, H.

Here below listed my code and array.

This is my code =>

var ArryString = []; for (var i = 0; i < data.length; i++) { ArryString.push(data[i].Str); }

Current o/p =>

"Abc" "Xyz,Hji,Lol", "Uyi,Mno"

my expacted o/p= >

"A" "X,H,L" "U,M"

Base64 encoded image is not showing in gmail

Tue, 10/17/2017 - 06:13

I have an embedded HTML email in which I'm using a base64 encoded image. Image doesn't show in gmail when accessing via chrome. But it works fine when accessing same mail via mail client(Mail application on Mac). I have set headers correctly. Any idea?

My code

<html> <body>Hi <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAREAAAALCAYAAABYrrnHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABANpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ1dWlkOjVEMjA4OTI0OTNCRkRCMTE5MTRBODU5MEQzMTUwOEM4IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjVGMjU1MzZBQUVGQjExRTc5NUQyQTc1MzA0RERGMTVGIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjVGMjU1MzY5QUVGQjExRTc5NUQyQTc1MzA0RERGMTVGIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIElsbHVzdHJhdG9yIENDIDIwMTcgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0idXVpZDpiNDQ5NzVjYy00YmI1LTRmNzAtODRiZi0zMGU2NjFkYmY3ZDMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6ZDc1MTVmZDQtMjkzZS00ZWI5LWFiMjQtOTMzYzRkZjNmOTY4Ii8+IDxkYzp0aXRsZT4gPHJkZjpBbHQ+IDxyZGY6bGkgeG1sOmxhbmc9IngtZGVmYXVsdCI+bXRrYV9hY3RpdmF0aW9uX2NhcmQ8L3JkZjpsaT4gPC9yZGY6QWx0PiA8L2RjOnRpdGxlPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pr6AOtYAAABESURBVHja7NZBDQAwCARB2tS/m6qoKIoGvswkGNjHhQgAAACAeVbdkwHoOnVXBqD9iWSmCkDblgAwIoARAYwIMNAXYACy9wSMWMVdzAAAAABJRU5ErkJggg==" width="273" height="11" alt=""> </body> </html>


Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable

using multiprocessing to handle socket

Tue, 10/17/2017 - 05:14

I have a server with main process acepting socket connections and put them in Queue stack and another process monitoring this stack and applying it to pool processes handling connections. All works fine except for one thing:

  • last connection allways at stuck until another connection appears, it's look like last connection can't be closed, but why?
from multiprocessing import Queue, Process, Pool, Manager import datetime import socket def get_date(): return'%H:%M:%S') class Server: def __init__(self, host, port): self.server_address = host, port self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def run(self): self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind(self.server_address) self.server_socket.listen(1) print('listen at: %s:%s' % self.server_address) q = Manager().Queue() Process(target=self.handle_request, args=(q,)).start() while True: client_socket, adress = self.server_socket.accept() print('\n[%s] request from: %s:%s' % (get_date(), *adress)) q.put(client_socket) client_socket.close() del client_socket # client_socket.close() not working def help(self, client_socket): data = client_socket.recv(512) client_socket.send(data) client_socket.close() print(data[:50]) def handle_request(self, q): with Pool(processes=2) as pool: while True: pool.apply_async(, (q.get(),)) Server('localhost', 8000).run()

Missing arguments and type errors

Tue, 10/17/2017 - 03:17

I was instructed to run the current code and understand the error message and change only one line of the function bs and fix the error I can kind of understand what the error message is saying, but I don't know how to fix it or where the actual problem is occurring in the function bs

def bs(L, item, left, right): if right is None: right = len(L) if right - left == 0: return False if right - left == 1: return L[left] == item median = (right + left)//2 if item < L[median]: return bs(L, item, left, median) else: return bs(L, item, median, right) L = [i for i in range(10)] for i in range(20): print(bs(L, i))

The error is the following

print(bs(L, i)) TypeError: bs() missing 2 required positional arguments: 'left' and 'right'