input
stringlengths
51
42.3k
output
stringlengths
18
55k
How to give interactive inputs in a single line for .exe windows <p>I am trying to automate one process which involves giving interactive input to a .exe utility. It expects the user-input for each step. I wanted to give all those values at single time while giving that command only. For eg: <code>./test.exe 8\n1\n0</code> etc. I have tried multiple ways to give input to the 'test.exe' utility like <code>8\n1\n0 | ./test.exe</code> and <code>8,1,2 | ./test.exe</code>. None of these worked. Any help how to pass these options 8,1,2 to the interactive utility test.exe in single line so that it will be helpful for my automation</p>
<p>There is no set way to automate a 3rd party program with Powershell. Not all utilities even offer the ability to do so.</p> <ol> <li><p>I'd look in the utility documentation for any switches.</p></li> <li><p>Try the following to see if you can get any built in help: test.exe -h, test.exe /h, test.exe /?, test.exe -?</p></li> <li><p>use the sysinternals strings utility to try and find anything that look like command line switches inside the exe that you can take advantage of. <a href="https://technet.microsoft.com/en-us/sysinternals/strings.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">https://technet.microsoft.com/en-us/sysinternals/strings.aspx?f=255&amp;MSPPError=-2147217396</a></p></li> </ol>
Entity Framework M:1 relationship resulting in primay key duplication <p>I'm somewhat new to EF 6.0 so I'm pretty sure I'm doing something wrong here. there are two questions related to the problem</p> <ol> <li>what am I doing wrong here</li> <li>what's the best practice to achieve this</li> </ol> <p>I'm using a code first model, and used the edmx designer to design the model and relationships, the system needs to pull information periodically from a webservice and save it to a local database (SQL Lite) in a desktop application</p> <p><a href="https://i.stack.imgur.com/AicE1.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/AicE1.jpg" alt="enter image description here"></a></p> <p>so I get an order list from the API, when I populate and try to save Ticket, I get a duplicate key exception when trying to insert TicketSeatType - </p> <p>how do I insert the ticket to dbContext, so that It doesn't try and re-insert insert TicketSeatType and TicketPriceType, I have tried setting the child object states to unchanged but it seems to be inserting</p> <p>secondly, what would be the best practice to achieve this using EF ? it just looks very inefficient loading each object into memory and comparing if it exists or not</p> <p>since I need to update the listing periodically, I have to check against each object in the database if it exists, then update, else insert</p> <p>code:</p> <pre><code>//read session from db if (logger.IsDebugEnabled) logger.Debug("reading session from db"); dbSession = dbContext.SessionSet.Where(x =&gt; x.Id == sessionId).FirstOrDefault(); //populate orders List&lt;Order&gt; orders = (from e in ordersList select new Order { Id = e.OrderId, CallCentreNotes = e.CallCentreNotes, DoorEntryCount = e.DoorEntryCount, DoorEntryTime = e.DoorEntryTime, OrderDate = e.OrderDate, SpecialInstructions = e.SpecialInstructions, TotalValue = e.TotalValue, //populate parent refernece Session = dbSession }).ToList(); //check and save order foreach (var o in orders) { dbOrder = dbContext.OrderSet.Where(x =&gt; x.Id == o.Id).FirstOrDefault(); if (dbOrder != null) { dbContext.Entry(dbOrder).CurrentValues.SetValues(o); dbContext.Entry(dbOrder).State = EntityState.Modified; } else { dbContext.OrderSet.Add(o); dbContext.Entry(o.Session).State = EntityState.Unchanged; } } dbContext.SaveChanges(); //check and add ticket seat type foreach (var o in ordersList) { foreach (var t in o.Tickets) { var ticketSeatType = new TicketSeatType { Id = t.TicketSeatType.TicketSeatTypeId, Description = t.TicketSeatType.Description }; dbTicketSeatType = dbContext.TicketSeatTypeSet.Where(x =&gt; x.Id == ticketSeatType.Id).FirstOrDefault(); if (dbTicketSeatType != null) { dbContext.Entry(dbTicketSeatType).CurrentValues.SetValues(ticketSeatType); dbContext.Entry(dbTicketSeatType).State = EntityState.Modified; } else { if (!dbContext.ChangeTracker.Entries&lt;TicketSeatType&gt;().Any(x =&gt; x.Entity.Id == ticketSeatType.Id)) { dbContext.TicketSeatTypeSet.Add(ticketSeatType); } } } } dbContext.SaveChanges(); //check and add ticket price type foreach (var o in ordersList) { foreach (var t in o.Tickets) { var ticketPriceType = new TicketPriceType { Id = t.TicketPriceType.TicketPriceTypeId, SeatCount = t.TicketPriceType.SeatCount, Description = t.TicketPriceType.Description }; dbTicketPriceType = dbContext.TicketPriceTypeSet.Where(x =&gt; x.Id == ticketPriceType.Id).FirstOrDefault(); if (dbTicketPriceType != null) { dbContext.Entry(dbTicketPriceType).CurrentValues.SetValues(ticketPriceType); dbContext.Entry(dbTicketPriceType).State = EntityState.Modified; } else { if (!dbContext.ChangeTracker.Entries&lt;TicketPriceType&gt;().Any(x =&gt; x.Entity.Id == ticketPriceType.Id)) { dbContext.TicketPriceTypeSet.Add(ticketPriceType); } } } } dbContext.SaveChanges(); //check and add tickets foreach (var o in ordersList) { dbOrder = dbContext.OrderSet.Where(x =&gt; x.Id == o.OrderId).FirstOrDefault(); foreach (var t in o.Tickets) { var ticket = new Ticket { Id = t.TicketId, Quantity = t.Quantity, TicketPrice = t.TicketPrice, TicketPriceType = new TicketPriceType { Id = t.TicketPriceType.TicketPriceTypeId, Description = t.TicketPriceType.Description, SeatCount = t.TicketPriceType.SeatCount, }, TicketSeatType = new TicketSeatType { Id = t.TicketSeatType.TicketSeatTypeId, Description = t.TicketSeatType.Description }, Order = dbOrder }; //check from db dbTicket = dbContext.TicketSet.Where(x =&gt; x.Id == t.TicketId).FirstOrDefault(); dbTicketSeatType = dbContext.TicketSeatTypeSet.Where(x =&gt; x.Id == t.TicketSeatType.TicketSeatTypeId).FirstOrDefault(); dbTicketPriceType = dbContext.TicketPriceTypeSet.Where(x =&gt; x.Id == t.TicketPriceType.TicketPriceTypeId).FirstOrDefault(); if (dbTicket != null) { dbContext.Entry(dbTicket).CurrentValues.SetValues(t); dbContext.Entry(dbTicket).State = EntityState.Modified; dbContext.Entry(dbTicket.Order).State = EntityState.Unchanged; dbContext.Entry(dbTicketSeatType).State = EntityState.Unchanged; dbContext.Entry(dbTicketPriceType).State = EntityState.Unchanged; } else { dbContext.TicketSet.Add(ticket); dbContext.Entry(ticket.Order).State = EntityState.Unchanged; dbContext.Entry(ticket.TicketSeatType).State = EntityState.Unchanged; dbContext.Entry(ticket.TicketPriceType).State = EntityState.Unchanged; } } } dbContext.SaveChanges(); </code></pre> <h1>UPDATE:</h1> <p>Found the answer, it has to do with how EF tracks references to objects, in the above code, I was creating new entity types from the list for TicketPriceType and TicketSeatType:</p> <pre><code> foreach (var o in ordersList) { dbOrder = dbContext.OrderSet.Where(x =&gt; x.Id == o.OrderId).FirstOrDefault(); foreach (var t in o.Tickets) { var ticket = new Ticket { Id = t.TicketId, Quantity = t.Quantity, TicketPrice = t.TicketPrice, TicketPriceType = new TicketPriceType { Id = t.TicketPriceType.TicketPriceTypeId, Description = t.TicketPriceType.Description, SeatCount = t.TicketPriceType.SeatCount, }, TicketSeatType = new TicketSeatType { Id = t.TicketSeatType.TicketSeatTypeId, Description = t.TicketSeatType.Description }, Order = dbOrder }; .... </code></pre> <p>in this case the EF wouldn't know which objects they were and try to insert them. </p> <p>the solution is to read the entities from database and allocate those, so it's referencing the same entities and doesn't add new ones</p> <pre><code>foreach (var t in o.Tickets) { //check from db dbTicket = dbContext.TicketSet.Where(x =&gt; x.Id == t.TicketId).FirstOrDefault(); dbTicketSeatType = dbContext.TicketSeatTypeSet.Where(x =&gt; x.Id == t.TicketSeatType.TicketSeatTypeId).FirstOrDefault(); dbTicketPriceType = dbContext.TicketPriceTypeSet.Where(x =&gt; x.Id == t.TicketPriceType.TicketPriceTypeId).FirstOrDefault(); var ticket = new Ticket { Id = t.TicketId, Quantity = t.Quantity, TicketPrice = t.TicketPrice, TicketPriceType = dbTicketPriceType, TicketSeatType = dbTicketSeatType, Order = dbOrder }; ...} </code></pre>
<p><strong><em>Don't you think that you are trying to write very similar codes for defining the state of each entity?</em></strong> We can handle all of these operations with a single command.</p> <p>You can easily achieve this with the newly released <a href="https://www.nuget.org/packages/EntityGraphOperations/" rel="nofollow">EntityGraphOperations</a> for Entity Framework Code First. I am the author of this product. And I have published it in the <a href="https://github.com/FarhadJabiyev/EntityGraphOperations" rel="nofollow">github</a>, <a href="http://www.codeproject.com/Tips/1131322/Automatically-Define-the-State-of-All-Entities-in" rel="nofollow">code-project</a> (<em>includes a step-by-step demonstration and a sample project is ready for downloading)</em> and <a href="https://www.nuget.org/packages/EntityGraphOperations/" rel="nofollow">nuget</a>. With the help of <code>InsertOrUpdateGraph</code> method, it will automatically set your entities as <code>Added</code> or <code>Modified</code>. And with the help of <code>DeleteMissingEntities</code> method, you can delete those entities which exists in the database, but not in the current collection.</p> <pre><code>// This will set the state of the main entity and all of it's navigational // properties as `Added` or `Modified`. context.InsertOrUpdateGraph(ticket); </code></pre> <p>By the way, I feel the need to mention that this wouldn't be the most efficient way of course. The general idea is to get the desired entity from the database and define the state of the entity. It would be as efficient as possible.</p>
How to fix Alamofire library errors? <p>I am using Xcode7.3.1 and i added Alamofire (4.0.1) version.But when i tried to run the project then i got many errors in Alamofire library.Please find attached screenshot contains errors.My podfile contain like the following.How to fix these errors?</p> <pre><code># Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'ALamoWeather' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for ALamoWeather pod 'Alamofire' end </code></pre> <p><a href="https://i.stack.imgur.com/RwpsB.png" rel="nofollow"><img src="https://i.stack.imgur.com/RwpsB.png" alt="enter image description here"></a></p>
<p>Alamofire 4.0.1 is using Swift 3, while Xcode 7.x doesn't support it. You should upgrade to Xcode 8 in order to use the newest Alamofire.</p>
Validate end_date is after start_date <p>I have a form with two date fields, <code>start_date</code> and <code>end_date</code>. I want to create a rule that <code>end_date</code> must be greater then <code>start_date</code>, and if this condition returns <code>false</code> then to show validation errors as in the picture below. </p> <p><a href="https://i.stack.imgur.com/wd0Kt.png" rel="nofollow"><img src="https://i.stack.imgur.com/wd0Kt.png" alt="enter image description here"></a></p> <p>So far I've tried to do so by creating a custom rule:</p> <pre><code>$.validator.addMethod("check_date", function(value, element) { var start_date = $("input[name='start_date']").val(); var end_date = $("input[name='end_date']").val(); return end_date(value) &gt; start_date(value); }, 'End date must be greater then start date.'); </code></pre> <p>I'm not sure how exactly I set the rule and the message.</p>
<p>Got it.</p> <pre><code> $.validator.addMethod("check_date", function(value, element) { var start_date = $("input[name='start_date']").val(); var end_date = $("input[name='end_date']").val(); return end_date &gt; start_date; }, 'End date must be greater then Start date.'); </code></pre>
Unresolved android dependency issue <p>Hi I am new to Android Studio and I am using <strong>Android studio 2.2.1.</strong> When I am trying to create a new project I am getting the the errors as shown in the screenshot.</p> <p><a href="https://i.stack.imgur.com/KZoL6.png" rel="nofollow"><img src="https://i.stack.imgur.com/KZoL6.png" alt="image"></a></p>
<p>You need to download the dependencies. Find the the SDK Manager and download the yellow ones which are the most importants</p> <p><a href="https://i.stack.imgur.com/yEvXX.png" rel="nofollow"><img src="https://i.stack.imgur.com/yEvXX.png" alt="enter image description here"></a></p> <p>If you still have problems, try to follow the official guide <a href="https://developer.android.com/topic/libraries/support-library/setup.html" rel="nofollow">here</a></p>
creating multiple folders inside current directory in c++ <p>I want to make some folders using a loop in current directory in c++. I have made a code but getting the following error.</p> <blockquote> <p>cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'void CreateFolder(const char*)'</p> </blockquote> <p>My code is:</p> <pre><code> #include&lt;iostream&gt; #include&lt;cstdio&gt; #include&lt;cstring&gt; #include &lt;windows.h&gt; #include &lt;cstdio&gt; #include&lt;cstdlib&gt; #include&lt;fstream&gt; #include &lt;sstream&gt; using namespace std; #define total 28 std::string to_string(int i) { std::stringstream s; s &lt;&lt; i; return s.str(); } void CreateFolder(const char * path) { if(!CreateDirectory(path ,NULL)) { return; } } main() { string folder_name; string suffix = ".\\"; // for current directory for(int i=0;i&lt;=total;i++) { folder_name=suffix+to_string(i); CreateFolder(folder_name); } } </code></pre> <p>How will I create those folders named 0,1... to 28?</p>
<p>You can not directly pass a <code>std::string</code> as <code>char*</code>. By using <code>c_str()</code> function you can retrieve the raw <code>char*</code> from <code>std::string</code>.</p> <pre><code>//std::string -&gt; const char* CreateFolder(folder_name.c_str()); </code></pre>
How to handle a missing lat long values from ajax response. How to detect and give appropriate alert to the user <p>I am getting a json response from ajax call like this below</p> <pre><code>{"metadata":{"assetStatusAvailable":false},"data":[{"id":"209880948","name":"1:Periodic Report","domainObjectType":"assetmessageevent","domainObjectTypeId":"assetmessageevent_209880948","heading":null,"latitude":,"longitude":,"isAlertEvent":false,"eventTime":"2016-10-03T04:53:02","assetCategory":"Underground Tank 15000GL","configurationName":"Tank","mapCurrentSymbol":"","asset":{"id":"209843212","name":"TANK001","domainObjectType":"tank","domainObjectTypeId":"tank_209843212"}}]} </code></pre> <p>Here latitude and longitude is missing so it's not parsed and hence throws an error. How to handle such scenario and give appropriate message to the user.</p>
<p>Use following function to check a blank value and null value of latitude, longitude</p> <pre><code>var checkBlankValue(){ $.each(obj.data, function(key, value){ if (key=='latitude' || key=='longitude'){ if (value === "" || value === null){ return false; } } }); return true; } </code></pre> <p>Check latitude, longitude blank value in data if any blank value in data then above function return false then you are able to display message to user.</p> <p>Something like this</p> <pre><code>if (!checkBlankValue){ return "your message"; } </code></pre>
Custom wordpress Form submission <p>I want to insert data into database table through custom php form in wordpress. I don't want to use/create plugins/hooks. just simple form for client so he can edit himself whenever he want.</p> <p>I tried <br></p> <pre><code>if($_POST['submit']) {&lt; submit to db &gt; } else { &lt; display html form &gt;&lt;br&gt; } </code></pre> <p><br>with action="" . this redirect to the same page without any error on page + in console. javascript validations on fields are working perfect.</p> <p>I tried another solution by creating a php file in themes folder, and setting action="../that_file.php", which gave 404 error. </p> <p>Any other solution? </p>
<p>you have to follow the WordPress file structure like page.that_file.php under your theme folder and calling header and footer in it and hit the page to check it work or not. After checking it call the page in your action form still you get 404 than issue in your calling function. </p>
How to rename master branch and make another branch as master? <p>I have several branches in my repo - master, production, staging, other_stuff I want to set my production branch as master, and rename my master branch to master_legacy.</p> <p>How can I do it? Actually I found guide, but I'm not sure, whether I can implement it here:</p> <pre><code>git checkout production git merge -s ours master git checkout master git merge production </code></pre>
<p>If you really just want to rename the branches and not merge information together; I would go for:</p> <pre><code>git branch master_legacy master # create a new branch master_legacy where master is git branch -D master # force deleting the master branch git branch master production # create a new master branch where production is </code></pre> <p>afterwards you might need to do some cleanup such as:</p> <pre><code>git push -f origin master # force pushing the new master to your remote </code></pre>
Get geo locations repeatedly (after every.. 1 minute ) <p>I am calling toast message in <code>AndroidGPSTrackingActivity.class</code>. how to fetch geo locations after every 1 minutes.. With below code I am getting only once </p> <pre><code>public class AndroidGPSTrackingActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gps = new GPSTracker(AndroidGPSTrackingActivity.this); // check if GPS enabled if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); Toast.makeText( getApplicationContext(),"Your Locion is - \nLat: " + latitude + "\nLog: " + longitude, Toast.LENGTH_LONG).show(); System.out.println("respmaillati::;;"+latitude); } else { gps.showSettingsAlert(); } } </code></pre> <p>in manifest I given </p> <pre><code>&lt;service android:name=".GPSTracker" /&gt; </code></pre> <p>Code:</p> <pre><code>public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 100 * 60 * 1; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled &amp;&amp; !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } System.out.println("responsel:::"+latitude); // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude System.out.println("responsel:::"+longitude); return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } </code></pre>
<p>Use <a href="http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html" rel="nofollow">google Fusion api example</a> for get location in interval.</p>
Bitbucket doesn't create visual branch <p>I'm new to git and working with bitbucket. Did I do something wrong that bitbucket doesn't show a visual branch? It looks like i'm still working in master. I have other commits before in the master branch.</p> <p><a href="https://i.stack.imgur.com/vDibk.png" rel="nofollow"><img src="https://i.stack.imgur.com/vDibk.png" alt="enter image description here"></a></p>
<p>You did not do anything wrong. Bitbucket shows your commit history just like it is: a linear list of commits (some of which have branches pointing to them). In git, a branch is merely a pointer to a commit.</p> <p>As soon as you make divergent commits on the two branches, you will see two visual branches on the graph.</p>
Cron Job (Quartz.NET) in .NET is not triggering daily <p>I have scheduled a cron Job in .NET and the same is hosted in IIS. On the first day it has triggered ( for testing purpose i actually send mail when this job is triggered). But the next day it has not (i want this to be recursive on daily basis ... every 24 Hrs once) Please find the code below.[![enter image description here][1]][1]</p> <pre><code>public class JobScheduler { public static void Start() { try { Logger.Error("-------------------------------------------Inside JobScheduler Start-------------------------------------------"); IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); IJobDetail job = JobBuilder.Create&lt;QualityGateSFDCActionJob&gt;().Build(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger3", "group1").WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(11, 42)).ForJob(job).Build(); scheduler.ScheduleJob(job, trigger); Logger.Error("-------------------------------------------Scheduler Started without Issues-------------------------------------------"); } catch (Exception ex) { Logger.Error(ex.Message); throw ex; } } } </code></pre> <p>Some on kindly help on this. </p> <pre><code>ITrigger trigger = TriggerBuilder.Create().WithIdentity("trigger3", "group1").WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(11, 42)).ForJob(job).Build(); </code></pre> <p>I just want this job to run daily in the morning 11:42 AM. I would be thank full for any help in this regard</p> <p>Application is built up on ASP.NET MVC and hosted on IIS. I want a job to be run on a daily basis, That's why i choose Cron Job (Windows service is out of context/scope in my production server)</p>
<p>IIS has a feature called "Recycling". This basically reloads everything in IIS.</p> <p>If you go into Advanced Settings of your Application Pool in the IIS Manager there is an Recycling Interval which by default is 1740 minutes (29 hours)</p> <p>When IIS Recycles, your application will not begin running until something calls the webservice. So once every 29 hours it will recycle, so depending on when you started your webservice it will run your Cron job once or twice but never a 3rd time unless you have called your webservice after the recycle to restart it. </p> <p>Basically, IIS is not a good place to host an application which needs to be always running jobs. </p>
How to generate automatically Makefile in vim (c/c++) super fast? <p>I'm quite new to vim, have installed few plugins one of them is SnipMate, which is quite useful while writing a short Makefile.</p> <pre><code>snippet base PHONY: clean, mrproper CC = gcc CFLAGS = -g -Wall all: $1 %.o: %.c $(CC) $(CFLAGS) -c -o $@ $&lt; ${1:OUTPUT_FILENAME}: $1.o $(CC) $(CFLAGS) -o $@ $+ clean: rm -f *.o core.* mrproper: clean rm -f $1 </code></pre> <p>but still it takes time to add manually the file names, I'm quite sure with some <strong>Vim Magic</strong> :) , Vim would able to do it <strong>automatically</strong> (executing it via hotkey) after I have wrote those c files, any suggestions?</p> <p>Thank you all!</p>
<p>You can extract filenames automatically with <code>glob()</code>, and <code>globpath()</code> (don't ask me about SnipMate syntax to import the result -- I'm maintaining another template/snippet plugin). </p> <p>But if you always use <strong>everything</strong> automatically, why don't you do it directly with make? There are ways to automatically glob filenames that match a pattern. If you need to trim files, well in that case listing explicitly every file you want to keep makes sense. But don't forget to remove unwanted files every time you trigger the <em>update the file list</em> action you wish to define.</p> <p>BTW, IIRC, a properly configured gnumake (i.e, not mingw one) already has the rule for <code>%.o: %.c</code></p>
How i can put my changeable pictures as wallpaper to homescreen...! <p>I have several picture to display it as live wallpaper I have this code but it doesn't change anything,,,,,,,,,,,,,,!! I'm newbie I just did copy paste this code I don't understand anything please can someone help me</p> <pre><code> public class MainActivity extends WallpaperService{ Handler handler; public void onCreate() { super.onCreate(); } public void onDestroy() { super.onDestroy(); } public Engine onCreateEngine() { return new CercleEngine(); } class CercleEngine extends Engine { public Bitmap image1, image2, image3; CercleEngine() { image1 = BitmapFactory.decodeResource(getResources(), R.drawable.greenww); image2 = BitmapFactory.decodeResource(getResources(), R.drawable.redww); image3 = BitmapFactory.decodeResource(getResources(), R.drawable.screen3); } public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); } public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels) { drawFrame(); } void drawFrame() { final SurfaceHolder holder = getSurfaceHolder(); Canvas c = null; try { c = holder.lockCanvas(); if (c != null) { c.drawBitmap(image1, 0, 0, null); c.drawBitmap(image2, 0, 0, null); c.drawBitmap(image3, 0, 0, null); } } finally { if (c != null) holder.unlockCanvasAndPost(c); } handler.removeCallbacks(drawRunner); if (isVisible()) { handler.postDelayed(drawRunner, 1000); // delay 1 sec } } private final Runnable drawRunner = new Runnable() { @Override public void run() { drawFrame(); } }; } </code></pre>
<p>I know two ways to do it:</p> <p>1)For creating live wallpaper you need to extend <a href="https://developer.android.com/reference/android/service/wallpaper/WallpaperService.html" rel="nofollow">WallpaperService</a>. Good tutorial - <a href="http://www.vogella.com/tutorials/AndroidLiveWallpaper/article.html" rel="nofollow">http://www.vogella.com/tutorials/AndroidLiveWallpaper/article.html</a></p> <p>2) Set AlarmManager( tutorial - <a href="https://developer.android.com/training/scheduling/alarms.html" rel="nofollow">https://developer.android.com/training/scheduling/alarms.html</a>) and change pictures every tick.</p>
Finding a "trail" in 2-D dimention arrays <p>I don't know how to figure out this question, I am just a beginner to computer science.</p> <p>The input will be 2D array A[n][n] numbers, representing the topographic map of the geographic surface. Also among the input will be a starting location (r,c). referring to entry A[r][c]</p> <p>If you were planning hiking trails you would be bound by the differences in elevation between neighboring entries. A person could traverse between 2 adjacent locations, if their elevations differ by no more than 2). Adjacency follows just the 4 standard compass directions, (so I assume no diagonals). Therefore , a point on the map is considered reachable if it is traversable from A[r][c] through any sequence of adjacent entires.</p> <p>Write an algorithm that computes all of the reachable locations. The output will be another 2D array R[n][n] with true/fals values. (I assume true means reachable, false means unreachable)</p> <p>If i understand this question correctly, I can create following matrix. (suppose A[10][10] looks like this from A[0][0]:)</p> <pre><code>50 51 54 58 60 60 60 63 68 71 48 52 51 59 60 60 63 63 69 70 44 48 52 55 58 61 64 64 66 69 44 46 53 52 57 60 60 61 65 68 42 45 50 54 59 61 63 63 66 70 38 42 46 56 56 63 64 61 64 62 36 40 44 50 58 60 66 65 62 61 36 39 42 49 56 62 67 66 65 60 30 36 40 47 50 64 64 63 62 60 50 50 50 50 50 50 50 50 50 50 </code></pre> <p>Both south and east are traversable from A[0][0] so reachable entries would be:</p> <pre><code>50 51 54 58 60 60 60 63 68 71 48 52 51 59 60 60 63 63 69 70 44 48 52 55 58 61 64 64 66 69 44 46 53 52 57 60 60 61 65 68 42 45 50 54 59 61 63 63 66 70 38 42 46 56 56 63 64 61 64 62 36 40 44 50 58 60 66 65 62 61 36 39 42 49 56 62 67 66 65 60 30 36 40 47 50 64 64 63 62 60 50 50 50 50 50 50 50 50 50 50 </code></pre> <p>so I can conclude that my resulting array should be</p> <pre><code>1 1 0 0 0 0 0 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>Our professor ask us to implement this in pseudocode. I don't know how to do comparisons for two neighbor points and 4 directions of the point. Anyone can give me some ideas? </p>
<p>It's just flood fill. You need a queue and an index-addressable vector of "visited" flags. Put the root into the queue. Whist the queue is not empty, take the first element, and check for reachable locations N,S,E,W. Then check if they have been visited. If not, mark them as visited, and put them in the queue. </p>
Custom shape in android using xml <p>I am trying to draw a custom shape which I can use as a background for my layout. But I am not able to do so. Is it possible to draw a shape as below using xml in android. I am not getting how to cut the semicircle shape from the vertical centres of rectangle. </p> <p><a href="https://i.stack.imgur.com/CDJQe.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/CDJQe.jpg" alt="enter image description here"></a></p>
<p>try bellow xml. save it in drawable.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; &lt;corners android:topLeftRadius="15dp" android:topRightRadius="15dp" android:bottomLeftRadius="5dp" android:bottomRightRadius="5dp" /&gt; &lt;solid android:color="#ffffff" /&gt; &lt;padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" /&gt; &lt;stroke android:width="1dp" android:color="#000000" /&gt; &lt;/shape&gt; </code></pre>
When window is resized, span element not getting its width <p>Here's the screenshot: <a href="https://i.stack.imgur.com/uegLZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/uegLZ.png" alt="enter image description here"></a></p> <p>And here's the code:</p> <pre><code>.contact_section .contact_form input[type="text"], .contact_section .contact_form input[type="email"]{ border: 1px solid black; margin: 15px 0; font-size: 16px; padding: 3px 5px; text-align: center; width: 30.2%; display: inline; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } .contact_section .right_box{ float: right; width: 500px; } .contact_form .wpcf7-form-control-wrap:nth-of-type(2){ margin: 0 5px; } @media screen and (max-width: 510px) { .contact_section .contact_form input[type="text"], .contact_section .contact_form input[type="email"]{ margin: 5px auto; display: block; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .contact_form .wpcf7-form-control-wrap:nth-of-type(2) { margin: 0; } } </code></pre> <p>The problem is that, at normal window size, it looks perfect as shown in the screenshot. But if resize the window(to less than 510px) and back to the full size window, the <code>email</code> textbox goes to the next line!</p> <p>Here's the screenshot:</p> <p><a href="https://i.stack.imgur.com/nWSED.png" rel="nofollow"><img src="https://i.stack.imgur.com/nWSED.png" alt="enter image description here"></a></p> <p>What I noticed is that, the parent <code>&lt;span&gt;</code> element now doesn't have a width! I have been trying to figure out why its happening, for many hours now. But still no success! :(</p> <p>Btw, am using <code>ContactForm7</code> for the contact form.</p> <hr> <p><strong>EDIT</strong></p> <p>SOLVED! I set the <code>span</code> elements to <code>inline-block</code> as well as set the <code>30.2%</code> <code>width</code> to them instead of the textboxes. And some margin adjustments fixed the issue! Thank you</p>
<p>The CSS property <code>display:inline</code> does not accept widths and heights. Change this to inline-block to solve your issues.</p> <pre><code>.contact_section .contact_form input[type="text"], .contact_section .contact_form input[type="email"]{ border: 1px solid black; margin: 15px 0; font-size: 16px; padding: 3px 5px; text-align: center; width: 30.2%; display: inline-block; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } </code></pre> <p>Reference: <a href="http://stackoverflow.com/questions/5759554/displayinline-resets-height-and-width">display:inline resets height and width</a></p>
extra characters after close-brace <p>The same code that works on Linux doesn't work on FreeBSD</p> <p><strong>On Linux</strong></p> <pre><code>% set timeZone "-4:0" -4:0 % set timeZone [format "%+03d%02d" {*}[scan $timeZone "%d:%d"]] -0400 % puts $tcl_version 8.5 </code></pre> <p><strong>On FreeBSD</strong></p> <pre><code>% set timeZone "-4:0" -4:0 % set timeZone [format "%+03d%02d" {*}[scan $timeZone "%d:%d"]] extra characters after close-brace % puts $tcl_version 8.4 </code></pre> <p>How to make this work on both FreeBSD and Linux?</p>
<p>You will have to use <code>eval</code>, since list expansion (<code>{*}</code>) <a href="http://wiki.tcl.tk/17158" rel="nofollow">was implemented in Tcl 8.5</a>. You could perhaps use something like this:</p> <pre><code>set timeZone "-4:0" set code "format \"%+03d%02d\" [scan $timeZone "%d:%d"]" # This gives you "format "%+03d%02d" -4 0" set timeZone [eval $code] </code></pre> <p>If you don't like escaping the quotes, you can use braces (which IMO is a bit cleaner):</p> <pre><code>set code "format {%+03d%02d} [scan $timeZone {%d:%d}]" </code></pre> <hr> <p>Or the more elaborate 8.4 solution from the wiki can be found <a href="http://wiki.tcl.tk/17379" rel="nofollow">here</a>.</p>
Javascript why array.slice() doesn't work when the first value is 0? <p>I have a problem, I don't understand why arr.slice doesn't work when the first value is 0, the returned array is empty:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function chunkArrayInGroups(arr, size) { var newArr = []; for (var i = 0; arr[i]; i += size) { newArr.push(arr.slice(i, i + size)); } return newArr; } console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));</code></pre> </div> </div> </p>
<p>You end direct the loop with the condition, which evaluates as <code>false</code>.</p> <pre><code>arr[i] -&gt; arr[0] -&gt; 0 -&gt; false -&gt; end for loop </code></pre> <p>Use the length of the array as check</p> <pre><code>for (var i = 0; i &lt; arr.length; i += size) { // ^^^^^^^^^^^^^^ </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function chunkArrayInGroups(arr, size) { var newArr = []; for (var i = 0; i &lt; arr.length; i += size) { newArr.push(arr.slice(i, i + size)); } return newArr; } console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));</code></pre> </div> </div> </p>
How can I do SQL Server RegEx replace similar to JavaScript RegEx replace <p>How can perform below shown JavaScript RegEx replace in SQL Server?</p> <pre><code>var str = "$5,000"; console.log(str.replace(/[$,]/g, "")); </code></pre> <p>Output:</p> <pre><code>5000 </code></pre>
<p>Try this </p> <pre><code>declare @str money set @str= cast(cast('$5,000' as money) as int) </code></pre> <p>Or else if you especially want to use regular expression, you can try the below,</p> <pre><code>DECLARE @Str varchar(100) SET @Str = '$5,000' set @Str = STUFF(@Str, PATINDEX('%[$,]%', @Str),1, '') select @str </code></pre>
can I use grant_type=client_credentials for google api? <p>I create a clientid, and clientcredentials in google console. when I request the token with <code>grant_type=client_credentials</code>. I got <code>401 unauthrorized</code>.</p> <pre><code>{ "error": "invalid_client", "error_description": "Unauthorized", "error_uri": "" } </code></pre>
<p>The error means that you are not authenticated. Also client_credentials is not a valid value for grant_type that I am aware of. </p> <p>The only ones I know of are </p> <ul> <li>authorization_code</li> <li>refresh_token</li> </ul> <p>It looks like <code>grant_type=client_credentials</code> is part of the <a href="https://tools.ietf.org/html/rfc6749" rel="nofollow">RFC</a> for Oauth2 but its not something I have seen implemented in Googles Authentication servers.</p> <p><strong>Anwser</strong>: No to my knowledge you cant use grant_type=client_credentials with Google APis.</p> <p><strong>update</strong>: just got word back from Google. I was correct they do not support this grant_type. </p>
Deserialize flattened JSON keys to proper objects with GSON <p>We ingest an external API (we cannot change the JSON we receive) which produces JSON with flattened keys. For example:</p> <pre><code>{ "composite.key": "value", "normal": "another value", "composite.key2": "back here again..." } </code></pre> <p>which we would ideally like to deserialize into:</p> <pre><code>public class SomeObject { public String normal; public Composite composite; } public class Composite { public String key; public String key2; } </code></pre> <p>while we know we can write a custom deserializer, I would first like to check if there is support for this in GSON using annotations or by some other means.</p>
<p>You can use GSON's <a href="https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html" rel="nofollow">@SerializedName</a> annotation on the Java fields.</p> <p>Something like this</p> <pre><code>public class Composite { @SerializedName("composite.key") public String key; @SerializedName("composite.key2") public String key2; } </code></pre>
Interpolate between elements in an array of floats <p>I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.</p> <p>So if this is my array...</p> <pre><code>list = [1.222, 3.111, 0.456, 9.222, 22.333] </code></pre> <p>I want to ramp from 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.</p>
<p>do you think about something like that?</p> <pre><code>import time l = [1.222, 3.111, 0.456, 9.222, 22.333] def play_led(value): #here should be the led- code print value def calc_ramp(given_list, interval_count): new_list = [] len_list = len(given_list) for i in range(len_list): first = given_list[i] second = given_list[(i+1) % len_list] delta = (second - first) / interval_count for j in range(interval_count): new_list.append(first + j * delta) return new_list def endless_play_led(ramp_list,count): endless = count == 0 count = abs(count) while endless or count!=0: for i in range(len(ramp_list)): play_led(ramp_list[i]) #time.sleep(1) if not endless: count -= 1 print '##############',count endless_play_led(calc_ramp(l, 3),2) endless_play_led(calc_ramp(l, 3),-2) endless_play_led(calc_ramp(l, 3),0) </code></pre>
Join data from rows to 1 row depending on the number of rows <p>I have the following tables:</p> <pre><code>user userId name 1 Sam 2 Harold 3 John othertable id id2 number 1 111 12 1 222 23 1 333 33 2 111 12 2 444 11 3 555 12 3 222 44 </code></pre> <p>The user table's userId matches the othertable's id column. Ideally I'd like to join the content of othertable to user depending on how many rows are present for that id. That's the output I'm aiming for:</p> <pre><code>e.g. user userId name 111 222 333 444 555 1 Sam 12 12 33 2 Harold 12 11 3 John 44 12 </code></pre> <p>Any idea?</p> <p>Update: The id2's values are limited. Only valid values 111, 222, 333, 444 and 555.</p>
<p>you may try out this 1... not sure if it meet you requirement...</p> <pre><code>CREATE TABLE users ( userId int, name varchar(max) ) INSERT INTO USERS VALUES (1, 'Sam'), (2, 'Harold'), (3, 'John') CREATE TABLE othertable ( id int, id2 int, number int ) INSERT INTO othertable VALUES (1, 111, 12), (1, 222, 23), (1, 333, 33), (2, 111, 12), (2, 444, 11), (3, 555, 12), (3, 222, 44) SELECT u.userId, u.name, SUM(CASE WHEN (id2=111) THEN number ELSE 0 END) AS [111], SUM(CASE WHEN (id2=222) THEN number ELSE 0 END) AS [222], SUM(CASE WHEN (id2=333) THEN number ELSE 0 END) AS [333], SUM(CASE WHEN (id2=444) THEN number ELSE 0 END) AS [444], SUM(CASE WHEN (id2=555) THEN number ELSE 0 END) AS [555] FROM othertable o INNER JOIN users u ON o.id = u.userId GROUP BY u.userId, u.name </code></pre> <p>Please have a try. :)</p> <blockquote> <p>UPDATE: Sorry, I'm not really familiar with MySQL. But I did tried my best by changing the query into subquery and hope this can help you. If this doesn't meet you requirement, I hope some other people can help you.</p> <p>UPDATE 2: Avoid using PIVOT</p> </blockquote>
css text to close hard to read in wordpress <p>[![enter image description here][1]][1]</p> <p>as you can se the text is to close am</p> <pre><code>#main { text-align: left; margin-bottom: 10px; display: inline-block; width: 1280px; padding: 10px; margin: auto; margin-top: 10px; text-align: justify; font-family: Century Gothic,sans-serif; } </code></pre>
<p>Use css property <code>line-height: 14px;</code> to set height of line between text</p> <pre><code>p { line-height: 25px; } </code></pre>
Sharepoint Rest Api calls` <p>I am making a simple website where I have to save some of my data to sharepoint list. I am using only html css js only. I need to make REST calls to Sharepoint APIs to post data on SP. I am trying to get data from my list(in SP) as follow:</p> <pre><code>$(document).ready(function() { processListItems(hostweburl, 'ListName'); }); function processListItems(url, listname) { $.ajax({ url: url + "/_api/web/lists/getbytitle('" + listname + "')", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function(data) { console.log(data); }, error: function(data) { console.log(data); } }); } </code></pre> <p>It returns this response:</p> <pre><code>"{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}" </code></pre> <p>I am referencing only two scripts:</p> <pre><code> &lt;script src="js/jquery-3.1.1.js"&gt;&lt;/script&gt; &lt;script src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>It says I am unauthorised to access. Although I am having admin rights to my list. Please tell me how to fix this issue. Do I need any authorization header for ajax call to Rest Api? I am new to Sharepoint. Please Help!</p>
<p>I think that custom scripting is disabled by default in SPOnline. You may have to enable it. These links may help:</p> <p><a href="http://stackoverflow.com/questions/29675567/access-denied-office-365-sharepoint-online-with-global-admin-account">Access denied office 365 / SharePoint online with Global Admin account</a></p> <p><a href="http://vamsi-sharepointhandbook.blogspot.com/2015/07/turn-scripting-capabilities-on-or-off.html" rel="nofollow">http://vamsi-sharepointhandbook.blogspot.com/2015/07/turn-scripting-capabilities-on-or-off.html</a></p>
How to get nokogiri attribute value? <p>My xml contains multiple statements like</p> <pre><code>&lt;House name="bla"&gt;&lt;Room id="bla" name="black" &gt;&lt;blah id="blue" name="brown"&gt;&lt;/blah&gt;&lt;/Room&gt;&lt;/House&gt; </code></pre> <p>I need to get all the values for the given keyword.</p> <p>I used <code>nodes = doc.css("[name]")</code> to get the <code>&lt;Room id="bla" name="black" &gt;&lt;blah id="blue" name="brown"&gt;&lt;/blah&gt;&lt;/Room&gt;</code>.\</p> <p>But how do I get the value for a key from this. Is there any easier way to do this?</p>
<pre><code>node_names = doc.css("[name]").map { |node| node['name'] } </code></pre> <p>for all node names; or for just "black",</p> <pre><code>black = doc.at_css("[name]")['name'] </code></pre>
How to create pullup and pulldown effect in web? <p>We are creating mobile application and need to create some sort of "android loading" effect. I've tried to draw, because it's difficult to explain.</p> <p><a href="https://i.stack.imgur.com/MKSf2.png" rel="nofollow"><img src="https://i.stack.imgur.com/MKSf2.png" alt="pull back bounce"></a></p> <ol> <li>User is at the end of scroll up</li> <li>User keeps scrolling (swiping page up) and should see an empty space (marked yellow)</li> <li>User releases finger and table is bouncing back down, hiding empty space.</li> </ol> <p>All we know how it works in native enviroment, but what would be the best technique to reproduce the same in web? Thanks in advance for any advise.</p> <p>EDIT: for those who think that question is too broad. I dont need code in answer, I want to get an idea on what whould be the best approach to solve this.</p>
<p>You'll have to add a Pseudo element at the end of the list(with some height).</p> <p>Now in Javascript check if the offset of this element is above the bottom of screen and scroll up to hide it (with some delay).</p> <p>Also hide the scroll bar else it may look a bit weird.</p>
Passing a vector as a reference to a recursive function <p>I've build a function that accepts a reference to a vector as argument, it looks like this :</p> <pre><code>void func(std::vector&lt;int&gt; &amp;vec) { // sth. to do } </code></pre> <p>But i want that the function is recursive and calls itself with a part of the original vector.</p> <pre><code>void func(std::vector&lt;int&gt; &amp;vec) { // sth. to do func(part of the orignial vector); } </code></pre> <p>How can i construct a new vector from my original vector ? It's important that when I modify the part of the vector in the recursive call, that the original vector "vec" has also this changes, so i didn't wan't to pass a copy or new vector. Thanks for your help.</p>
<p>The old way!</p> <pre><code>void func(std::vector&lt;int&gt; &amp;vec,int l,int r) { // this function modifies only vec fro indices l to r. // // do what you want // // func(vec,new_l,new_r); } </code></pre>
install4j obsolete files not removed on upgrade <p>I am writing a sample upgrade installer and added in few files and removed up some files. I see that the added files are getting properly placed but the removed are not getting deleted.</p> <p>how to handle this</p>
<p>You can add an "Uninstall previous installation" action to the "Installation" screen of your installer in order to remove those files.</p>
Connection: keep-alive in nginx webserver <p>I have enabled the Connection: keep-alive in my nginx webserver. And its working fine as well. My query is in nginx access logs i am getting the below message many times. I believe its due to the keep-alive but what exactly the server is doing? Thanks in advance.</p> <p>Access Log Message: "GET / HTTP/1.0" 302 43 "-" "HTTP-Monitor/1.1" "-"</p>
<p>If I'm not mistaken, when the keep alive activates the web server sends a packet to the client to indicate that the connection is still active, so those messages are in the log.</p> <p>Sorry for my English ;)</p>
undefined method with time_select <p>I am trying to use a time select with locals passed to the partial, but I am getting the following error</p> <pre><code>undefined method `open_time' for #&lt;Merchant:0x007fb41fd0aa90&gt; </code></pre> <p>Partial Call</p> <pre><code>= form_for @merchant, :url =&gt; admin_merchant_path(@merchant) do |form| #account-panel.mdl-tabs__panel = render :partial =&gt; 'venue', :locals =&gt; {:address_fields =&gt; form} = render :partial =&gt; 'hours', :locals =&gt; {:hour_fields =&gt; form} </code></pre> <p>Rendered Partial</p> <pre><code>.mdl-cell.mdl-cell--12-col /h3.mdl-typography--display-1.teal-heading= t('.trading_hours_title') - (0..6).each do |i| li.mdl-list__item.mdl-list__item--two-line span.mdl-list__item-primary-content = Date::DAYNAMES[i] span.mdl-list__item-sub-title = hour_fields.time_select :open_time, {:minute_step =&gt; 30, :ampm =&gt; true} </code></pre> <p>Merchant Model</p> <pre><code>has_many :trading_hours, dependent: :destroy accepts_nested_attributes_for :trading_hours </code></pre> <p>Trading Hour Model</p> <pre><code>belongs_to :merchant </code></pre>
<p>you can do something like this(starting from the last line of your mentioned code):</p> <pre><code>&lt;%= hour_fields.fields_for :trading_hours do |trading_field| %&gt; &lt;%= trading_field.time_select :open_time, {:minute_step =&gt; 30, :ampm =&gt; true} %&gt; &lt;% end %&gt; </code></pre> <p>And in Merchants controller action build <code>trading_hours</code> if you don't have any <code>trading_hour</code>:</p> <pre><code>@merchant.trading_hours.build </code></pre> <p>PS: This is is ERB(I know only this :) )</p>
Integrating Auth0 authentication with existing user database <p>I've a requirement to integrate Auth0 in our project (Reactjs/Hapijs/MySQL). I checked the documentation and they have many examples and that is great, however, I can't find any related to how exactly do I use my existing user database.</p> <p>In my application I have users and those users can have one or more projects. With the authorization that we currently use, a user logs in, I check what projects does he own and send it to the React application.</p> <p>I am missing a document that explains me how to use Auth0 and still be able to check in my database what projects user owns.</p> <p>My idea on how that should work (I might be wrong):</p> <ol> <li>User sends username and password to our server</li> <li>Our server makes request to Auth0 (with provided credentials)</li> <li>Auth0 replies back to our server with some <strong>token</strong></li> <li>We look in users table in our database and try to verify the existence of that user</li> <li>If it is a match then we simply look (as we already do) for user projects.</li> </ol> <p>Is this how it is supposed to work?</p>
<p>There are a few options available for scenarios where you want to integrate Auth0 with applications that already have existing user databases. You can either:</p> <ol> <li>continue to <a href="https://auth0.com/docs/connections/database#using-a-custom-user-store" rel="nofollow">use your existing store</a></li> <li>progressively <a href="https://auth0.com/docs/connections/database#migrating-to-auth0-from-a-custom-user-store" rel="nofollow">migrate your users from your custom store</a> to the Auth0 store</li> </ol> <p>You don't mention it explicitly, but judging from your expected flow it seems you would be wanting to implement the first option. <strong>There is specific documentation that you can follow that explain how you can setup your custom database connection, see <a href="https://auth0.com/docs/connections/database/mysql" rel="nofollow">Authenticate Users with Username and Password using a Custom Database</a></strong>. It mentions MySQL, but others database servers are supported and there are many templates that will allow you to quickly setup things.</p> <p>When you complete this the final flow will be the following:</p> <ol> <li>Using either Auth0 authentication libraries (Lock) or your custom UI you'll ask the user for their credentials</li> <li>Either Lock or your custom UI submits the credentials to Auth0 authentication API</li> <li>Auth0 authentication API validates the credentials by calling scripts that execute against your custom database (these scripts were provided by you when you configured the database connection)</li> <li>If the credentials are valid the Authentication API will return a token to the calling application that will have user information and proves the users is who he say he is.</li> </ol> <p>The scripts you need to provide are the following, but only one is mandatory:</p> <ul> <li>Login script (executed each time a user attempts to login) (<strong>mandatory</strong>)</li> <li>Create user script</li> <li>Verify email script</li> <li>Change password script</li> <li>Delete user script</li> </ul> <p>The optional scripts are only required when you want to provide the associated functionality through Auth0 libraries, if only need the login to work then you can skip them. The login script, in the case of a valid user, is also where you return the profile information of the user, for example, you could in theory include their owned projects in the user profile.</p>
Deciding when to use a hash table <p>I was soving a competitive programming problem with the following requirements:</p> <p>I had to maintain a list of unqiue 2d points (x,y), the number of unique points would be less than 500.</p> <p>My idea was to store them in a hash table (C++ unordered set to be specific) and each time a node turned up i would lookup the table and if the node is not already there i would insert it.</p> <p>I also know for a fact that <strong>i wouldn't be doing more than 500 lookups</strong>. So i saw some solutions simply searching through an array (unsorted) and checking if the node was already there before inserting.</p> <p>My question is is there any reasonable way to guess when should i use a hash table over a manual search over keys without having to benchmark them?</p>
<blockquote> <p>My question is is there any reasonable way to guess when should i use a hash table over a manual search over keys without having to benchmark them?</p> </blockquote> <p><sup>I am guessing you are familiar with basic algorithmics &amp; <a href="https://en.wikipedia.org/wiki/Time_complexity" rel="nofollow">time complexity</a> and C++ <a href="http://en.cppreference.com/w/cpp/container" rel="nofollow">standard containers</a> and know that with luck hash table access is O(1)</sup></p> <p>If the hash table code (or some balanced tree code, e.g. using <code>std::map</code> - assuming there is an easy order on keys) is more readable, I would prefer it for that readability reason alone.</p> <p>Otherwise, you might make some guess taking into account the <a href="http://norvig.com/21-days.html#answers" rel="nofollow">approximate timing for various operations on a PC</a>. BTW, the entire <a href="http:///norvig.com/21-days.html" rel="nofollow">http:///norvig.com/21-days.html</a> page is worth reading.</p> <p>Basically, memory accesses are much more slow than everything else in the CPU. The <a href="https://en.wikipedia.org/wiki/CPU_cache" rel="nofollow">CPU cache</a> is extremely important. A typical memory access with cache fault requiring fetching data from DRAM modules is <em>several hundreds times slower</em> than some elementary arithmetic operation or machine instruction (e.g. adding two integers in registers).</p> <p>In practice, it does not matter that much, as long as your data is tiny (e.g. less than a thousand elements), since in that case it is likely to sit in L2 cache.</p> <p>Searching (linearly) in an array is really fast (since very cache friendly), up to several thousand of (small) elements.</p> <p>IIRC, <a href="https://herbsutter.com/" rel="nofollow">Herb Sutter</a> mentions in some video that even <em>inserting</em> an element inside a vector is practically -but unintuitively- faster (taking into account the time needed to move slices) than inserting it into some balanced tree (or perhaps some other container, e.g. an hash table), up to a container size of several thousand small elements. This is on typical tablet, desktop or server microprocessor with a multimegabyte cache. YMMV.</p> <p>If you really care that much, you cannot avoid benchmarking.</p> <p>Notice that 500 pairs of integers is probably fitting into the L1 cache!</p>
Select Orders of Last Month in MySQL <p>I have to write a query that selects Last month orders from a table Order( id , ......., order_date).</p> <p>Assume that the date of today is 4th of April. Will i select orders from 1st March to 31th of March or from the 4th of March to the 4th of April ??? </p> <p>Edit : The first query : </p> <pre><code>SELECT * from Order where order_date between sysdate() and sysdate - INTERVAL 1 Month </code></pre> <p>The Second Query : </p> <pre><code> SELECT * from Order where order_date between (Last_day(sysdate()) - INETRVAL 1 MONTH) and ((Last_day(sysdate()) + INTERVAL 1 DAY) - INETRVAL 2 MONTH)) </code></pre> <p><code>(Last_day(sysdate()) - INETRVAL 1 MONTH)</code> gives 30 of March</p> <p><code>((Last_day(sysdate()) + INTERVAL 1 DAY) - INETRVAL 2 MONTH))</code> gives 1st of March</p>
<p>"Last month" typically means the whole period of the month prior to today. So if today was 4th April then last month is</p> <pre><code> &gt;= 1st March and &lt; 1st April </code></pre> <p>E.g.</p> <pre><code>Select * from orders Where order_date &gt;= '2016-03-01' and order_date &lt; '2016-04-01' </code></pre> <p>Note I recommend avoiding between for date ranges. Also note that the time of 23:59:59 is NOT the end of a day and that recent versions of mysql do support subsecond time precision.</p>
Decomposition of time series data <p>Can anybody help be decipher the output of ucm. My main objective is to check if the ts data is seasonal or not. But i cannot plot and look and every time. I need to automate the entire process and provide an indicator for the seasonality.</p> <p>I want to understand the following output </p> <pre><code>ucmxmodel$s.season # Time Series: # Start = c(1, 1) # End = c(4, 20) # Frequency = 52 # [1] -2.391635076 -2.127871717 -0.864021134 0.149851212 -0.586660213 -0.697838635 -0.933982269 0.954491859 -1.531715424 -1.267769820 -0.504165631 # [12] -1.990792301 1.273673437 1.786860414 0.050859315 -0.685677002 -0.921831488 -1.283081922 -1.144376739 -0.964042949 -1.510837956 1.391991657 # [23] -0.261175626 5.419494363 0.543898305 0.002548125 1.126895943 1.474427901 2.154721023 2.501352782 0.515453691 -0.470886132 1.209419689 ucmxmodel$vs.season # [1] 1.375832 1.373459 1.371358 1.369520 1.367945 1.366632 1.365582 1.364795 1.364270 1.364007 1.364007 1.364270 1.364795 1.365582 1.366632 1.367945 # [17] 1.369520 1.371358 1.373459 1.375816 1.784574 1.784910 1.785223 1.785514 1.785784 1.786032 1.786258 1.786461 1.786643 1.786802 1.786938 1.787052 # [33] 1.787143 1.787212 1.787257 1.787280 1.787280 1.787257 1.787212 1.787143 1.787052 1.786938 1.786802 1.786643 1.786461 1.786258 1.786032 1.785784 # [49] 1.785514 1.785223 1.784910 1.784578 1.375641 1.373276 1.371175 1.369337 1.367762 1.366449 1.365399 1.364612 1.364087 1.363824 1.363824 1.364087 # [65] 1.364612 1.365399 1.366449 1.367762 1.369337 1.371175 1.373276 1.375636 1.784453 1.784788 1.785101 1.785392 1.785662 1.785910 1.786136 1.786339 ucmxmodel$est.var.season # Season_Variance # 0.0001831373 </code></pre> <p>How can i use the above info without looking at the plots to determine the seasonality and at what level ( weekly, monthly, quarterly or yearly)?</p> <p>In addition, i am getting NULL in est</p> <pre><code>ucmxmodel$est # NULL </code></pre> <h2>Data</h2> <p>The data for a test is:</p> <pre><code>structure(c(44, 81, 99, 25, 69, 42, 6, 25, 75, 90, 73, 65, 55, 9, 53, 43, 19, 28, 48, 71, 36, 1, 66, 46, 55, 56, 100, 89, 29, 93, 55, 56, 35, 87, 77, 88, 18, 32, 6, 2, 15, 36, 48, 80, 48, 2, 22, 2, 97, 14, 31, 54, 98, 43, 62, 94, 53, 17, 45, 92, 98, 7, 19, 84, 74, 28, 11, 65, 26, 97, 67, 4, 25, 62, 9, 5, 76, 96, 2, 55, 46, 84, 11, 62, 54, 99, 84, 7, 13, 26, 18, 42, 72, 1, 83, 10, 6, 32, 3, 21, 100, 100, 98, 91, 89, 18, 88, 90, 54, 49, 5, 95, 22), .Tsp = c(1, 3.15384615384615, 52), class = "ts") </code></pre> <p>and</p> <pre><code>structure(c(40, 68, 50, 64, 26, 44, 108, 90, 62, 60, 90, 64, 120, 82, 68, 60, 26, 32, 60, 74, 34, 16, 22, 44, 50, 16, 34, 26, 42, 14, 36, 24, 14, 16, 6, 6, 12, 20, 10, 34, 12, 24, 46, 30, 30, 46, 54, 42, 44, 42, 12, 52, 42, 66, 40, 60, 42, 44, 64, 96, 70, 52, 66, 44, 64, 62, 42, 86, 40, 56, 50, 50, 62, 22, 24, 14, 14, 18, 18, 10, 20, 10, 4, 18, 10, 10, 14, 20, 10, 32, 12, 22, 20, 20, 26, 30, 36, 28, 56, 34, 14, 54, 40, 30, 42, 36, 52, 30, 32, 52, 42, 62, 46, 64, 70, 48, 40, 64, 40, 120, 58, 36, 40, 34, 36, 26, 18, 28, 16, 32, 18, 12, 20), .Tsp = c(1, 4.36, 52), class = "ts") </code></pre>
<p>I think the most straightforward approach would be to follow <a href="http://robjhyndman.com/hyndsight/detecting-seasonality/" rel="nofollow">Rob Hyndman's approach</a> (he is the author of many time series packages in R). For your data it would work as follows,</p> <pre><code>require(fma) # Create a model with multiplicative errors (see https://www.otexts.org/fpp/7/7). fit1 &lt;- stlf(test2) # Create a model with additive errors. fit2 &lt;- stlf(data, etsmodel = "ANN") deviance &lt;- 2 * c(logLik(fit1$model) - logLik(fit2$model)) df &lt;- attributes(logLik(fit1$model))$df - attributes(logLik(fit2$model))$df # P-value 1 - pchisq(deviance, df) # [1] 1 </code></pre> <p>Based on this analysis we find the <em>p-value</em> of 1 which would lead us to conclude there is no seasonality.</p>
how to pass thymeleaf object to angularjs <p>I am using Spring-boot, thymeleaf and Angularjs. In my my view.html I need to recover the list "lstUsers" from my class "controller.java" using Angular.</p> <p>For informations: "view.html" and "controller.java" works good. The problem is how I can fill my variable "$scope.users" with "lstUsers"</p> <p>this is app.js</p> <pre><code>var app = angular.module('angularTable', ['angularUtils.directives.dirPagination']); app.controller('listdata',function($scope, $http){ $scope.users = []; $scope.users = $lstUsers; // (lstUsers) is an object from controller.java: this not work !!!!!!! $scope.sort = function(keyname){ $scope.sortKey = keyname; //set the sortKey to the param passed $scope.reverse = !$scope.reverse; //if true make it false and vice versa } }); </code></pre> <p>this is my view.html</p> <pre><code>&lt;body&gt; &lt;div role="main" class="container theme-showcase"&gt; &lt;div class="" style="margin-top:90px;"&gt; &lt;div class="col-lg-8"&gt; &lt;div class="bs-component" ng-controller="listdata"&gt; &lt;form class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;input type="text" ng-model="search" class="form-control input-style search-input" placeholder="Search" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;table class="table table-responsive table-hover table-striped table-bordered tablesorter"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th ng-click="sort('id')"&gt;Id &lt;span class="glyphicon sort-icon" ng-show="sortKey=='id'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"&gt;&lt;/span&gt; &lt;/th&gt; &lt;th ng-click="sort('first_name')"&gt;First Name &lt;span class="glyphicon sort-icon" ng-show="sortKey=='first_name'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"&gt;&lt;/span&gt; &lt;/th&gt; &lt;th ng-click="sort('last_name')"&gt;Last Name &lt;span class="glyphicon sort-icon" ng-show="sortKey=='last_name'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"&gt;&lt;/span&gt; &lt;/th&gt; &lt;th ng-click="sort('hobby')"&gt;Hobby &lt;span class="glyphicon sort-icon" ng-show="sortKey=='hobby'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"&gt;&lt;/span&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr dir-paginate="user in users|orderBy:sortKey:reverse|filter:search|itemsPerPage:5"&gt; &lt;td&gt;{{user.id}}&lt;/td&gt; &lt;td&gt;{{user.first_name}}&lt;/td&gt; &lt;td&gt;{{user.last_name}}&lt;/td&gt; &lt;td&gt;{{user.hobby}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;dir-pagination-controls max-size="5" direction-links="true" boundary-links="true" &gt; &lt;/dir-pagination-controls&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script th:src="@{/js/angular/angular.js}"&gt;&lt;/script&gt; &lt;script th:src="@{/js/dirPagination.js}"&gt;&lt;/script&gt; &lt;script th:src="@{/js/app.js}"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre> <p>this is a snippet of my controller.java</p> <pre><code>... @RequestMapping(value = "/getSubTasks") public ModelAndView getSubTasks(@RequestParam String issueKey) { ModelAndView model = new ModelAndView(); ..... model.setViewName("view"); model.addObject("lstUsers", getUsers()); } return model; } ... </code></pre> <p>Thanks for your answer </p>
<p>Usually this kind of data is retrieved from the server via ajax. For example you can provide a Spring MVC Controller that returns your sub tasks as a JSON array and your angular app would need to retrieve that data from your Spring MVC Controller via ajax.</p> <p>Have a look at this tutorial: <a href="https://spring.io/guides/gs/consuming-rest-angularjs/" rel="nofollow">https://spring.io/guides/gs/consuming-rest-angularjs/</a></p>
Swift 3, UITextView under the keyboard while typing <p>I'm developing an app with a chat inside, really simple, one tableview with a textview and a button.</p> <p><a href="https://i.stack.imgur.com/EY6dq.png" rel="nofollow"><img src="https://i.stack.imgur.com/EY6dq.png" alt="enter image description here"></a></p> <p>When I'm typing in the textview, it grow up under the keyboard, like the picture below...</p> <p><a href="https://i.stack.imgur.com/IJIP6.png" rel="nofollow"><img src="https://i.stack.imgur.com/IJIP6.png" alt="enter image description here"></a></p> <p>What I need is that the TextView move up :)</p> <p>Thank you!</p>
<p>You can use <a href="https://github.com/hackiftekhar/IQKeyboardManager" rel="nofollow">IQKeyboardManager</a> which will take care of your problem</p>
Count unique customers <p>Thank you in advance for your help. I have been working on this problem for hours. I have a table with the following columns:</p> <pre><code>OrderID | CustomerID | Date | Course --------|------------|-----------|---------- 14954 | 13440 |16.10.2016 | Zürich 14955 | 13441 |17.10.2016 | Bern 14956 | 13441 |17.10.2016 | Aargau 14957 | 13442 |17.10.2016 | Bern 14958 | 10483 |17.10.2016 | Zürich 14959 | 13442 |18.10.2016 | Solothurn </code></pre> <p>I'd like to count the customer's first order, which was received on a certain date broken down by course. The query should yield the following result for the 17.10.2016.</p> <pre><code>Bern: 2 Aargau: 0 Zürich: 1 </code></pre> <p>I've already tried a DISTINCT and nested Query like:<br></p> <pre><code>SELECT Count(*) AS Anzahl FROM (SELECT DISTINCT kundennummer FROM (SELECT datum, kundennummer FROM unterlagenbestellungen WHERE kurs LIKE '%" &amp; DgvStatUnterlagenbestellungen.Rows(x).HeaderCell.Value &amp; "%') WHERE datum BETWEEN # " &amp; mindatum &amp; " # AND # " &amp; maxdatum &amp; " # ) </code></pre> <p>I'm very thankful for any help</p>
<p>You want this:</p> <pre><code>SELECT Course, COUNT(DISTINCT CustomerID) FROM [Table_name] WHERE Date='17.10.2016' </code></pre>
Xamarin Forms trouble with SQLite and await <p>I'm using the sqlite-net-pcl nuget, in my view model I am trying to get the list of announcements from my database </p> <pre><code> private SQLiteAsyncConnection connection; public ObservableCollection&lt;Announcement&gt; AnnouncementList { get; private set; } public AnnouncementsViewModel() { connection = DependencyService.Get&lt;ISQLiteDb&gt;().GetConnection(); Initialize(); } public async void Initialize() { await connection.CreateTableAsync&lt;Announcement&gt;(); var announcements = await connection.Table&lt;Announcement&gt;().ToListAsync(); AnnouncementList = new ObservableCollection&lt;Announcement&gt;(announcements); System.Diagnostics.Debug.WriteLine("***********************************"); System.Diagnostics.Debug.WriteLine(AnnouncementList.Count); } </code></pre> <p>in my code behind, in the constructor: </p> <pre><code> BindingContext = new AnnouncementsViewModel(); InitializeComponent(); var list = (BindingContext as AnnouncementsViewModel).AnnouncementList; </code></pre> <p>The error I get is:</p> <blockquote> <p>System.NullReferenceException: Object reference not set to an instance of an object.</p> </blockquote> <p>I put a break point in my viewModel, when it arrives to the first await it returns to the code behind and the App crashes. I get the null exception because the AnnouncementList is not filled in the viewModel and it didn't print the stars. How can I solve this problem?</p> <p>Thanks</p>
<p>You can't just call your async <code>Initialize()</code> method in a sync way like that. It will return immediately and by the time you get around to using <code>AnnouncementList</code>, <code>Initialize</code> isn't finished running yet and it is still null.</p> <p>It's not an ideal solution but you should add <code>.Wait()</code> after <code>Initialize()</code> to ensure it completes before you exit the constructor.</p> <p>I say 'not ideal' because depending on your context <code>Wait()</code> might block. If that happens you're probably better off doing that initialization work before constructing your ViewModel, using only 'proper' awaiting, and passing <code>AnnouncementsList</code> into the constructor.</p>
Entity Framework temporary save <p>We are building a website where users can add/edit/remove students and their related info. Everything works great, but now we want to allow anonymous users to try our demo school.</p> <p>Demo school is the same as regular school but we want users to be able to edit/delete information on the page without it being persisted in the database (This way this demo is always the same, despite of the user changes)</p> <p>One way to do this is to run hourly SQL scripts that will clean-up records but this is not ideal because it will require running a scheduler, plus if user is trying out the demo sometimes data will be erased during their visit.</p> <p>Is there a way to temporarily save data in a session or other storage and then wipe so demo is not affected? </p>
<p>use a temporary database and as soon as you want to switch to the original one just change the web.config file , if you use Code first it will be easy else you need to generate sql+data from the original database to the temporary . </p>
Can not convert JSON to domain object with spring restTemplate <p>Actually I try to invoke a get request with the restTemplate in Spring. Debbuging my application clearly shows that the JSON is downloaded but the automatic mapping does not work. My List of domain object includes only 0 values and null values. When I invoke the get request from the browser, I get the following response as JSON (I copied here the first two record out of the 3 192):</p> <pre><code>[{"OrderId":77862,"DateAdded":"2016-04-30T02:25:40.263","OrderItemCorpusId":"HUBW","OrderItemCorpusOriginalId":null,"OrderItemCurrency":"HUF","OrderItemExchangeRate":1.00000,"OrderItemOriginalLocation":"HU","OrderItemBuyLocation":"HU","OrderItemPrice":1337.80314,"OrderItemDiscountId":0,"OrderItemDiscountValue":"","DocumentId":25140,"Title":"Romana Gold 10. kötet","PublisherOriginalName":"Harlequin Kiadó","ISBN":"9789634073369"},{"OrderId":77864,"DateAdded":"2016-04-30T15:49:22.61","OrderItemCorpusId":"HUBW","OrderItemCorpusOriginalId":null,"OrderItemCurrency":"HUF","OrderItemExchangeRate":1.00000,"OrderItemOriginalLocation":"HU","OrderItemBuyLocation":"HU","OrderItemPrice":2748.03149,"OrderItemDiscountId":0,"OrderItemDiscountValue":"","DocumentId":25252,"Title":"Az eltűnt lány","PublisherOriginalName":"Harlequin Kiadó","ISBN":"9789634072423"}] </code></pre> <p>My POJO domain object which should keep the converted data from JSON:</p> <pre><code>@JsonIgnoreProperties(ignoreUnknown = true) public class BandWTransaction { private long OrderId; private Date DateAdded; private String OrderItemCurrency; private double OrderItemExchangeRate; private String OrderItemBuyLocation; private double OrderItemPrice; private String OrderItemDiscountValue; private long DocumentId; private String Title; private String PublisherOriginalName; private String ISBN; //getters and setters </code></pre> <p>Finally the code snippet I use for the rest get request:</p> <pre><code>String startDate = new SimpleDateFormat("yyyy-MM-dd").format(start.getTime()); String endDate = new SimpleDateFormat("yyyy-MM-dd").format(end.getTime()); UriComponents uri = UriComponentsBuilder.newInstance().scheme("http").host("www.bookandwalk.hu") .path("/api/AdminTransactionList").queryParam("password", "XXX") .queryParam("begindate", startDate).queryParam("enddate", endDate).queryParam("corpusid", "HUBW") .build().encode(); LOG.log(Level.INFO, "{0} were called as a rest call", uri.toString()); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("User-Agent", "Anything"); HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(headers); ResponseEntity&lt;List&lt;BandWTransaction&gt;&gt; transResponse = restTemplate.exchange(uri.toString(), HttpMethod.GET, entity, new ParameterizedTypeReference&lt;List&lt;BandWTransaction&gt;&gt;() { }); List&lt;BandWTransaction&gt; transactions = transResponse.getBody(); </code></pre> <p>When I debug the app I realized that the transactions list includes objects with full of null and 0 values. More precisely, there is no and objcet within the list having other values as 0 and null in the properties. I have also checked that spring boot automatically registered in the restTemplate.messageConverters ArrayList 9 HttpMessageConverter. The 7th element of this ArrayList is the org.springframework.http.converter.json.MappingJackson2HttpMessageConverter which supports the application/json and application/+json media types. Any idea is appreciated to solve this problem as I am newbie in spring and in JSON mapping in general.</p>
<p>I can suggest you to write a test and check how fasterxml ObjectMapper read a json and unmarshall json to your object:</p> <pre><code>ObjectMapper objectMapper = new ObjectMapper(); String somestring = objectMapper.readValue("somestring", String.class); </code></pre> <p>just replace <em>String</em> with your class and <em>"somestring"</em> with your json. So you check if there is problem with it. </p> <p>And try to use @JsonPropery cause all this capital letters fields start with looks messy:</p> <pre><code>@JsonIgnoreProperties(ignoreUnknown = true) public class BandWTransaction { @JsonProperty("OrderId") private long OrderId; [...] </code></pre> <p>With this stuff I read json correct. You can come in from other side remove ignoring unknown properties:</p> <p>@JsonIgnoreProperties(ignoreUnknown = true) //remove it and run test public class BandWTransaction {</p> <p>and you get :</p> <blockquote> <p>(11 known properties: "dateAdded", "orderItemExchangeRate", "documentId", "orderItemPrice", "orderId", "orderItemBuyLocation", "orderItemDiscountValue", "orderItemCurrency", "isbn", "title", "publisherOriginalName"])</p> </blockquote> <p>So problem in variables naming and you can fix it with @JsonProperty</p>
How do I convert multiple elements of a character array into an integer? <p>Say I have,</p> <pre><code>char x[0] = '1'; char x[1] = '2'; </code></pre> <p>I need to 'concatenate' these two into an integer variable,</p> <pre><code>int y = 12; </code></pre> <p>How do I do this?</p>
<p>As long as you terminate <code>x</code> with a NULL-terminator you can use <code>atoi</code>.</p> <p><a href="http://ideone.com/z22XKk" rel="nofollow">Example</a>:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { char x[3]; x[0] = '1'; x[1] = '2'; x[2] = '\0'; int x_int = atoi(x); printf("%i", x_int); return 0; } </code></pre>
Deploying Angula2 UI application in High Availability Mode <p>Currently we have implemented a Angular2 UI application and deployed in single server. We would like to implement the UI application in high availability mode by deploying the UI application in 2 servers(1 in active mode and another one in stand-by mode). Is there any easy way of implementing it in Angular2 and nodeJS?</p> <p>Thanks, Rajkumar</p>
<p>Angular2 runs in the client (browser) only. </p> <p>The server only serves static HTML, JS, and CSS files. There are no specific requirements for an Angular2 server (except when you want to use server side rendering). Just build your Angular2 source and you will only get static files for deployment.</p> <p>Any HTTP server will do and any HTTP server can serve multiple clients (it's main purpose ;-) )</p>
Sending an email causes - Connection interrupted <p>Basically what am i trying to do is to send an email: </p> <pre><code>-(void) sendAnEmail { if ([MFMailComposeViewController canSendMail]) { MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init]; mail.mailComposeDelegate = self; [mail setSubject:@"Subject"]; [mail setMessageBody:@"Hey, check this out!" isHTML:NO]; [mail setToRecipients:@[@"testing@gmail.com"]]; [self presentViewController:mail animated:YES completion:NULL]; } else { NSLog(@"device cannot send email"); } } </code></pre> <p>There is no error, no warning. The output if this void is:</p> <blockquote> <p>BSXPCMessage received error for message: Connection interrupted</p> </blockquote> <p><strong>How can I solve this?</strong></p> <p>test device - 5S(8.3)</p>
<ol> <li><p>From <a href="https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingXPCServices.html" rel="nofollow">this Apple Guide</a> I can understand that XPC services are supposed to prevent apps from crashing by separating unstable components somehow.</p></li> <li><p>The crash itself is caused by some kind of a bug in CIFilter. It's hard to tell what actually is wrong with your code, since the issue is obviously not with <code>MFMailComposeViewController</code>. If you are creating <code>CIContext</code> with options like this:</p></li> </ol> <p></p> <pre><code>[CIContext contextWithOptions: @{kCIContextUseSoftwareRenderer : @(NO)}]; </code></pre> <p>Try to replace <code>NO</code> with <code>YES</code></p>
mv command is throwing too many arguments in SOLARIS <pre><code>for f in `find /app/rohith/* -type f -o -prune -name "*.*"` ; mv $f /app/arch/; done </code></pre> <p>ERROR: ksh: /usr/bin/find: arg list too long </p> <hr> <p>Note : -> OS is Solaris -> So, i am using prune here, its similar to maxdepth</p> <p>My Query : How to move only files(not the sub directories) from /app/rohith/ to /app/arch/ in SOLARIS, and also it should not give too many arguments error/exception.</p>
<p>Try this</p> <pre><code>find /app/rohith/* -type f -prune -name "*.*" -exec mv {} /app/arch/ \; </code></pre> <p>I am not sure if it works on solaris but on linux it does</p>
Plot decision boundaries of classifier, ValueError: X has 2 features per sample; expecting 908430" <p>Based on the scikit-learn document <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html#sphx-glr-auto-examples-svm-plot-iris-py" rel="nofollow">http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html#sphx-glr-auto-examples-svm-plot-iris-py</a>. I try to plot a decision boundaries of the classifier, but it sends a error message call "ValueError: X has 2 features per sample; expecting 908430" for this code "Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])"</p> <pre><code>clf = SGDClassifier().fit(step2, index) X=step2 y=index h = .02 colors = "bry" x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) plt.axis('off') # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) </code></pre> <p>the 'index' is a label which contain around [98579 X 1] label for the comment which include positive, natural and negative</p> <pre><code>array(['N', 'N', 'P', ..., 'NEU', 'P', 'N'], dtype=object) </code></pre> <p>the 'step2' is the [98579 X 908430] numpy matrix which formed by the Countvectorizer function, which is about the comment data</p> <pre><code>&lt;98579x908430 sparse matrix of type '&lt;type 'numpy.float64'&gt;' with 3168845 stored elements in Compressed Sparse Row format&gt; </code></pre>
<p>The thing is you <strong>cannot</strong> plot decision boundary for a classifier for data which is not <strong>2 dimensional</strong>. Your data is clearly high dimensional, it has 908430 dimensions (NLP task I assume). There is no way to plot actual decision boundary for such a model. Example that you are using is trained on <strong>2D data</strong> (reduced Iris) and this is <strong>the only reason</strong> why they were able to plot it.</p>
getDrawable with AnimatedVectorDrawable crashes in android version 4 <p>I tried to access AnimatedVectorDrawable as follows using the ContextCompat. Im using the following code to do so. It works well in Android version 5 and above but not in android version 4.</p> <pre><code>@TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startOpenAnimations() { // Icon AnimatedVectorDrawable menuIcon = (AnimatedVectorDrawable) ContextCompat.getDrawable(getContext(), R.drawable.ic_menu_animated); mFabView.setImageDrawable(menuIcon); menuIcon.start(); // Reveal int centerX = mFabRect.centerX(); int centerY = mFabRect.centerY(); float startRadius = getMinRadius(); float endRadius = getMaxRadius(); Animator reveal = ViewAnimationUtils .createCircularReveal(mNavigationView, centerX, centerY, startRadius, endRadius); // Fade in mNavigationMenuView.setAlpha(0); Animator fade = ObjectAnimator.ofFloat(mNavigationMenuView, View.ALPHA, 0, 1); // Animations AnimatorSet set = new AnimatorSet(); set.playSequentially(reveal, fade); set.start(); } </code></pre> <blockquote> <p>android.content.res.Resources$NotFoundException: File res/drawable/ic_menu_animated.xml from drawable resource ID</p> <h1>0x7f020064</h1> <pre><code> at android.content.res.Resources.loadDrawable(Resources.java:3451) at android.content.res.Resources.getDrawable(Resources.java:1894) at </code></pre> <p>android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)</p> </blockquote> <p>why is that getDrawable with ContextCompat is not possible in Lollipop devices</p> <p>How can I be able to sort this out?</p>
<p>Try this : <code>AnimatedVectorDrawableCompat.create(this, R.drawable.animated_vector_name)</code></p> <p>Reference: <a href="http://stackoverflow.com/a/35699072/7001152">http://stackoverflow.com/a/35699072/7001152</a></p>
Convert specific column of file into upper case in unix (without using awk and sed) <p>My file is as below file name = test</p> <pre><code>1 abc 2 xyz 3 pqr </code></pre> <p>How can i convert second column of file in upper case without using awk or sed. </p>
<p>In pure <code>bash</code></p> <pre><code>#!/bin/bash while read -r col1 col2; do printf "%s%7s\n" "$col1" "${col2^^}" done &lt; file &gt; output-file </code></pre> <p>Input-file</p> <pre><code>$ cat file 1 abc 2 xyz 3 pqr </code></pre> <p>Output-file</p> <pre><code>$ cat output-file 1 ABC 2 XYZ 3 PQR </code></pre>
auto load php script <p>I have shared folder between in my server which will allow other server to send XML file to me and I want my script read this file auto without opening any page. I know how to open and read the file.</p> <p>But the issue how to auto load in the backhand. </p>
<p>you have to create a one page which will read the provided file and do the required actions , then share this URL and format with the team who will going to provide you the xml file.</p> <p>It is very much like API Endpoint, Where you have to write the code which will handled request and in this scenario your Endpoint will treat as a server and XML file provider will treat as clients.</p> <p>I hope this answer helps u. Thanks</p>
Looping through array to store duplicate string and add up values of the same string C++ <p>Relatively new to C++ , the following is my code:</p> <pre><code>void displaydailyreport() { std::string myline; string date[100]; // array for dates int dailyprice =0; ifstream myfile("stockdatabase.txt"); // open textfile int i,j; for(i=0;std::getline(myfile,myline);i++) // looping thru the number of lines in the textfile { date[i] = stockpile[i].datepurchased; // stockpile.datepurchased give the date,already seperated by : cout&lt;&lt;date[i]&lt;&lt;endl; // prints out date for(j=i+1;std::getline(myfile,myline);j++) { if(date[i] == date[j]) // REFER TO //PROBLEM// BELOW dailyprice += stockpile[i].unitprice; // trying to add the total price of the same dates and print the // datepurchased(datepurchased should be the same) of the total price // means the total price purchased for 9oct16 } } cout&lt;&lt;endl; } </code></pre> <p>everything is already retrieved and and seperated by : from the methods i have wrote</p> <p><code>stockpile[i].unitprice</code> will print out the price</p> <p><code>stockpile[i].itemdesc</code> will print out the item description</p> <p>PROBLEM</p> <p>I am trying to sum up unitprice of the same dates. and display the total unitprice + date as u can see my textfile , </p> <p>if i do the above if statement of <code>date[i] == date[j]</code> but it won't work because what if there is another 9oct somewhere else?</p> <p>My textfile is:</p> <pre><code>itemid:itemdesc:unitprice:datepurchased 22:blueberries:3:9oct16 11:okok:8:9oct16 16:melon:9:10sep16 44:po:9:9oct16 63:juicy:11:11oct16 67:milk:123:12oct16 68:pineapple:43:10oct16 69:oranges:32:9oct16 &lt;-- </code></pre> <p>Does C++ have array object where i can do this :</p> <pre><code>testArray['9oct16'] </code></pre> <p><strong><em>//EDIT//</em></strong> after trying Ayak973's answer , compiled with g++ -std=c++11 Main.cpp</p> <pre><code>Main.cpp: In function ‘void displaydailyreport()’: Main.cpp:980:26: error: ‘struct std::__detail::_Node_iterator&lt;std::pair&lt;const std::basic_string&lt;char&gt;, int&gt;, false, true&gt;’ has no member named ‘second’ mapIterator.second += stockpile[i].unitprice; </code></pre>
<p>With c++11 support, you can use std::unordered_map to store key/values pair: </p> <pre><code>#include &lt;string&gt; #include &lt;unordered_map&gt; std::unordered_map&lt;std::string, int&gt; totalMap; //... for(i=0;std::getline(myfile,myline);i++) { auto mapIterator = totalMap.find(stockpile[i].datepurchased); //find if we have a key if (mapIterator == totalMap.end()) { //element not found in map, add it with date as key, unitPrice as value totalMap.insert(std::make_pair(stockpile[i].datepurchased, stockpile[i].unitprice)); } else { //element found in map, just sum up values mapIterator-&gt;second += stockpile[i].unitprice; } } </code></pre> <p>After that, you got one map with date as keys, and sum of unit price as values. To get the values, you can use range based for loop :</p> <pre><code>for (auto&amp; iterator : totalMap) { std::cout &lt;&lt; "Key: " &lt;&lt; iterator.first &lt;&lt; " Value: " &lt;&lt; iterator.second; } </code></pre>
Ruby Morse Decoder <p>I tried to create a Morse Decoder. It replaces latin letters with their morse codes. There is one whitespace between letters and three whitespace between words.</p> <pre><code>def decodeMorse(morseCode) morse_dict = { "a" =&gt; ".-","b" =&gt; "-...","c" =&gt; "-.-.","d" =&gt; "-..","e" =&gt; ".","f" =&gt; "..-.","g" =&gt; "--.","h" =&gt; "....","i" =&gt; "..","j" =&gt; ".---","k" =&gt; "-.-","l" =&gt; ".-..","m" =&gt; "--","n" =&gt; "-.","o" =&gt; "---","p" =&gt; ".--.","q" =&gt; "--.-","r" =&gt; ".-.","s" =&gt; "...","t" =&gt; "-","u" =&gt; "..-","v" =&gt; "...-","w" =&gt; ".--","x" =&gt; "-..-","y" =&gt; "-.--","z" =&gt; "--.."," " =&gt; " ","1" =&gt; ".----","2" =&gt; "..---","3" =&gt; "...--","4" =&gt; "....-","5" =&gt; ".....","6" =&gt; "-....","7" =&gt; "--...","8" =&gt; "---..","9" =&gt; "----.","0" =&gt; "-----" } wordList = morseCode.split(" ") wordList.each do |word| word = word.downcase word.split("").each do |letter| a = ' ' + morse_dict[letter].to_s + ' ' word.gsub! letter a end end sentence = wordList.join(' ') return sentence.lstrip end puts decodeMorse("Example from description") </code></pre> <p>Then I got this error:</p> <pre><code>NoMethodError: undefined method `letter' for main:Object from codewars.rb:12:in `block (2 levels) in decodeMorse' from codewars.rb:10:in `each' from codewars.rb:10:in `block in decodeMorse' from codewars.rb:8:in `each' from codewars.rb:8:in `decodeMorse' </code></pre> <p>What is wrong?</p>
<p>The problem is here:</p> <pre><code>word.gsub! letter a </code></pre> <p>it is being interpreted from the right to the left since there is no comma between <code>letter</code> and <code>a</code> it’s being treated as <code>letter(a)</code> function call. You want both <code>letter</code> and <code>a</code> to be passed as parameters to a function call ⇒ separate them <em>with comma</em>:</p> <pre><code># ⇓ HERE word.gsub! letter, a </code></pre> <p>BTW, <code>gsub</code> might take a hash as a second param to make substitutions:</p> <pre><code>word.gsub(/./, morse_dict) </code></pre> <p>would change all letters to their Morse representations. To deal with spaces one might use <code>gsub</code> that takes a block:</p> <pre><code>word.gsub(/./) { |l| " #{morse_dict[l]} " }.squeeze(' ') </code></pre>
jq filter array of object unique propertie value <p>Very simple but beginning with jq.</p> <p>What I have is an array of object. I want to have an array of object filtered by unique value 'myprop'</p> <pre><code>[ { myProp: "similarValue" }, { myProp: "similarValue" }, { myProp: "OtherValue" } ] </code></pre> <p>Result I want:</p> <pre><code>[ { myProp: "similarValue" }, { myProp: "OtherValue" } ] </code></pre> <p>What I've tried: .someContainerProp | unique[] .myProp</p> <p>The problem is that is returns just the list of values not list of object</p>
<p>It was pretty easy actually</p> <p>.values | unique_by(.myProp)</p>
onclick inside function fail <p>I have 3 inputs and 3 buttons. I would like to set a value by clicking on the button. Everything working fine with the first set. When I set next input, it change the value of all my inputs. </p> <p>How can I fix that?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $("input").on("click", function () { var here = $(this); $("div").on("click", "button", function() { here.val(this.value); }); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="text"&gt; &lt;input type="text"&gt; &lt;input type="text"&gt; &lt;div&gt; &lt;button value="a"&gt;a&lt;/button&gt; &lt;button value="b"&gt;b&lt;/button&gt; &lt;button value="c"&gt;c&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p>You can't scope click function inside click function , just use two click and global variable ...</p> <pre><code>$(function() { var here; $("input").on("click", function () { here = $(this); }); $("div").on("click", "button", function() { here.val(this.value); }); }); </code></pre>
Send JSON data through AJAX <p>I'm trying to send data from option selector </p> <pre><code>&lt;select id="city"&gt; &lt;option value="{'city':'melbourne','lat':'-37.8602828','long':'144.9631'}"&gt;Melbourne&lt;/option&gt; </code></pre> <p>Through an AJAX POST</p> <pre><code>$.ajax({ method: "POST", url: "action.php", dataType: "json", data: { city: $('#city option:selected').val() }, }) </code></pre> <p>However I got an empty <code>$_POST</code> in <code>action.php</code>. What is the correct way to send the value of the selected option through an AJAX request?</p>
<p>You have a missing <code>="</code> at the option value attribute</p> <pre><code>&lt;select id="city"&gt; &lt;option value="{'city':'melbourne','lat':'-37.8602828','long':'144.9631'}"&gt;Melbourne&lt;/option&gt; </code></pre> <p>Plus, you can directly access the select value:</p> <pre><code>$.ajax({ method: "POST", url: "action.php", dataType: "json", data: { city: $('#city').val() }, }) </code></pre> <p>At the level of PHP, you have to decode the value of <code>$_POST['city']</code> to get a mapped PHP array:</p> <pre><code>$city = json_decode($_POST['city']); </code></pre>
Mailchimp API form not sending final welcome email <p>I'm trying to build a custom form in my site using the <code>Mailchimp API</code>. I've managed to write up a <code>PHP</code> script which is adding my users to a mailing list from within the Mailchimp dashboard. However I'm having an issue sending them an auto responder email.</p> <p>This is my <code>HTML</code> form:</p> <pre><code>&lt;form method='post' action='&lt;?= get_template_directory_uri() ?&gt;/mailchimp.php'&gt; &lt;input type='text' name='email'/&gt; &lt;input type='submit' name='submit' value='Subscribe'/&gt; &lt;/form&gt; </code></pre> <p>This is my code that handles the request to Mailchimp and adds a user to a list:</p> <pre><code>session_start(); if(isset($_POST['submit'])){ $email = $_POST['email']; if(!empty($email) &amp;&amp; !filter_var($email, FILTER_VALIDATE_EMAIL) === false){ // MailChimp API credentials $apiKey = 'xxx'; $listID = 'xxx'; // MailChimp API URL $memberID = md5(strtolower($email)); $dataCenter = substr($apiKey,strpos($apiKey,'-')+1); $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID; // member information $json = json_encode([ 'email_address' =&gt; $email, 'status' =&gt; 'subscribed' ]); // send a HTTP POST request with curl $ch = curl_init($url); curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo "&lt;h1&gt;$httpCode&lt;/h1&gt;"; return $httpCode; } } </code></pre> <p>I read that you cannot send a final welcome email to anyone unless they are marked as <code>subscribed</code> to your list. I understand Mailchimp enforces a double optin policy unless overriden using the API by setting the users status to subscribed as I've done below:</p> <pre><code>// member information $json = json_encode([ 'email_address' =&gt; $email, 'status' =&gt; 'subscribed' ]); </code></pre> <p>but for some reason I am still not receiving an email upon subscribing to the list. Would anyone have any suggestions as to what I am doing wrong.</p> <p>I've ensured from backend of Mailchimp that the Final Welcome Email is setup.</p>
<p>I've managed to resolve my issue and I'm posting this answer here for anyone who may experience a similar problem to me regarding the sending of a welcome email by way of the single opt-in process.</p> <p><strong>Double Opt In Process</strong></p> <p>Mailchimp enforces a double opt-in policy whereby a user who signs up for your newsletter/service will be sent 2 emails. The first is a confirmation email which enables the user to confirm they requested to join your list. The second is a welcome email - only sent once the user is added to your list.</p> <p><strong>Overriding the Double Opt in Process</strong></p> <p>You can override this functionality by using the <code>Mailchimp API</code>. You must ensure that you add the user with the status of <code>subscribed</code> so that they do not have to go through the double opt-in process. However, this still will not mean that the welcome email is sent. </p> <p><strong>Sending the Welcome Email</strong></p> <p>In order to send this welcome email you must set up an Automation rule. This rule should contain a trigger which is fired immediately after a user subscribes to a list. You can set these rules up in the Mailchimp backend. By doing this you can then send welcome emails to subscribers via the single opt in process. </p> <p><strong>Automation Rules</strong></p> <p>Bear in mind that the Automation rule will only trigger once per email. So if someone were to unsubscribe or be deleted from the list and resubscribed with the same email no welcome email would be received. </p> <p><strong>For Wordpress</strong></p> <p>If you are using <code>Wordpress</code> a great <code>plugin</code> which handles the integration to Mailchimp is <code>Mailchimp for Wordpress</code>. However this on it's own won't work - you need to add the automation via your mailchimp account to send the welcome emails.</p> <p>I hope this helps people in the future!</p>
DB2Driver from jar dependency not found <p>I have created a small jar distribution that sets up a database connection for me. Problem is that when i add it as a gradle dependency I get:</p> <pre><code>java.lang.ClassNotFoundException: com.ibm.db2.jcc.DB2Driver </code></pre> <p>Gradle dependecie tree:</p> <pre><code>--- prokasdb-connector:prokasDBConnection:2.0 +--- commons-collections:commons-collections:3.2.1 +--- commons-dbcp:commons-dbcp:1.4 | \--- commons-pool:commons-pool:1.5.4 +--- commons-pool:commons-pool:1.5.4 +--- log4j:log4j:1.2.17 +--- prokasdb-connector-dependencies:db2jcc:0.1 +--- prokasdb-connector-dependencies:db2jcc4:0.1 +--- prokasdb-connector-dependencies:db2jcc_license_cu:0.1 \--- prokasdb-connector-dependencies:db2small:0.1 </code></pre> <p>Another remark is that when I go to the build path via eclipse menu i noticed that the last for dependencies are missing, while the rest where added automatically. The db2 connector is contained within the last 4 jars, that is why java cannot find it</p>
<p>Add this to your <code>build.gradle</code> and run <code>gradle findClass</code> from command line</p> <pre><code>task findClass { doLast { def foundJars = [] as Set configurations.runtime.files.each { jar -&gt; zipTree(jar).visit { FileVisitDetails fvd -&gt; def path = fvd.relativePath.pathString.replace('\\', '/') if (path == 'com/ibm/db2/jcc/DB2Driver.class') { foundJars &lt;&lt; jar } } } println "Found driver in ${foundJars}" } } </code></pre>
Eloquent relationships: cloumn doesn't exist <p>I'm new to Laravel and am having a bit of a hard time cracking how relationships work. I'm building a simple e-commerce application, where each user has some orders, and order has one or many sub-orders, and each sub-order is linked to only one item (please don't comment on my scheme yet; for now I just need to figure out Eloquent and will be doing refactoring later :) ).</p> <p>Following are my models:</p> <pre><code>class Order extends Model { //timestamp protected $created_at; public function sub_orders() { return $this-&gt;hasMany('App\SubOrder'); } public function user() { return $this-&gt;belongsTo('App\User'); } } class SubOrder extends Model { protected $fillable = array('delivery_date', 'quantity', 'total_price', 'delivery_status'); public function item() { return $this-&gt;hasOne('App\Item'); } public function order() { return $this-&gt;belongsTo('App\Order'); } } class Item extends Model { //note - slug is kind of categorization and is common to many items protected $fillable = array('sku', 'name', 'slug', 'unit_price'); } </code></pre> <p>And here are the migrations:</p> <pre><code>class CreateOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('orders', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;timestamp('created_at'); //foreign keys $table-&gt;unsignedInteger('user_id')-&gt;after('id'); $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users') -&gt;onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('orders'); } } class CreateSubOrdersTable extends Migration { public function up() { Schema::create('sub_orders', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;date('delivery_date'); $table-&gt;decimal('quantity', 5, 2); $table-&gt;decimal('total_price', 7, 2); $table-&gt;enum('delivery_status', ['pending_from_farmer', 'ready_for_customer', 'out_for_delivery', 'delivered']); //foreign keys $table-&gt;unsignedInteger('order_id')-&gt;after('id'); $table-&gt;foreign('order_id')-&gt;references('id')-&gt;on('orders') -&gt;onDelete('cascade'); $table-&gt;unsignedInteger('item_id')-&gt;after('order_id'); $table-&gt;foreign('item_id')-&gt;references('id')-&gt;on('items') -&gt;onDelete('cascade'); }); } public function down() { Schema::dropIfExists('sub_orders'); } } class CreateItemsTable extends Migration { public function up() { Schema::create('items', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;string('sku')-&gt;unique(); $table-&gt;string('name'); $table-&gt;string('slug'); $table-&gt;decimal('unit_price', 5, 2); }); } public function down() { Schema::dropIfExists('items'); } } </code></pre> <p>The problematic expression is why I write <code>App\Order::all()[0]-&gt;sub_orders[0]-&gt;item</code> in my <code>web.php</code> and get the following error:</p> <pre><code>SQLSTATE[42703]: Undefined column: 7 ERROR: column items.sub_order_id does not exist LINE 1: select * from "items" where "items"."sub_order_id" = $1 and ... ^ (SQL: select * from "items" where "items"."sub_order_id" = 1 and "items"."sub_order_id" is not null limit 1) </code></pre> <p>I don't understand why it's looking for <code>sub_order_id</code> in the <code>items</code> table. And what's the right way to go about doing it?</p>
<p>Overall: define the 1-to-1 relationship using <code>hasOne</code> or <code>belongsTo</code> will affect the target table where Laravel find the foreign key. <code>hasOne</code> assume there is a <code>my_model_id</code> in target table.And <code>belongsTo</code> assume there is a <code>target_model_id</code> in my table.</p> <pre><code>class SubOrder extends Model { public function item() { return $this-&gt;hasOne('App\Item', 'id', 'item_id'); } } </code></pre> <p>or </p> <pre><code>class SubOrder extends Model { public function item() { return $this-&gt; belongsTo('App\Item'); } } </code></pre> <p>According to <a href="https://laravel.com/docs/5.3/eloquent-relationships#one-to-one" rel="nofollow">Laravel Doc</a></p> <pre><code>class User extends Model { /** * Get the phone record associated with the user. */ public function phone() { return $this-&gt;hasOne('App\Phone'); } } </code></pre> <blockquote> <p>Eloquent determines the foreign key of the relationship based on the model name. In the above case, <strong>the Phone model</strong> is automatically assumed to have a <strong>user_id foreign key</strong>. If you wish to override this convention, you may pass a second argument to the hasOne method:</p> </blockquote> <pre><code>$this-&gt;hasOne('App\Phone', 'foreign_key', 'local_key'); </code></pre> <p>Or Defining The Inverse Of The Relationship</p> <pre><code>class Phone extends Model { /** * Get the user that owns the phone. */ public function user() { return $this-&gt;belongsTo('App\User'); } } </code></pre> <blockquote> <p>In the example above, Eloquent will try to match the <strong>user_id from the Phone</strong> model to an <strong>id on the User</strong> model.</p> </blockquote>
OData don't connect with SAP Web IDE (local installation) <p>I used automatical OData connection with SAP Web IDE. Unfortunately, Data don't connect and Layout Editor says that Data Set "not defined". I have tried to connect by coding, for example <code>&lt;Table items={/Stats}&gt;</code>, but it doesn't work either. When I use project template (Master-Detail or Worklist), there are no problems with connection and Data is automatically connecting, but when I want to make my project and make a connection, there are always some problems. </p> <p>Component.js</p> <pre><code>sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/Device", "Statusverwaltung/model/models" ], function(UIComponent, Device, models) { "use strict"; return UIComponent.extend("Statusverwaltung.Component", { metadata: { manifest: "json" }, config : { "resourceBundle" : "i18n/i18n.properties", "titleResource" : "SHELL_TITLE", "serviceConfig" : { name: "UI5STAT1_SRV", serviceUrl: "/sap/opu/odata/kernc/UI5STAT1_SRV/" } }, /** * The component is initialized by UI5 automatically during the startup of the app and calls the init method once. * @public * @override */ init: function() { // call the base component's init function UIComponent.prototype.init.apply(this, arguments); // set the device model this.setModel(models.createDeviceModel(), "device"); } }); }); </code></pre> <p>Manifest.json</p> <pre><code>{ "_version": "1.1.0", "sap.app": { "_version": "1.1.0", "id": "Statusverwaltung", "type": "application", "i18n": "i18n/i18n.properties", "applicationVersion": { "version": "1.0.0" }, "title": "{{appTitle}}", "description": "{{appDescription}}", "sourceTemplate": { "id": "servicecatalog.connectivityComponent", "version": "0.0.0" }, "dataSources": { "UI5STAT1_SRV": { "uri": "/sap/opu/odata/kernc/UI5STAT1_SRV/", "type": "OData", "settings": { "odataVersion": "2.0", "localUri": "webapp/localService/UI5STAT1_SRV/metadata.xml" } } } }, "sap.ui": { "_version": "1.1.0", "technology": "UI5", "icons": { "icon": "", "favIcon": "", "phone": "", "phone@2": "", "tablet": "", "tablet@2": "" }, "deviceTypes": { "desktop": true, "tablet": true, "phone": true }, "supportedThemes": ["sap_hcb", "sap_bluecrystal"] }, "sap.ui5": { "_version": "1.1.0", "rootView": { "viewName": "Statusverwaltung.view.View", "type": "XML" }, "dependencies": { "minUI5Version": "1.30.0", "libs": { "sap.ui.core": {}, "sap.m": {}, "sap.ui.layout": {} } }, "contentDensities": { "compact": true, "cozy": true }, "models": { "i18n": { "type": "sap.ui.model.resource.ResourceModel", "settings": { "bundleName": "Statusverwaltung.i18n.i18n" } } }, "resources": { "css": [{ "uri": "css/style.css" }] }, "routing": { "targets": { "View": { "viewType": "XML", "transition": "slide", "clearAggregation": true, "viewName": "View", "viewId": "View" } } } } } </code></pre> <p>neo-app.json</p> <pre><code> { "welcomeFile": "/webapp/index.html", "routes": [ { "path": "/resources", "target": { "type": "service", "name": "sapui5", "entryPath": "/resources" }, "description": "SAPUI5 Resources" }, { "path": "/test-resources", "target": { "type": "service", "name": "sapui5", "entryPath": "/test-resources" }, "description": "SAPUI5 Test Resources" }, { "path": "/sap/opu/odata", "target": { "type": "destination", "name": "v01", "entryPath": "/sap/opu/odata" }, "description": "V01 description" } ], "sendWelcomeFileRedirect": true } </code></pre> <p>.project.json</p> <pre><code> { "projectType": [ "sap.watt.uitools.ide.fiori", "sap.watt.uitools.ide.web", "sap.watt.saptoolsets.fiori.project.ui5template.smartProject", "sap.watt.saptoolsets.fiori.project.uiadaptation" ], "build": { "targetFolder": "dist", "sourceFolder": "webapp" }, "generation": [ { "templateId": "ui5template.basicSAPUI5ApplicationProject", "templateVersion": "1.32.0", "dateTimeStamp": "Mon, 17 Oct 2016 08:28:52 GMT" }, { "templateId": "servicecatalog.connectivityComponent", "templateVersion": "0.0.0", "dateTimeStamp": "Mon, 17 Oct 2016 10:10:52 GMT" }, { "templateId": "uiadaptation.changespreviewjs", "templateVersion": "0.0.0", "dateTimeStamp": "Tue, 18 Oct 2016 08:08:06 GMT" } ], "translation": { "translationDomain": "", "supportedLanguages": "en,fr,de", "defaultLanguage": "en", "defaultI18NPropertyFile": "i18n.properties", "resourceModelName": "i18n" }, "basevalidator": { "services": { "xml": "fioriXmlAnalysis", "js": "fioriJsValidator" } }, "codeCheckingTriggers": { "notifyBeforePush": true, "notifyBeforePushLevel": "Error", "blockPush": false, "blockPushLevel": "Error" }, "mockpreview": { "mockUri": "/sap/opu/odata/kernc/UI5STAT1_SRV/", "metadataFilePath": "webapp/localService/UI5STAT1_SRV/metadata.xml", "loadJSONFiles": false, "loadCustomRequests": false, "mockRequestsFilePath": "" } } </code></pre>
<p>It seems like you are never instantiating a model. You can do that in the manifest.json</p> <pre class="lang-json prettyprint-override"><code> "models": { "i18n": { "type": "sap.ui.model.resource.ResourceModel", "settings": { "bundleName": "Statusverwaltung.i18n.i18n" } }, "": { "dataSource":"UI5STAT1_SRV" } }, </code></pre> <p><code>""</code> defines the default model so you can use Bindingpaths like <code>{/Stats}</code>.</p>
Why the output of this C program that uses fork and shared memory like that? <p>I have question from old exam, Given a C code and m is global variable, when the program finish what the value of m,the answer is "between 7 and 19" but i don't understand why, can someone explain it to me why the answer is between 7-19 and not exactly 19.</p> <pre><code>int m = 0; int main() { int i; fork(); m=3; fork(); for(i=0;i&lt;4;i++) m++; } </code></pre>
<p>The first thing to notice, analysing this problem is that there are no blocking calls, this means that when the main process reaches the end of main the program will finish, regardless of what state the other processes are in.</p> <p>Using this fact we can work out the lower limit of <code>m</code>: this will be when the forked processes don't change the value of <code>m</code> before the main process exits. In this case m will start at 3, and be added to 4 times in the loop, giving you the lower limit of <code>m = 7</code>.</p> <p>The upper limit will happen when all processes have been spawned before any enters the loop and then each process will add 4 to <code>m</code> (which will have a starting value of 3). In other words, <code>m = 3 + N*4</code> where <code>N</code> is the total number of processes spawned.</p> <p>So to finally get the upper limit we need to know how many processes are spawned. The first call of <code>fork()</code> will turn one process into two, and the subsequent call of <code>fork()</code> will turn each of these processes into two, meaning that <code>N = 4</code>.</p> <p>Using our expression for <code>m</code> from before then we see that the upper limit is <code>m = 3 + 4 * 4 = 19</code></p>
Animation with GSAP <p>I am doing an envelope animation using GSAP, been facing quite a lot of issue but couldn't find much help online.</p> <p>I am trying to make some animations to 1) rotate from the front of the envelope to back of the envelope, 2) opening of flap and 3) a letter coming out from an envelope.</p> <p>Currently I am on step 3 now and struggling with "looks like z-index" issue but I am not sure whether is it because of z-index. Somehow I could not get the letter to overlay on top of the flap opening.</p> <p>Below are my gsap code :</p> <pre><code>var tl = new TimelineMax(); var $container = $(".container"), $envelope = $(".envelope"), $envFront = $(".front"), $envBack = $(".back"), $topFlap = $(".top"), $card = $(".card"); tl.set($container, {perspective:1100}) .set($envelope, {transformStyle:"preserve-3d"}) .set($envBack, {rotationY:-180}) .set([$envBack, $envFront], {backfaceVisibility:"hidden"}) .set([$envBack, $envFront, $card], {scale: 0.6}) .set($topFlap, {transformOrigin: "center top"}); $container.click(function(){ tl.to($envelope, 1, {rotationY: 180}) .to($topFlap, 1, {rotationX: 180, z: 0}) .to($card, 1, {top: -50, opacity: 1}, 1); }); </code></pre> <p>I have created in codepen : <a href="https://codepen.io/Dr3am3rz/pen/EgdPOX" rel="nofollow">https://codepen.io/Dr3am3rz/pen/EgdPOX</a></p> <p>Hope you guys can help me out.</p> <p>Thanks in advance.</p>
<p>Anyway I have solved my issue.</p> <p>Missed out a line in the timeline to change the z-index.</p>
Incorrect URLs in Sitecore Habitat <p>After a number of trials, I finally managed to setup Habitat for Sitecore 8.2 </p> <p>The instance name used is <code>habitatdev</code>. I followed the git document on configuring these custom names in 3 config files in the VS solution. </p> <p>The home page <a href="http://habitatdev" rel="nofollow">http://habitatdev</a> works fine. But when trying to browse to any other page (say "About"), it goes to <a href="http://habitat.habitatdev/about" rel="nofollow">http://habitat.habitatdev/about</a>. </p> <p>This is with all other pages. I see there are redirection modules and solutions to create a new layout for redirections.</p> <p>Is there any simple fix like a property in web.config where we can set the Items to navigate to <a href="http://habitatdev/[name]" rel="nofollow">http://habitatdev/[name]</a> instead of <a href="http://habitat.habitatdev/[name]" rel="nofollow">http://habitat.habitatdev/[name]</a></p> <p><strong>FIX:</strong><br> Open this config - <code>\Website\App_Config\Include\Project\Habitat.Website.config</code></p> <p>Look for the <code>site</code> and <code>cacheSizes</code> properties. </p> <p><strong>Original:</strong></p> <pre><code>&lt;sites&gt; &lt;site name="habitatdev" patch:after="site[@name='modules_website']" targetHostName="habitat.$(rootHostName)" database="web" virtualFolder="/" .... /&gt; &lt;/sites&gt; &lt;cacheSizes&gt; &lt;sites&gt; &lt;habitat&gt; &lt;html&gt;50MB&lt;/html&gt; &lt;registry&gt;0&lt;/registry&gt; &lt;viewState&gt;0&lt;/viewState&gt; &lt;xsl&gt;25MB&lt;/xsl&gt; &lt;/habitat&gt; &lt;/sites&gt; &lt;/cacheSizes&gt; </code></pre> <p><strong>Changed to:</strong></p> <pre><code>&lt;sites&gt; &lt;site name="habitatdev" patch:after="site[@name='modules_website']" targetHostName="$(rootHostName)" database="web" virtualFolder="/" .... /&gt; &lt;/sites&gt; &lt;cacheSizes&gt; &lt;sites&gt; &lt;habitatdev&gt; &lt;html&gt;50MB&lt;/html&gt; &lt;registry&gt;0&lt;/registry&gt; &lt;viewState&gt;0&lt;/viewState&gt; &lt;xsl&gt;25MB&lt;/xsl&gt; &lt;/habitatdev&gt; &lt;/sites&gt; &lt;/cacheSizes&gt; </code></pre>
<p>The problem (looking at your comment) is in your site config.</p> <p>You have:</p> <pre class="lang-xml prettyprint-override"><code>&lt;site name="habitat" targetHostName="habitat.habitatdev" database="web" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content/habitat" startItem="/Home" ... /&gt; </code></pre> <p>which means that when Sitecore generates url, it creates them using <code>targetHostName="habitat.habitatdev"</code> for their host names.</p> <p>Just change it to </p> <pre class="lang-xml prettyprint-override"><code>&lt;site name="habitat" targetHostName="habitatdev" database="web" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content/habitat" startItem="/Home" ... /&gt; </code></pre> <p>and all the urls will be <code>http://habitatdev/...</code></p>
npm install fails with error <p>I'm following this tutorial <a href="https://www.youtube.com/watch?v=_-CD_5YhJTA" rel="nofollow">enter link description here</a> but I'v got stuck at 12:41. I downloaded seed project following link in the video description and issued somman <code>npm install</code> as administrator on Windows 7. But I'm getting following error:</p> <pre><code>C:\development\angular2\angular2-seed&gt;npm install &gt; angular2-quickstart@1.0.0 postinstall C:\development\angular2\angular2-seed &gt; typings install (I translated following lines to English) typings is not name of an command, executable or batch. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\ch okidar\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@ 1.0.14: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64" }) npm WARN angular2-quickstart@1.0.0 No description npm WARN angular2-quickstart@1.0.0 No repository field. npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Administrator\\A ppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" npm ERR! node v4.6.0 npm ERR! npm v3.10.8 npm ERR! code ELIFECYCLE npm ERR! angular2-quickstart@1.0.0 postinstall: `typings install` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the angular2-quickstart@1.0.0 postinstall script 'typings ins tall'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the angular2-quickstart p ackage, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! typings install npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs angular2-quickstart npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls angular2-quickstart npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! C:\development\angular2\angular2-seed\npm-debug.log </code></pre> <p>Please advise. Thank you.</p> <p>EDIT: Attached file npm-debug.log: <a href="https://1drv.ms/u/s!AnVEezaTN_ijbhx0Ay5__kXnBWA" rel="nofollow">enter link description here</a> Attached file package.json: <a href="https://1drv.ms/u/s!AnVEezaTN_ijbwCyUWJgrCzWQ10" rel="nofollow">enter link description here</a></p>
<p><strong>Permission Issue</strong>. It probably has to do with the path names in windows.</p> <p>Check the same in Git Bash or Windows Powershell. </p> <p>You can set the NODE path like : <code>set NODE_PATH=source</code></p> <p>Remove the node_modules and run <code>npm install</code> again.</p>
PDO rollback and beginTransaction , cannot work more than 1 query <p>The first query will execute successfully, but for the second query, it doesn't work. The following is the coding which I declare my database and executes two of the queries:</p> <pre><code>$db = new PDO( "sqlsrv:server=$servername ; Database=$databasename", $UserId, $pwd); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-&gt;beginTransaction(); $sql2 = "INSERT INTO Header " . "(Number,Date)" . "VALUES (:Number, :Date)"; try { $stmt2 = $db-&gt;prepare($sql2); $stmt2-&gt;bindParam("Number", $Number); $stmt2-&gt;bindParam("Date", $Date); $stmt2-&gt;execute(); $sql3 = "UPDATE table2 SET Number= :Number WHERE Date= :Date "; try { $stmt3 = $db-&gt;prepare($sql3); $stmt3-&gt;bindParam("Number", $Number); $stmt3-&gt;bindParam("Date ", $Date ); $stmt3-&gt;execute(); } catch(PDOException $e) { $db-&gt;rollBack(); } $db-&gt;commit(); } catch(PDOException $e) { $db-&gt;rollBack(); } </code></pre> <p>I try before set the autocommit to false by <code>$db-&gt;setAttribute(PDO::ATTR_AUTOCOMMIT,0);</code> , however, it show the <code>the auto-commit mode cannot be changed for this driver</code> error message.</p>
<p>You don't need the inner try...catch clause because either 1st or 2nd error would trigger the rollback anyway. <strong>Back to your question</strong>, MySQL might not execute your update statement because your target rows aren't identified by unique id . (unsafe update)</p> <p>you can override the safe update checkpoint as:</p> <pre><code>SET SQL_SAFE_UPDATES =0; do the update.. SET SQL_SAFE_UPDATES =1; </code></pre> <p>or use unique identifiers in your where clause.</p>
react-native calender picker in dialog in ios <p>In <code>react-native-ios</code>, I am using <code>react-native-datepicker</code> for selecting date from calender. For this, I am using following link: <a href="https://github.com/xgfe/react-native-datepicker" rel="nofollow">Date Picker in react-native-ios</a></p> <p>I am adding following code in my render method:</p> <pre><code>&lt;View style={styles.buttonContainer}&gt; &lt;TouchableOpacity style={[styles.bubble, styles.button]} onPress={() =&gt; this.openCalender()}&gt; &lt;DatePicker style={{width: 150}} date={this.state.date} mode="date" placeholder="Date" format="YYYY-MM-DD" minDate="2015-01-01" maxDate="2025-12-01" confirmBtnText="Confirm" cancelBtnText="Cancel" iconSource={require('./assets/cal.png')} onDateChange={(date) =&gt; {this.setState({date: date});}} /&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; </code></pre> <p>but I want to add this date picker in dialog. What will be the way for implementing that in <code>react-native-ios</code>.</p> <p>I want to put Date picker on NavBar Right button click.</p>
<p>I am using this library : <a href="https://github.com/xgfe/react-native-datepicker" rel="nofollow">https://github.com/xgfe/react-native-datepicker</a></p> <p>It works great and cross-platform too.</p>
Collapsing Toolbar and ImageView - toolbar is not showing <p>I have Collapsing <code>Toolbar</code> with <code>ImageView</code> and <code>Toolbar</code> (which contais this three lines icon for side drawer menu for example). <code>ImageView</code> is collapsing just like I want but... Toolbar is not showing at all.When I remove <code>ImageView</code> everything is fine (I mean Toolbar is showing normally).</p> <p><strong>This is my code:</strong></p> <pre><code>&lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginStart="48dp" app:expandedTitleMarginEnd="64dp" android:fitsSystemWindows="true"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/AppTheme.PopupOverlay" /&gt; &lt;ImageView android:layout_width="380dp" android:layout_height="320dp" android:background="@drawable/plant2" android:fitsSystemWindows="true" android:scaleType="centerCrop" app:layout_collapseMode="parallax"/&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" app:tabGravity="fill"/&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; &lt;android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_layout" app:menu="@menu/activity_main_drawer" /&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre>
<p>You need to use app:layout_scrollFlags="scroll|exitUntilCollapsed" inside the CollapsingToolbarLayout</p> <p>and use app:layout_collapseMode="pin" inside the toolbar</p> <pre><code>&lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:contentScrim="?attr/colorPrimary" &gt; &lt;FrameLayout android:layout_width="match_parent" android:layout_height="250dp" app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="0.7" &gt; &lt;ImageView android:id="@+id/backdrop" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /&gt; &lt;View android:layout_width="match_parent" android:layout_height="match_parent" android:background="#20000000" /&gt; &lt;/FrameLayout&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" &gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Application Title" android:textColor="#fff" android:textSize="18sp" /&gt; &lt;/android.support.v7.widget.Toolbar&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; </code></pre>
C++ std::regex How to fix the error_complexity? <p>I used <code>std::regex</code> to match a string. </p> <p>My define of regex is : </p> <pre><code>regex reg("(-?\\d+,?){2,}", regex::icase) </code></pre> <p>Test string is : </p> <pre><code>5,3240,7290,11340,-3240,-7290,-11340 </code></pre> <p>I used std function of <code>regex_match()</code>. The following is the error I got.</p> <blockquote> <p>regex_error(error_complexity): The complexity of an attempted match against a regular expression exceeded a pre-set level.</p> </blockquote> <p>How can I fix the problem ? My compiler is VS2013.</p>
<p>You may "unroll" the <code>,?</code>-containing group into a more linear pattern to reduce complexity - <code>",?-?\\d+(?:,-?\\d+)+"</code>.</p> <p>See <a href="https://ideone.com/vGh1Vf" rel="nofollow">C++ demo</a>:</p> <pre><code>#include &lt;iostream&gt; #include &lt;regex&gt; using namespace std; int main() { regex reg(",?-?\\d+(?:,-?\\d+)+"); string s("5,3240,7290,11340,-3240,-7290,-11340"); if (regex_match(s, reg)) { std::cout &lt;&lt; "Matched!"; } return 0; } </code></pre> <p>Now, the pattern matches:</p> <ul> <li><code>,?</code> - an optional comma</li> <li><code>-?</code> - an optional hyphen</li> <li><code>\\d+</code> - 1 or more digits</li> <li><code>(?:,-?\\d+)+</code> - 1 or more sequences matching <ul> <li><code>,</code> - a comma</li> <li><code>-?\\d+</code> - see above.</li> </ul></li> </ul>
Video won't play on iphone <p>I have an app that places videos online, and cannot find a way to get iPhones to actually play them.</p> <p>ffprobe says:</p> <pre><code> merc@mercs-thinkpad:/disk/home/merc/Downloads$ ffprobe 5801005ff1861ba1729757fbffprobe version 2.8.8-0ubuntu0.16.04.1 Copyright (c) 2007-2016 the FFmpeg developers built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.2) 20160609 configuration: --prefix=/usr --extra-version=0ubuntu0.16.04.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv WARNING: library configuration mismatch avcodec configuration: --prefix=/usr --extra-version=0ubuntu0.16.04.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv --enable-version3 --disable-doc --disable-programs --disable-avdevice --disable-avfilter --disable-avformat --disable-avresample --disable-postproc --disable-swscale --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libvo_aacenc --enable-libvo_amrwbenc libavutil 54. 31.100 / 54. 31.100 libavcodec 56. 60.100 / 56. 60.100 libavformat 56. 40.101 / 56. 40.101 libavdevice 56. 4.100 / 56. 4.100 libavfilter 5. 40.101 / 5. 40.101 libavresample 2. 1. 0 / 2. 1. 0 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 2.101 / 1. 2.101 libpostproc 53. 3.100 / 53. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '5801005ff1861ba1729757fb': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf57.50.100 Duration: 00:00:12.37, start: 0.021333, bitrate: 993 kb/s Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 928 kb/s, 29.83 fps, 29.83 tbr, 11456 tbn, 59.67 tbc (default) Metadata: handler_name : VideoHandler Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, mono, fltp, 70 kb/s (default) Metadata: handler_name : SoundHandler </code></pre> <p>The video is <a href="http://www.wonder-app.com/f/videos/5801005ff1861ba1729757fb" rel="nofollow">here</a></p> <p>The file was created using ffmpeg from within the app.</p> <p>Is this a codec problem? What shall I do to make sure iPhones can actually play them?</p>
<p>Oh my... amazingly, it was the file name! Even though the mime type is set, if the file name is not <code>.mp4</code>, the file won't be treated as a movie file!</p> <p>(Which is amazing to think about, if you know Apple's history...)</p>
Migrating jquery code from stateless react component to es6 component <p>I have a component that renders a Boostrap modal. I want to add a class to another button when the modal appears, so I have the below code:</p> <pre><code>const AddContact = () =&gt; { } $('#myModal').on('show.bs.modal', function (e) { $('.add-button').addClass("orange-btn") }) return ( //modal ... } </code></pre> <p>How do I do the same thing with a es6 component? I tried to put the jquery code into the constructor but it didn't work.</p>
<p>I guess you closed the function's bracket early in 2nd line. Try with this.</p> <pre><code>const AddContact = () =&gt; { $('#myModal').on('show.bs.modal', function (e) { $('.add-button').addClass("orange-btn") }) return ( //modal ... } </code></pre> <p>Hope this will help.</p>
How do I dynamically create a common proxy class of two unrelated classes? <p>I have two unrelated java classes (only <code>*.class</code>, no <code>*.java</code>) like this:</p> <pre><code>public class Trick { public String getName() { return "Jack"; } public String trick() { ... } } </code></pre> <p>and</p> <pre><code>public class Treat { public String getName() { return "John"; } public String treat() { ... } } </code></pre> <p>and I would like to generate a sort of <em>Proxy</em> class at runtime that represents the union of both classes and forwards them to the respective instance, and maybe throw if that's not possible. I assume that can be done with <code>cglib</code> but I don't know where to start.</p> <p>This is what I would like to do (pseudocode):</p> <pre><code>// prepare: generate a common interface TrickOrTreat trickOrTreat = magic.createUnionInterface(Trick.class, Treat.class); // use with concrete interface A: Trick trick = new Trick(); TrickOrTreat proxyA = magic.createProxy(trickOrTreat.class, trick); System.out.println("trick name: " + proxyA.getName()); // use with concrete interface B: Treat treat = new Treat(); TrickOrTreat proxyB = magic.createProxy(trickOrTreat.class, treat); System.out.println("treat name: " + proxyB.getName()); </code></pre> <p>Or something to that effect. I would like to do it completely dynamically, probably <code>cglib</code>-based? If thats not possible I would do it with a code generation step in between?</p>
<ul> <li>If you need functionality of both classes/interfaces you can use</li> </ul> <pre><code>public &lt;TT extends Trick &amp; Treat&gt; void process(TT thing){ //... } </code></pre> <p><strong>edit:</strong> </p> <ul> <li>Implement new Interface MyProxyHandler</li> </ul> <pre><code>public interface MyProxyHandler {} </code></pre> <ul> <li><p>Extend it with interfaces of classes say TreatInterface and TrickInterface</p></li> <li><p>Create class ProxyManager that implements java.lang.reflect.InvocationHandler</p></li> </ul> <pre><code>public abstract class ProxyManager&lt;T extends MyProxyHandler&gt; implements InvocationHandler { protected static String LOCK_OBJECT = new String("LOCK"); protected T proxyHandler; protected List&lt;T&gt; handlers = new ArrayList&lt;&gt;(); @SuppressWarnings("unchecked") public ProxyManager(Class&lt;T&gt; _clazz) { proxyHandler = (T) Proxy.newProxyInstance(_clazz.getClassLoader(), new Class[]{_clazz}, this); } public T getProxy() { return proxyHandler; } public List&lt;T&gt; getHandlers() { return handlers; } public void setHandlers(List&lt;T&gt; handlers) { this.handlers = handlers; } public boolean registerHandler(T handler) { synchronized (LOCK_OBJECT) { boolean add = true; for (T item : this.handlers) { if (item.getClass().equals(handler.getClass())) { add = false; } } if (add) this.handlers.add(handler); return add; } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String result = ""; for (MyProxyHandler handler : getHandlers()) { try { //I recommend that methods returns some enum like HANDLED/NOTHANDLED result = (String) method.invoke(handler, args); if (result.equals("Some flag")) break; } catch (InvocationTargetException e) { throw e.getCause(); } } return result; } } </code></pre> <ul> <li>Extend that class with your concrete class</li> </ul> <pre><code>public class TreatTrickProxyManager&lt;T extends TreatInterface &amp; TreatInterface&gt; extends ProxyManager&lt;T&gt; { public TreatTrickProxyManager(Class&lt;T&gt; _clazz) { super(_clazz); } } </code></pre> <ul> <li><p>In your bussines logic class get an instance of TreatTrickProxyManager</p></li> <li><p>In your method </p></li> </ul> <pre><code>public void retrieveSomeData(){ ((TreatTrickProxyManager)getTreatTrickProxyManager().getProxy()).someMethodInvocation() } </code></pre>
Serializing a JSON object for a Django URL <p>I have a JSON object that looks like this:</p> <pre><code>var obj = { "selection":[ { "author":"John Doe", "articles":[ "Article One", "Article Two" ] } ] } </code></pre> <p>I want to pass this object to Django to render a view that displays 'Article One' and 'Article Two' upon render. I first serialize the JSON object so that it can be appended to a URL; I use <code>$.param(obj)</code> for serialization. Now the JSON object looks something like this:</p> <pre><code>"selection%5B0%5D%5Bauthor%5D=John+Doe&amp;selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&amp;selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two" </code></pre> <p>Now I can append this to a path and use <code>window.open(url)</code> the view will handle everything else. On the Django end, I was surprised to see that the structure of the JSON object has changed to this:</p> <pre><code>"selection[0][author]=John+Doe&amp;selection[0][articles][]=Article+One&amp;selection[0][articles][]=Article+Two" </code></pre> <p>I want to be able to use the JSON object as a dict e.g.:</p> <pre><code>obj = request.GET.get('selection') obj = json.loads(obj) print(obj[0].author) ... </code></pre> <p>How should I handle this JSON structure on the Django side of things?</p>
<p>You are not properly serializing the object to JSON, even if you say you do. The correct way would be to use <code>JSON.stringify()</code>, as @dunder states.</p> <p>Than you parse it back to an object with <code>JSON.parse(strignifiedJson)</code>.</p> <pre><code>var obj = { "selection":[ { "author":"John Doe", "articles":[ "Article One", "Article Two" ] } ] } // Stringify and encode var objAsParam = encodeURIComponent(JSON.stringify(obj)); // Send as a param, for example like http://example.com?obj=YourStringifiedObject... // Parse it back: var parsedObj = JSON.parse(decodeURIComponent(objAsParam)); </code></pre>
ClickOnce Fails to Launch After Install <p>I’m having a problem with my ClickOnce application at work. The application refuses to launch when its icon is clicked. No error is displayed, it just doesn’t load. This is only happening on some deployment machines, not all. As far as I know, all of the machines at work are more-or-less identical ... but I know that often doesn't matter.</p> <p>The application installs/updates okay -- or appears to. The installation log says everything has installed fine; it’s just when the user tries to launch the application that the problem occurs.</p> <p>The application DOES launch when I browse to the .exe in the install location (i.e. C:\Users\Username\AppData\Local\Apps\2.0\etc\etc\etc\Application.exe) using the command prompt. </p> <p>Some details about the non-compliant deployment machines: </p> <ul> <li>The machines have the correct .NET prerequisites installed.</li> <li>They all have the same permissions/firewall settings.</li> <li>They are all running (or are trying to run, rather!) the most recent version of the application.</li> <li>I have tried reinstalling the application/deleting the 2.0 folder &amp; updating several times.</li> <li>There is no Kensington Mouseworks software installed on any of them.</li> </ul> <p>Thanks for your advice.</p>
<p>So, I fixed it ... But not sure how/why this was a fix. Despite the fact that we've disabled UAC on all machines (via the control panel) because we don't want it, I had to make sure that the EnableLUA regkey was set to 1. The thing is, some of the affected PCs already <em>had</em> EnableLUA set to 1, so I simply set it to 0, restarted, set it to 1, then restarted again. (Reg path: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System)</p> <p>Is UAC ever really turned off? And is there a way to turn it off AND have my application run happily at the same time, on all machines?</p>
how to save change from split content of text <p>I've managed to cut the string a sentence into a word. but the new results can be viewed in the browser when the program runs. but these results can not change the condition of the strings in the original text file. I want the contents of the original text file identical to compile the results in the browser. Well how ya how to store the results of the pieces of the word to the text file? in this case stored in notepad with a .txt extension.</p> <p>To cut the text I use the following php code:</p> <pre><code>$width = strlen($openfile)/28000; $wrapped = wordwrap($openfile, $width,'&lt;br&gt;'); //echo $wrapped; $stringedit=str_replace(" ", "&lt;br&gt;", $openfile); echo $stringedit; </code></pre> <p>result from browser is like this</p> <p><a href="https://i.stack.imgur.com/I8dSP.png" rel="nofollow"><img src="https://i.stack.imgur.com/I8dSP.png" alt="enter image description here"></a></p>
<p>You can use:</p> <pre><code>file_put_contents ( $fileName); //here filename indicates the name/path of source file. </code></pre>
React.js, Is `DOMContentLoaded` equal with `componentDidMount`? <p>People always say that you can get the <code>dom</code> in <code>componentDidMount</code> .</p> <p>Is that mean <code>componentDidMount</code> is equal with <code>DOMContentLoaded</code>, or mean when <code>componentDidMount</code>, the <code>dom</code> is always ready?</p>
<p>The <code>DOMContentLoaded</code> event is <em>exclusive</em> to when the <a href="https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded" rel="nofollow">entire HTML page loads</a>. Therefore, this event is only fired once and only once, throughout the entirety of the web page's lifetime. <code>componentDidMount</code>, on the other hand, is called when a React component is rendered. Therefore, it is entirely possible for <code>componentDidMount</code> to be called several times, albeit for entirely different instances of the same component's class.</p> <p>And yes, the browser's DOM is always in the "ready state", at the time when a <code>componentDidMount</code> event is called.</p>
json array for events array in jQuery fullcalendar <p>i'm using jQuery fullcalendar and i must set events dynamically, from a query, using a JSON array, for now i'm trying with a static array. This is my code:</p> <pre><code>&lt;?php $arr = array( array( "title" =&gt; "first", "start" =&gt; "2016-10-18T10:00", "end" =&gt; "2016-10-18T11:00" ), array( "title" =&gt; "second", "start" =&gt; "2016-10-18T12:00", "end" =&gt; "2016-10-18T13:00" ), array( "title" =&gt; "third", "start" =&gt; "2016-10-18T16:00", "end" =&gt; "2016-10-18T17:00" ) ); json_encode($arr); ?&gt; $(document).ready(function () { var initialLocaleCode = 'it'; var events = [$arr]; var eventsArray = []; console.log('e',events); $.parseJSON(events).forEach(function(element, index){ eventsArray.push({ title:element.title, description:element.description.substring(0,30), start:new Date(element.start).toISOString(), end:new Date(element.end).toISOString(), }) } } $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listMonth' }, defaultDate: '2016-09-12', locale: initialLocaleCode, buttonIcons: false, // show the prev/next text weekNumbers: true, navLinks: true, // can click day/week names to navigate views editable: true, eventLimit: true, // allow "more" link when too many events events: eventsArray; </code></pre> <p>it doesn't work... Can someone help me? Thank's</p>
<p>Problem is in your code. Try below one.</p> <pre><code>&lt;?php $arr = array( array( "title" =&gt; "first", "start" =&gt; "2016-10-18T10:00", "end" =&gt; "2016-10-18T11:00" ), array( "title" =&gt; "second", "start" =&gt; "2016-10-18T12:00", "end" =&gt; "2016-10-18T13:00" ), array( "title" =&gt; "third", "start" =&gt; "2016-10-18T16:00", "end" =&gt; "2016-10-18T17:00" ) ); $jsonArr = json_encode($arr); ?&gt; $(document).ready(function () { var initialLocaleCode = 'it'; var events = &lt;?php echo $jsonArr; ?&gt;; var eventsArray = []; console.log('e',events); $.parseJSON(events).forEach(function(element, index){ eventsArray.push({ title:element.title, description:element.description.substring(0,30), start:new Date(element.start).toISOString(), end:new Date(element.end).toISOString(), }) } } $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listMonth' }, defaultDate: '2016-09-12', locale: initialLocaleCode, buttonIcons: false, // show the prev/next text weekNumbers: true, navLinks: true, // can click day/week names to navigate views editable: true, eventLimit: true, // allow "more" link when too many events events: eventsArray; </code></pre> <p>Hope, this will work..!!!</p>
Publishing to npmjs - using a machine user? <p>We're currently working on an open source project (wicked.haufe.io, an API Management system), and for this system, we would like to publish an SDK to npmjs.com for situations where you would want to extend the functionality of the system (it's designed for that).</p> <p>Now, obviously I don't want to publish to npmjs.com using my own user, but would want to use an organization in some way. My questions regarding this (and I didn't find anything appropriate in the npm documentation on this) are:</p> <ul> <li>Can and should I use a machine user for npmjs.com when publishing? Is this allowed? We'd build and publish from our own build pipelines, and those only use machine credentials, not personal ones.</li> <li>Do I need a paid plan even if my organization only wants to publish open source packages?</li> </ul> <p>The second bullet point is not that big an issue, we can do with the minimal $14 for an organization; the first issue is what's interesting.</p> <p>Best regards, Martin</p>
<p>From my understanding machine credentials have nothing to do with it. The only credentials that matter are when you try to "npm publish", it will ask for npmjs.com credentials which you have already created (and can be anything). As far as company and publishing information for the package, you can arbitrarily include whatever you want in the package.json file. Just type "npm init".</p> <p><a href="https://docs.npmjs.com/files/package.json" rel="nofollow">See link here</a></p> <p>I don't think a paid account would be required.</p>
MySQL find ids for which there is no existing row <p>I have three tables : </p> <pre><code>1. Person (person_id, name) : (1, "Test1"), (2, "Test2"), (3, "Test3") 2. Role (role_id, description) : (1, "Admin"), (2, "Designer"), (3, "Developer") .. 3. PersonRoles (person_id, role_id) : (1 , 1), (1, 2), (2, 3), (2, 1), (3, 1) </code></pre> <p>Is it possible in MySQL with a query to get the ids of the people for which there`s no row with exact role in the PersonRoles table. For Example if I want to check for "Designer" role the query should return ids: 2 and 3</p>
<p>Here is your solution: </p> <pre><code>select person_id from Person where person_id not in (select person_id from Role r inner join PersonRoles pr on pr.role_id=r.role_id where r.description='Designer') </code></pre>
modify lists removing elements without making a mess <p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
<p>You should use <code>del</code> to delete list item. Also you should iterate from end to the beginning because if you will go from the beginning and delete let say <code>1st</code> element the element that was on the <code>3rd</code> place will be now on the <code>2nd</code></p> <p>It should look like</p> <pre><code>#you need to handle what if len of lists is 0, if lens are not the same and so on... def compare_and_delete(list1, list2): i = len(list1) -1 while i &gt;= 0: if list1[i] &gt; list2[i]: del list1[i] elif list2[i] &gt; list1[i]: del list2[i] else: del list1[i] del list2[i] i-=1 return list1, list2 l1, l2 = compare_and_delete(['bear', 'tiger', 'wolf', 'whale', 'elephant'], ['swan', 'cat', 'dog', 'duck', 'rabbit']) </code></pre>
Login via enter button <p>I have login form and it works fine, but I don't know how to make it work via enter buttom. I did try to make it with JS, but it didn't work for some reason.</p> <p>Also I think I made horrible code for login :(, but it works.</p> <pre><code>&lt;div class="clientLogin"&gt; &lt;form&gt; &lt;div class="closeBtn"&gt;&lt;i class="icofont icofont-close"&gt;&lt;/i&gt;&lt;/div&gt; &lt;div class="h5"&gt;sign in&lt;/div&gt; &lt;div class="userName"&gt;&lt;input name="userName" placeholder="E-mail" id="username" type="text"&gt;&lt;/div&gt; &lt;div class="password"&gt;&lt;input name="password" placeholder="Password" id="password" type="password"&gt;&lt;/div&gt; &lt;div class="failedlogin" id="failed"&gt;&lt;/div&gt; &lt;div class="sucesslogin" id="success"&gt;&lt;/div&gt; &lt;input type="button" class="zzzz" onclick="auth()" value="sign in"/&gt; &lt;div class="h5"&gt;Forgot Passsword? &lt;a href="https://billing.xeovo.com/?func=recovery&amp;lang=en"&gt;Click here&lt;/a&gt;&lt;/div&gt; &lt;div class="logBtm"&gt; &lt;div class="h5" id="data"&gt;Don’t have an account yet?&lt;/div&gt; &lt;a href="https://billing.xeovo.com/billmgr?func=register&amp;lang=en" class="signUp"&gt;Click here to sign up.&lt;/a&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>Website: <a href="https://www.xeovo.com" rel="nofollow">https://www.xeovo.com</a></p>
<p>Make the sign in input a type of <code>submit</code>. Like this,</p> <pre><code>&lt;input type="submit" class="zzzz" onclick="auth()" value="sign in"/&gt; </code></pre> <p>This should fix the issue. It's a type of <code>button</code> currently which doesn't get triggered on submitting enter key. </p>
How to get result in blocks immediately? <p>I'm using blocks to get header fields from response in one class and I have to get that in another class. </p> <p>I implemented code like this</p> <p>In first class:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; UserAuthentication *auth = [[UserAuthentication alloc]init]; NSDictionary *dict = [auth getUserConfiguration]; NSLog(@"%@",dict); } </code></pre> <p>In userAuthentication class:</p> <pre><code>-(NSDictionary *)getUserConfiguration; { __block NSDictionary *resultDictionary; NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithURL:[NSURL URLWithString:@"http://72.52.65.142:8083/auth"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; if ([response respondsToSelector:@selector(allHeaderFields)]) { resultDictionary = [httpResponse allHeaderFields]; NSLog(@"%@",resultDictionary); } }] resume]; NSLog(@"%@",resultDictionary); return resultDictionary; } </code></pre> <p>Here my problem is in first class I'm getting <code>dict</code> as null.</p> <p>Even in <code>userAuthentication</code> class also I'm getting null.</p> <p>But after some time call back method is calling and then I can see the response correctly in <code>completionHandler</code>.</p> <p>So how I can get response in firstClass?</p>
<p>You are misunderstanding the basic principle of async operation that runs in background thread and when the operation is completed it gives you data in completion block.</p> <p>To get response in viewDidLoad Method of second class you need to use blocks. like below</p> <pre><code>-(void)getUserConfigurationOnCompletion:(void (^)(NSDictionary *))completion { __block NSDictionary *resultDictionary; NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithURL:[NSURL URLWithString:@"http://72.52.65.142:8083/auth"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; if ([response respondsToSelector:@selector(allHeaderFields)]) { resultDictionary = [httpResponse allHeaderFields]; // Call completion with parameter completion(resultDictionary); } }] resume]; } </code></pre> <p>and use it like this in viewDidLoad</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; UserAuthentication *auth = [[UserAuthentication alloc]init]; [auth getUserConfigurationOnCompletion:^(NSDictionary *dict){ // do necessary work with response dictionary here NSLog(@"%@",dict); }]; } </code></pre>
Custom GL plugin's GL Impact Line disappearing when the transaction posting flag is "YES" <p>I have created the <strong>custom GL Plugin and configured to the Invoice Transaction.</strong> Every created <strong>Invoice Transaction is goes for approval process</strong>, once the invoice is approved the <strong>status changed from pending approval to open status.</strong></p> <p>when the Invoice Transaction created the Custom GL Impact, working perfectly by creating the Custom GL Lines. Since the Invoice is "Pending Approval State" the Standard and Custom GL Showing correctly and the posting flag is "NO". when the Invoice is approved ,while seeing the GL Impact of the transaction only standard GL Lines are appearing and the Custom GL Lines are disappeared. and posting flag changed to "YES".</p> <p>My Question is whether the Custom GL Impact plugin will create the custom GL Lines only when the <strong>posting flag is "NO"</strong> or it will remain as it is on the transaction when <strong>posting flag status is both "yes" and "No".</strong></p>
<p>NetSuite Custom GL Impact will run on on both Non posting and Posting.</p> <p>Can you provide the code you are using in the Custom GL plugin? It sounds like a logic issue. Do you have any logs?</p>
Vertical Bar chart using rotation='vertical' not working <p>From the matplot lib example <a href="http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html" rel="nofollow">lines_bars_and_markers</a> using <code>rotation='vertical'</code> does not make it vertical. What am I doing wrong?</p> <pre><code>""" Simple demo of a horizontal bar chart. """ import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4) plt.yticks(y_pos, people) plt.xlabel('Performance') plt.title('How fast do you want to go today?') plt.show() rotation='vertical' </code></pre>
<p><code>barh</code> is for horizontal bar charts, change to <code>bar</code> and then swap around the data for the axes. You can't simply write <code>rotation='vertical'</code> because that isn't telling the <code>matplotlib</code> library anything, it's just creating a string that is never used. </p> <pre><code>import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') x_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) plt.bar(x_pos, performance, yerr=error, align='center', alpha=0.4) plt.xticks(x_pos, people) plt.ylabel('Performance') plt.title('How fast do you want to go today?') plt.show() </code></pre>
Last digit in a exponent b <p>I wrote this code to find last digit of a exponent b but SPOJ says its wrong. I tried almost all test cases but couldn't find the error. Problem:<a href="http://www.spoj.com/problems/LASTDIG/" rel="nofollow">http://www.spoj.com/problems/LASTDIG/</a> My Solution:</p> <pre class="lang-java prettyprint-override"><code>package spoj; import java.util.Scanner; public class LastDigit { public static void main(String[] args) throws java.lang.Exception { Scanner p = new Scanner(System.in); for(int test = p.nextInt();test&gt;0;test-- ){ int a = p.nextInt(); int b = p.nextInt(); int result = (int) Math.pow(a,b); System.out.println(result%10); } } } </code></pre>
<p><code>Math.pow</code>is a floating point operation! It doesn't compute the exact result. That's why you have that funny cast to int in there.</p> <p>Therefore you need to use <code>BigInteger</code> or write your own exponentiation function. The latter is the more desirable since the way more efficient way to compute the last digit is to reduce a modulo 10, b modulo 4, <em>then</em> take the power and then reduce modulo 10 again. This should even work within the range were floating-point arithmetic is exact.</p> <p>Also: You really should have a check in there whether <code>a % 10</code>is even invertible modulo 10 if <code>b</code>is negative. Otherwise your doing the modulo-10-equivalent of a division by zero.</p>
Restoring NSTableView sort order after reload <p>In Interface Builder, an NSTableView is set up with sortable columns (by clicking on the column headers). The data source uses an NSArray. When updating a row of data, the table's data is reloaded which refreshes the array and lays out the data rows according to the array's order.</p> <p>I would like to keep the table column's sort order. I tried saving the table's sortDescriptors, reloading data, and restoring the table's sortDescriptors, but that does not trigger the desired reload. I suspect I want to refresh the array according to the sortDescriptors such that reloading will lay out as desired. Please enlighten me.</p>
<p>The answer was under my nose. I can use the data source method <code>tableView:sortDescriptorsDidChange:</code>.</p> <p>I think a cleaner solution is to post the notification for the data source. It should be the same notification as when clicking on a column header. If anyone knows, kindly share here.</p>
Mysql Trigger IF(select) doesn't work <p>The following code in my trigger doesn't work when I add a record in the table 'Assessment' (column seen of table 'person' wasn't updated when adding a record in 'Assessment')</p> <pre><code>IF ((select CAST(max(`date`) AS DATE) from `Assessment` where x = NEW.x and (`date` != NEW.`date`) and is_deleted = 0) != null) THEN UPDATE person set seen = 1; END IF </code></pre>
<p>the issue was in the condition on date that's why I get null in query, so I added the conditions <code>'and day(</code>date<code>) &lt; day(NEW.</code>date<code>) and month(</code>date<code>) &lt;= month(NEW.</code>date<code>) and year(</code>date<code>) &lt;= year(NEW.</code>date<code>)'</code> then I got the right record.</p>
Import existing web application into Bluemix <p>I've existing Web application developed and would like to import the entire repo into Bluemix. This web application required Web Server, Node.js and Bootstrap. Which is the most appropriate buildpack under CloundFoundry should I use?</p> <p>I've uploaded my application to Github <a href="https://github.com/mikeytsk/signage_example_0408" rel="nofollow">https://github.com/mikeytsk/signage_example_0408</a></p> <p>Thanks Michael</p>
<p>use following steps to add your git repository for Deploying app on Bluemix.</p> <p>1) Create an app on bluemix by clicking on "Cloud Foundry app "and then <a href="https://i.stack.imgur.com/esXqv.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/esXqv.jpg" alt="enter image description here"></a> </p> <p>Then on Web -</p> <p><a href="https://i.stack.imgur.com/vYMsj.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vYMsj.jpg" alt="enter image description here"></a></p> <p>and Then choose SDK for Node.js-</p> <p><a href="https://i.stack.imgur.com/2AoBv.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/2AoBv.jpg" alt="enter image description here"></a></p> <p>2) Give you App a name. You can see your App staging and started on Bluemix. </p> <p><a href="https://i.stack.imgur.com/NFq9v.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/NFq9v.jpg" alt="enter image description here"></a></p> <p>3) Click on the App and you will be redirected to App overview page. There you will find ADD GIT option at top right corner. </p> <p><a href="https://i.stack.imgur.com/SLNiW.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SLNiW.jpg" alt="enter image description here"></a></p> <p>4) A pop will appear asking you to create git Repository. Click on "Create" option to create one. </p> <p>5) Now you can see a git repository created for you. The link is given at top right corner. But the Git repository created will be in hub.jazz.net not GITHUB. <a href="https://i.stack.imgur.com/alfsp.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/alfsp.jpg" alt="enter image description here"></a></p> <p>6) To Sync your app with Github account, click on the Git url, a new tab will open with Git Repository shown to you. Click on the button at right top corner. <a href="https://i.stack.imgur.com/WYGqo.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/WYGqo.jpg" alt="enter image description here"></a></p> <p>7) A pop will come up. Select Change repository and link you Git hub account with Bluemix. <a href="https://i.stack.imgur.com/cHuVp.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/cHuVp.jpg" alt="enter image description here"></a></p> <p>8) Clicking on Authorise with Github will take you to github page, where you can authorise Bluemix to access your Repository. Once, its done. It will be easy for you to use your existing Repository with Bluemix. In case, you can also go through the Bluemix Documentation for further clarity. Following is the link - <a href="https://console.ng.bluemix.net/docs/starters/deploy_devops.html" rel="nofollow">https://console.ng.bluemix.net/docs/starters/deploy_devops.html</a></p> <p>Hope this helps you, Let me know if you face any issue. </p>
How to create an isolated html page without any link/reference to the home page using angularjs? <p>Am new to AngualrJS. I reference index.html as my home page and I want to map a partial link which is not at all related to the home page(<code>index.html</code>); example, <code>http://www.example.com/newpage</code>.</p> <p>Here, the newpage shouldn't have any connection with the <code>index.html</code>. and where to put my <code>newpage.html</code> in the project.</p>
<p>To achieve what you want, you need to have two differente apps. Every app needs a fixed route prior to the '#'.</p> <p>So, in your case, index.html would have it's app, and newpage.html would have another one.</p>
Clicking on an element targeted by id but result is still incorrect <p>I am testing Selenium-Webdriver on Google Translate page. What I'm trying to do is:</p> <ol> <li>See if the input language is already presented</li> <li>If presented, is it selected? If not select it.</li> <li>If not present, open the more language table. Select (click on) the language on the table.</li> <li>See if the output language is already presented</li> <li>If presented, is it selected? If not select it.</li> <li>If not present, open the more language table. Select (click on) the language on the table.</li> <li>Finally translate and check result</li> </ol> <p>I don't have any problem with Case 1: Input and Output language already presented and the result is as expected. But with Case 2: Output language is not presented yet and has to be selected on the table, the problem occurs. <strong>The language selected is incorrect</strong> (for example, I choose Norwegian but finally Samoan will be selected). <em>The select input uses the same way to select but doesn't return any issue at all</em>.</p> <h1>My code below</h1> <pre><code>package TestNG; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.*; public class GoogleTranslate { WebDriver driver; @BeforeMethod public void setUp() { System.setProperty("webdriver.gecko.driver","F:\\path\\geckodriver.exe"); driver=new FirefoxDriver(); } @Test(priority=0) public void VietnameseToEnglish() throws InterruptedException { // Go to google translate driver.manage().window().maximize(); driver.get("https://translate.google.com/"); Thread.sleep(5000); // Check if the page is correct String currentTitle = driver.getTitle(); Assert.assertEquals(currentTitle, "Google Translate"); Thread.sleep(3000); // Select Vietnamese as input if (driver.findElements(By.xpath("//div[@id='gt-lang-left']/div[@id='gt-lang-src']/div[@id='gt-sl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='vi']")).size() &gt; 0) { WebElement Vi = driver.findElement(By.xpath("//div[@id='gt-lang-left']/div[@id='gt-lang-src']/div[@id='gt-sl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='vi']")); String isViSelected = Vi.getAttribute("aria-pressed"); if (isViSelected.equals("false")) { Vi.click(); } } else { WebElement allLangSrc = driver.findElement(By.id("gt-sl-gms")); allLangSrc.click(); WebElement ViSrc = driver.findElement(By.xpath("//div[@id='goog-menuitem-group-7']/div[@id=':2r']/div")); ViSrc.click(); } // Select English as output if (driver.findElements(By.xpath("//div[@id='gt-lang-right']/div[@id='gt-lang-tgt']/div[@id='gt-tl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='en']")).size() &gt; 0) { WebElement En = driver.findElement(By.xpath("//div[@id='gt-lang-right']/div[@id='gt-lang-tgt']/div[@id='gt-tl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='en']")); String isEnSelected = En.getAttribute("aria-pressed"); if (isEnSelected.equals("false")) { En.click(); } } else { WebElement allLangTrg = driver.findElement(By.id("gt-tl-gms")); allLangTrg.click(); WebElement EnTrg = driver.findElement(By.xpath("//div[@id='goog-menuitem-group-2']/div[@id=':3j']/div")); EnTrg.click(); } WebElement Input = driver.findElement(By.id("source-is")); //Input.clear(); Input.sendKeys("Ga"); WebElement TranslateButton = driver.findElement(By.id("gt-submit")); TranslateButton.click(); Thread.sleep(3000); WebElement Output = driver.findElement(By.xpath("//span[@id='result_box']/span")); String Outtext = Output.getText(); Assert.assertEquals(Outtext, "Chicken"); } @Test(priority=1) public void VietnameseToNorg() throws InterruptedException { // Go to google translate driver.manage().window().maximize(); driver.get("https://translate.google.com/"); Thread.sleep(5000); // Check if the page is correct String currentTitle = driver.getTitle(); Assert.assertEquals(currentTitle, "Google Translate"); Thread.sleep(3000); // Select Vietnamese as input if (driver.findElements(By.xpath("//div[@id='gt-lang-left']/div[@id='gt-lang-src']/div[@id='gt-sl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='vi']")).size() &gt; 0) { WebElement Vi = driver.findElement(By.xpath("//div[@id='gt-lang-left']/div[@id='gt-lang-src']/div[@id='gt-sl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='vi']")); String isViSelected = Vi.getAttribute("aria-pressed"); if (isViSelected.equals("false")) { Vi.click(); } } else { WebElement allLangSrc = driver.findElement(By.id("gt-sl-gms")); allLangSrc.click(); WebElement ViSrc = driver.findElement(By.xpath("//div[@id='goog-menuitem-group-7']/div[@id=':2r']/div")); ViSrc.click(); } // Select Norg as output if (driver.findElements(By.xpath("//div[@id='gt-lang-right']/div[@id='gt-lang-tgt']/div[@id='gt-tl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='no']")).size() &gt; 0) { WebElement No = driver.findElement(By.xpath("//div[@id='gt-lang-right']/div[@id='gt-lang-tgt']/div[@id='gt-tl-sugg']/div[contains(@class,'goog-inline-block jfk-button jfk-button-standard') and @value='no']")); String isNoSelected = No.getAttribute("aria-pressed"); if (isNoSelected.equals("false")) { No.click(); } } else { WebElement allLangTrg = driver.findElement(By.id("gt-tl-gms")); allLangTrg.click(); WebElement NoTrg = driver.findElement(By.xpath("//div[@id='goog-menuitem-group-5']/div[@id=':52']/div")); NoTrg.click(); } WebElement Input = driver.findElement(By.id("source-is")); //Input.clear(); Input.sendKeys("Sua"); WebElement TranslateButton = driver.findElement(By.id("gt-submit")); TranslateButton.click(); Thread.sleep(3000); WebElement Output = driver.findElement(By.xpath("//span[@id='result_box']/span")); String Outtext = Output.getText(); Assert.assertEquals(Outtext, "Melk"); } @AfterMethod public void tearDown(){ driver.close(); driver.quit(); } } </code></pre>
<p>I would do something like this. You should focus on creating functions that do a single thing so that you have reusable code that can be used in various tests easily.</p> <p>Here are my functions</p> <pre><code>static public String getTranslatedText() { new WebDriverWait(driver, 10).until(new ExpectedCondition&lt;Boolean&gt;() { public Boolean apply(WebDriver d) { return d.findElement(By.id("result_box")).getText().length() != 0; } }); return driver.findElement(By.id("result_box")).getText(); } static public void setSourceLanguage(String lang) { // see if the desired language is already selected if (!driver.findElement(By.cssSelector("#gt-lang-src div.jfk-button-checked")).getText().equals(lang)) { // open the Source language dropdown driver.findElement(By.id("gt-sl-gms")).click(); // select the desired language driver.findElement(By.xpath("//div[@id='gt-sl-gms-menu']//div[text()='" + lang + "']")).click(); } } static public void setTargetLanguage(String lang) { // see if the desired language is already selected if (!driver.findElement(By.cssSelector("#gt-lang-tgt div.jfk-button-checked")).getText().equals(lang)) { // open the Source language dropdown driver.findElement(By.id("gt-tl-gms")).click(); // select the desired language driver.findElement(By.xpath("//div[@id='gt-tl-gms-menu']//div[text()='" + lang + "']")).click(); } } static public void translateText(String text) { driver.findElement(By.id("source")).sendKeys(text); } </code></pre> <p>A simple test would look like</p> <pre><code>driver.get("https://translate.google.com/"); setSourceLanguage("English"); setTargetLanguage("Lao"); translateText("This is some text"); System.out.println(getTranslatedText()); </code></pre> <hr> <p>After going through this exercise, I noticed the URL after the text was translated was <a href="https://translate.google.com/#en/lo/This%20is%20some%20text" rel="nofollow">https://translate.google.com/#en/lo/This%20is%20some%20text</a>. I'm assuming that you aren't testing google translate but instead just want the translations? If that's true, you could just navigate to the URL based on the language tokens and pass in the desired text.</p> <p>The URL is of the form</p> <pre><code>https://translate.google.com/#&lt;source language token&gt;/&lt;target language token&gt;/&lt;text to be translated&gt; </code></pre> <p>So Vietnamese to English would be</p> <pre><code>https://translate.google.com/#vi/en/This%20is%20some%20text </code></pre> <p>and Vietnamese to Norwegian would be</p> <pre><code>https://translate.google.com/#vi/no/This%20is%20some%20text </code></pre> <p>Then all you would have to do is to grab the translated text.</p>
Custom attributes for angular translate <p>I am doing a research if I can use a non alphabetic characters for custom translate value attributes. I walked through that doc</p> <p><a href="https://angular-translate.github.io/docs/#/guide/06_variable-replacement" rel="nofollow">https://angular-translate.github.io/docs/#/guide/06_variable-replacement</a></p> <p>and I was playing around here:</p> <p><a href="http://plnkr.co/edit/MFxE13ioZfzH74TcarM7?p=streamer" rel="nofollow">http://plnkr.co/edit/MFxE13ioZfzH74TcarM7?p=streamer</a></p> <pre><code>var translations = { VARIABLE_REPLACEMENT: '{{aa}}_REQUIRES_AN_APPROVAL', VARIABLE_REPLACEMENT2: '{{@@}}_REQUIRES_AN_APPROVAL' }; </code></pre> <p>and I cant display 2nd line of translations as long as I use some symbols in angular expression e.g. {{@@}}</p> <p>Does anybody know what symbols are allowed for custom attributes of angular translate? Or way to workaround this so that symbols are allowed?</p> <p>I could not find any doc on that, but I am new to programming so maybe I was searching wrongly:)</p>
<p>According to <a href="http://stackoverflow.com/a/9337047/744534">this</a> answer, <code>@@</code> can't be an identifier.</p> <p>Hence <code>@@</code> can't be part of translation texts.</p>
Number guessing what the user has in mind C <p>I'm trying to create a program where the program guesses what kind of number the user has in mind. First it will ask the user for a minimum and maximum number, for example 1 and 10(the number I have in mind should be between 1 and 10 then).<br> Lets say I have the number 4 in mind and the program will output a number. I can type in L for low, H for high or G for good.<br> If I type in L, the program should generate a number lower than the guessed number, for H it should guess an higher number. If I input G, the program should stop and print out how many times it guessed.<br> I have added my code below, what am I missing?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() { int minNumber; int maxNumber; int counter; printf("Give min and max: "); scanf("%d %d", &amp;minNumber, &amp;maxNumber); //printf("%d %d", minNumber, maxNumber); int num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber; char input[100]; do { printf("is it %d? ", num_between_x_and_y); scanf("%s", input); if (input == 'L') { counter++; } if (input == 'H') { counter++; } } while (input != 'G'); printf("I guessed it in %d times!", counter); return 0; } </code></pre>
<p>You can't use <code>==</code> to compare strings (which are multiple bytes).</p> <p>Either do <code>if (input[0] == 'L')</code> to just compare the first letter the user entered to a literal value, or <code>if (strcmp(input,"L") == 0)</code> to compare everything the user entered to the 1 character string literal (to use <code>strcmp</code> you will need to add <code>#include &lt;string.h&gt;</code></p> <p>Also your code is missing other things, like counter should be set to presumably set to zero before you use it. I assume you haven't finished your code yet because you can't get the user input part to work.</p>
WSO2 DAS + Clustering APIM with mysql <ol> <li><p>My APIM version is 1.10.0 and DAS is 3.0.1.</p></li> <li><p>At first ,I deploy no Clustering APIM + DAS with mysql. the stats shows good.</p></li> <li><p>Then,I clustering APIM into publisher、store、keymanager and gateway.Configured APIM and DAS order <a href="https://docs.wso2.com/display/AM1100/Publishing+API+Runtime+Statistics+Using+RDBMS#PublishingAPIRuntimeStatisticsUsingRDBMS-ConfiguringWSO2APIManager" rel="nofollow">this article</a>,when I invoke an api , gateway node then show error</p></li> </ol> <blockquote> <pre><code>[2016-10-13 11:13:54,775] ERROR - APIMgtUsageHandler Cannot publish event. null java.lang.NullPointerException at org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher.publishEvent(APIMgtUsageDataBridgeDataPublisher.java:124) at org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageHandler.handleRequest(APIMgtUsageHandler.java:169) at org.apache.synapse.rest.API.process(API.java:322) at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:86) at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:65) at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:295) at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:83) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:317) at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:149) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) [2016-10-13 11:13:54,807] ERROR - APIMgtResponseHandler Cannot publish response event. null java.lang.NullPointerException at org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher.publishEvent(APIMgtUsageDataBridgeDataPublisher.java:140) at org.wso2.carbon.apimgt.usage.publisher.APIMgtResponseHandler.mediate(APIMgtResponseHandler.java:211) at org.apache.synapse.mediators.ext.ClassMediator.mediate(ClassMediator.java:84) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:81) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:48) at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:155) at org.apache.synapse.rest.Resource.process(Resource.java:297) at org.apache.synapse.rest.API.process(API.java:335) at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:86) at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:52) at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:295) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.handleMessage(SynapseCallbackReceiver.java:529) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.receive(SynapseCallbackReceiver.java:172) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) at org.apache.synapse.transport.passthru.ClientWorker.run(ClientWorker.java:251) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) </code></pre> </blockquote> <ol start="4"> <li>Then i change the way of DAS configuration. Following <a href="http://rukspot.com/configure_wso2_apim_analytics_using_xml.html" rel="nofollow">this blog</a> ,i configured all the api-manager.xml,there is no error and no stats.And store node show info:</li> </ol> <blockquote> <pre><code>[2016-10-18 11:31:39,131] INFO - ReceiverGroup Resending the failed published data... [2016-10-18 11:31:44,134] WARN - AccessConfiguration Error loading properties from file: access-log.properties [2016-10-18 11:31:44,207] INFO - TimeoutHandler This engine will expire all callbacks after : 120 seconds, irrespective of the timeout </code></pre> </blockquote> <ol start="5"> <li>I google the reason ,in <a href="https://wso2.org/jira/browse/APIMANAGER-4307" rel="nofollow">wso2 jira</a>,they say this is not a bug.</li> </ol> <p>But I cannot wait for my stats for hours.Did I configure something wrong?</p> <p>Reguards.</p>
<p>Seems in store node, data are publishing are enabled and working. But gateway node data not publishing. Please try to verify the gateway node configuration. Also check gateway node can access the DAS node.</p>
counting number of true/talse periods in r <p>I have a boolean vector derived from a time series. It basically looks like this: c(true, false, true, true, false, false, false, true, true...).</p> <p>I want to count the periods in which the vector is true. Example: for a vector like this: c(true, true, false, true) it would be 2 (1 long true period in the beginning, 1 short in the end). </p> <p>the vector can contain NAs in the beginning. </p> <p>I thought of something like:</p> <pre><code>aaa &lt;- c(NA,F,T,T,T,F) for(j in 1:(length(aaa)-1)){ if(aaa[j]!=aaa[j+1]){ # add a counter that returns [1] } } </code></pre> <p>=================================================</p> <p>edit: This works fine for me:</p> <pre><code>data.frame("#"=unlist(rle(aaa)[1]),"length"=unlist(rle(aaa)[2])) </code></pre>
<p>How about this:</p> <pre><code>aaa[is.na(aaa)] &lt;- FALSE sum(rle(aaa)$values) </code></pre> <p>Convert <code>NA</code>s to <code>FALSE</code>, and the see how many <code>TRUE</code> values there are in the run length encoding (<code>TRUE</code> is stored as 1, <code>FALSE</code> as zero).</p>
Java printf statement giving errors <p>I'm using Eclipse on an a homework assignment and I'm really struggling. The goal is to write a payroll program that has a user enter their name, hours worked, pay rate, federal and state tax withheld, and then outputs the calculated information of their amounts withheld as well as their net pay. </p> <p>I used what I was familiar with which is <code>println</code> statements to show the output but the teacher wants us to use the <code>System.out.printf</code> function and I can't get it to work at all. If I use <code>println</code> statements all the values fill but for some reason I can't manage to get the <code>printf</code> to do the same. What am I missing? If I use the <code>printf</code> function it gives me the error of </p> <pre><code>"Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method printf(Locale, String, Object[]) in the type PrintStream is not applicable for the arguments (String, String, String) at Payrolls.main(Payrolls.java:31)" </code></pre> <p>Here's my code:</p> <pre><code>import java.util.Scanner; public class Payrolls { public static void main(String []args) { Scanner input = new Scanner(System.in); System.out.print("Enter employee first name: "); String employeeFirst = input.nextLine(); System.out.print("Enter employee last name: "); String employeeLast = input.nextLine(); System.out.print("Enter number of hours worked this week: "); int hoursWorked = input.nextInt(); System.out.print("Enter hourly pay rate of the employee: "); double payRate = input.nextDouble(); System.out.print("Enter federal tax withholding rate: "); double fedTax = input.nextDouble(); System.out.print("Enter state tax withholding rate: "); double stateTax = input.nextDouble(); System.out.println(" "); System.out.println(" "); //System.out.printf("%-20s %s\n", employeeFirst, employeeLast); System.out.println("Name: " + employeeFirst +" " +employeeLast); System.out.println("Hours Worked:" + hoursWorked); System.out.println("Pay Rate:" + payRate); double grossPay; grossPay = payRate * hoursWorked; System.out.println("Gross Pay:" + grossPay); double deductions; deductions = grossPay * fedTax; System.out.println("\tDeductions:"); System.out.println("\t\tFederal Witholding %: $" + deductions); double statTax; statTax = grossPay * stateTax; System.out.println("\t\tState Witholding %: $" + statTax); double totalDeduction; totalDeduction = deductions + statTax; System.out.println("\t\tTotal Deduction: $" + totalDeduction); double netPay; netPay = grossPay - totalDeduction; System.out.println("Net Pay:" + netPay); } } </code></pre>
<ul> <li>Printf methode is available from java version 1.5. Make sure that your jdk version is greater than or equal to 1.5.</li> <li>Your error tells you that the first argument of the printf method must be a Locale type see an exmaple <a href="http://www.tutorialspoint.com/java/io/printstream_printf_locale.htm" rel="nofollow">here</a></li> </ul>
How to prevent JS code from being parsed/evaluated by compiler? <p>I have a module with a lot of JS code in it. Module is created like so:</p> <pre><code>(function (root, factory) { // root === window root.MyModuleName = factory(); })(this, function () { 'use strict'; var MyModuleName = function() { // A lot of code here that I don't want to be parsed or evaluated // until MyModuleName constructor is executed. // // For example: // var a = { d: 123 }; // var b = function() { return 45; }; // this.someMethod = function() { b() + a.d }; // ... }; return MyModuleName; }); </code></pre> <p>All methods &amp; properties are inside <code>MyModuleName</code> closure and (I thought) they should be parsed only after <code>MyModuleName()</code> is executed.</p> <p>After user clicks on some button I create an instance of <code>MyModuleName</code> and execute some method:</p> <pre><code>someButton.onclick = function() { // I want compiler to parse and evaluate JS code only here var myModule = new MyModuleName(); console.log(myModule.someMethod()); }; </code></pre> <p>Even though <code>MyModuleName</code> constructor is executed() only after click, code inside it is evaluated when JS file loads (I can see it in Chrome dev tools timeline).</p> <p>How to make sure compiler evaluates code only after click, not after JS file loads?</p>
<p>You can't. The JS engine has to evaluate the code to create the function before it can assign the function anywhere.</p>
Not Fount :/media/app/images/my_image.png <p>image not found but the image exist at exact location .</p> <pre><code>print(profile.image.url) #/media/app/images/my_image.png </code></pre> <p>prints the image location but when i used in my template , other column are current but image is not found</p> <pre><code>profile = same_table.object.get(pk = 1) </code></pre> <p>setting:</p> <pre><code>MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(MY_BASE_DIR , 'media') </code></pre> <p>my media location has no problem because when i upload image to server it is working fine</p> <p>Template:</p> <pre><code>&lt;img src = "{{profile.image.url}}"&gt; </code></pre> <p>any idea what i messed ?</p> <p>Using Django 1.10 with Python 3.4 in window 10</p>
<p>Add to end of your root urls config <code>urls.py</code> this:</p> <pre><code>from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre>
why is my ArgumentMatcher never called? <p>I try to run the simplest test </p> <p>with mockito argument matcher:</p> <pre><code>import org.mockito.ArgumentMatcher; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.*; @Test public void test123() throws Exception { MyClient cofmanClient = mock(MyClient.class); cofmanClient.holy("zigzag"); MyClient verify = verify(cofmanClient); verify.holy(argThat(new MyMatcher())); } private static class MyClient { public void holy(String s) { System.out.println("Called with: " + s); } } private static class MyMatcher extends ArgumentMatcher&lt;String&gt; { @Override public boolean matches(Object argument) { System.out.println("Deadly cow! s=" + argument.getClass().getName()); return argument.getClass() == Class.class; } } </code></pre> <p>however my matcher is never called.</p> <p>what am i missing?</p>
<p>try this:</p> <pre><code>public boolean matches(String argument) </code></pre>
Where to get a wordpress plugins for online exam with countdown time embedded with it <p>Please have being working a a project where i want to use wordpress platform to make an online test, i was able to install one plugins called WATU but it doesn't has the countdown time features for each test. I just need someone to tell me how to go about this, response would be highly welcome. Thanks.</p>
<p>Please have a look at all the plugins that you can find here:</p> <p><a href="https://wordpress.org/plugins/tags/exam" rel="nofollow">https://wordpress.org/plugins/tags/exam</a></p>
Sequelize validate not working on save() <p>I have a sequelize model with a validation like this:</p> <pre><code>validate: { isEmail: {msg: 'This field must be an E-Mail!'} } </code></pre> <p>It's working when I use <code>.create()</code> method but not working when I use <code>.update()</code>/<code>.save()</code> methods. What did I do something wrong? </p> <p>Thanks in advance.</p>
<p>To validate the instance you can call <code>.validate()</code> on the model instance as well.</p>
How to scale a BigDecimal in Java? <pre><code>import java.math.*; class Moqueet { public static void main(String [] args){ double a, b, c; BigDecimal bg1, bg2; a = 1; b = 10000; c = a / b; bg1 = new BigDecimal(c); MathContext mc = new MathContext(10); bg2 = bg1.round(mc); System.out.println(bg1); } } </code></pre> <p>when I try this I get output as follow:</p> <pre><code>0.000100000000000000004792173602385929598312941379845142364501953125 </code></pre> <p>I want my out put as <code>0.0001</code> only. How can I achive this? </p>
<pre><code> bg1 = bg1.setScale(4, RoundingMode.FLOOR); </code></pre>
Select max time from second table JOIN <pre><code>SELECT q.uid, q.title, q.category_id, CONCAT(CONCAT(q.text,'\n'),a.answer) as description FROM questions q LEFT JOIN ( SELECT question_id, crdate, GROUP_CONCAT(text SEPARATOR '|| ') answer FROM answers GROUP BY question_id ORDER BY crdate DESC ) a ON q.uid = a.question_id WHERE q.deleted = 0 AND q.answers &gt; 0 </code></pre> <p>I want to select uid, title and category id from first table, all text and <strong>MAX</strong> crdate of answers from second table. This query select Min crdate. How I should change it?</p> <p><strong>UPD</strong> I have tables questions and answers. As the names of tables I select questions and answers. One question may has several answers. I want concat all answers in one variable (later concat some variables in one for full-text search) and select crdate of last answer. </p>
<p>Try this</p> <pre><code>SELECT q.uid, q.title, q.category_id, CONCAT(CONCAT(q.text,'\n'),a.answer) as description FROM questions q LEFT JOIN ( SELECT question_id, max(crdate) as crdate, GROUP_CONCAT(text SEPARATOR '|| ') answer FROM answers GROUP BY question_id ORDER BY crdate DESC ) a ON q.uid = a.question_id WHERE q.deleted = 0 AND q.answers &gt; 0 GROUP BY q.uid </code></pre>