input
stringlengths
51
42.3k
output
stringlengths
18
55k
Search from the string array and ignore that exact matched string <p>how can I ignore the exact matched from the string array with linq query</p> <p>here is my code whats wrong with it</p> <pre><code>public string GetItems(string SearchText, Int64 userID, Int64 orgID, Int64 locationID, string[] selectedProductName) { List&lt;Product&gt; searchList = new List&lt;Product&gt;(); string jsonText = ""; try { searchList = dbContext.usp_ang_GetProductList_(orgID, SearchText, locationID, 0).ToList(); var abc = searchList.Where(a =&gt; a.Name.Any(a.Name != selectedProductName).ToList(); jsonText = JsonConvert.SerializeObject(abc); } catch (Exception ex) { } return jsonText; } </code></pre>
<p>Your use of the <code>.Any</code> is incorrect:</p> <ol> <li>In your current use you are checking if <code>any</code> of the <code>char</code>s that construct <code>a.name</code> match some predicate.</li> <li><code>.Any(a.Name != selectedProductName)</code> - you need to form a properly formatted lambda expression</li> </ol> <p>You want to check if <code>any</code> of the values of the <code>selectedProductName</code> array is equals to the <code>a.Name</code>.</p> <pre><code>var abc = searchList.Where(a =&gt; !selectedProductName.Any(name =&gt; name == a.Name)).ToList(); </code></pre> <p>Because <code>selectedProductName</code> is a <code>string[]</code> it is cleaner just to use <code>.Contains</code>:</p> <pre><code>var abc = searchList.Where(a =&gt; !selectedProductName.Contains(a.Name)).ToList(); </code></pre> <hr> <p>Also it is a shame to bring all that data from the database just to filter it the row after. If you remove the <code>ToList()</code> the filtering will happen in the database:</p> <pre><code>var abc = dbContext.usp_ang_GetProductList_(orgID, SearchText, locationID, 0) .Where(a =&gt; !selectedProductName.Contains(a.Name)).ToList(); </code></pre>
how to pass enum values from TCL script to C++ class using Swig <p>I am using following code </p> <p>1) File : example.i </p> <pre><code>%module example %{ /* Put header files here or function declarations like below */ #include "example.h" %} %include "example.h" </code></pre> <p>2) File example.h</p> <pre><code>enum Type {one,two}; class myClass { public: myClass() {} static bool printVal(int val); static bool printEnum(Type val); }; </code></pre> <p>3) File example.cpp</p> <pre><code>#include "example.h" #include &lt;iostream&gt; using namespace std; bool myClass::printVal(int val) { cout &lt;&lt; " Int Val = " &lt;&lt; val &lt;&lt; endl; return 0; } bool myClass::printEnum(type val) { cout &lt;&lt; " Enum Val = " &lt;&lt; val &lt;&lt; endl; return 0; } </code></pre> <p>Steps to compile and run </p> <pre><code>swig -c++ -tcl example.i g++ -c -fpic example_wrap.cxx example.cpp -I/usr/local/include g++ -shared example.o example_wrap.o -o example.so setenv LD_LIBRARY_PATH /pathtoexample.so:$LD_LIBRARY_PATH tclsh % load example.so %myClass_printVal 1 Int Val = 1 %myClass_printEnum one TypeError in method 'myClass_printEnum', argument 1 of type 'type' </code></pre> <p>I am getting TypeError if I pass enum . I know there is typemap for type conversion , but I do not know how to use typemaps to pass enum values from TCL script to c++ class . I am looking forward for help for how to pass enum values from TCL to c++ class objects using SWIG.</p>
<p>According to the <a href="http://www.swig.org/Doc1.3/Tcl.html#Tcl_nn18" rel="nofollow">official documentation</a>:</p> <blockquote> <p>C/C++ constants are installed as global Tcl variables containing the appropriate value.</p> </blockquote> <p>So you must refer to the enum value by dereferencing the corresponding variable:</p> <pre><code>% myClass_printEnum $one </code></pre> <p>Some examples of exposing C/C++ enums in Tcl are a available at <a href="http://doc.gnu-darwin.org/enum/" rel="nofollow">http://doc.gnu-darwin.org/enum/</a></p>
Is it possible to retrieve in output which predicate in where clause is evaluated true? <p>Is it possibile in a select query that has a where clause with a lot of predicates retrieving in output which one predicate is evaluated true, together with real tuple?</p> <p>For instance, given this table:</p> <pre><code>Table person name age hair_color Tom 12 Brown Bob 27 Black Sam 20 Red Ann 15 Blonde John 30 Blonde </code></pre> <p>An that query:</p> <pre><code>select * from person where (age &gt;= 25) or (hair_color = 'Blonde') </code></pre> <p>I would like to have in output something like that:</p> <pre><code>name age hair_color clause_1 clause_2 Bob 27 Black true false Ann 15 Blonde false true John 30 Blonde true true </code></pre> <p>What do you suggest to achieve a similar result?</p> <p><strong>UPDATE</strong></p> <p>Thanks! You answered my question! So It's possible with something like that:</p> <pre><code>select * from ( select p.*, (age &gt;= 25) as clause_1, (hair_color = 'Blonde') as clause_2 from test.person as p ) as t where t.clause_1 or t.clause_2 </code></pre> <p>Now I have a related one. If I already have a table predisposed to contain this clause evaluations, for instance 'check_1' and 'check_2'.</p> <pre><code>Table person name age hair_color check_1 check_2 Tom 12 Brown Bob 27 Black Sam 20 Red Ann 15 Blonde John 30 Blonde </code></pre> <p>Is there any way to 'temporary' valorize this field during the select query (check_1 = clause_1, check_2 = clause_2)?</p> <pre><code>name age hair_color check_1 check_2 Bob 27 Black true false Ann 15 Blonde false true John 30 Blonde true true </code></pre> <p>I ask you because I need it in a Java project in which I use JPA and Criteria API to make typed query, and I would like to get the object 'Person' with 'check' values evaluated in one shot.</p> <p>Thanks again everyone!</p>
<p>You could wrap the condition:</p> <pre><code>select * from ( select p.*, (age &gt;= 25) as condition_1, (hair_color = 'Blonde') as condition_2 from person p ) t where condition_1 or condition_2 </code></pre> <p>The above is standard SQL and assumes the DBMS being used support a proper <code>boolean</code> data type.</p> <p>I am not sure though how smart an optimizer would be to push down the condition so this might be slower then the original query.</p>
getting Readable { .. } instead of specific collection using find() on mongodb <p>I have a collection named 'EloVars' on my mongodb, with only one document:</p> <pre><code>{ "_id": { "$oid": "5800f3bfdcba0f48d2c58161" }, "nextPID": "0", "TotalComprasions": "0" </code></pre> <p>}</p> <p>I'm trying to get the value of nextPID this way:</p> <pre><code>var myDoc = db.collection('EloVars').find(); if(myDoc) { console.log('What exactly am I getting here:') console.log(myDoc) req.body.pid = myDoc.nextPID; } </code></pre> <p>When I look at the console i noticed that what I'm getting is not 'EloVars' collection... just weired long Readable:</p> <pre><code> Readable { pool: null, server: null, disconnectHandler: { s: { storedOps: [], storeOptions: [Object], topology: [Object] }, length: [Getter] }, bson: {}, ns: 'mydb.EloVars', cmd: { find: 'mydb.EloVars', limit: 0, skip: 0, query: {}, slaveOk: true, readPreference: { preference: 'primary', tags: undefined, options: [Object] } }, options: ..... ..... </code></pre> <p>What is this readable and why am I getting it?</p>
<p><code>find()</code> returns a <code>cursor</code>. You have to iterate the cursor to get the documents.</p> <pre><code>var cursor = db.collection('EloVars').find(); cursor.each(function(err, doc) { console.log(doc); }); </code></pre> <p>Or you can convert it to an array to get the documents.</p> <pre><code>cursor.toArray(function(err, doc){ console.log(doc); }); </code></pre>
Angular2 reverse/generate url from Routes (typescript) <p>How can I generate url from route be code? For exemple, I have a login component in my routes:</p> <pre><code>const appRoutes: Routes = [ ... { path: 'login', component: LoginComponent }, ... ]; </code></pre> <p>I want to build a string corresponding to the url of my login component:</p> <pre><code>let url = "I don't know"; console.log(url); ----&gt; 'http:localhost:4200/login' </code></pre>
<p>You can inject <code>Router</code> and <code>UrlSerializer</code></p> <pre><code>constructor(router:Router, urlSerializer:UrlSerializer) { let tree = router.createUrlTree(['/path', param, 'otherPath'], relativeTo: 'xxx', queryParams: {y: z}); let url = urlSerializer.serializeUrl(tree); } </code></pre> <p>To get the static part of the URL you might need to inject <code>Location</code> and use </p> <pre><code>let fullUrl = window.location.origin + location.prepareExternalUrl(url); </code></pre> <p>See also </p> <ul> <li><a href="https://angular.io/docs/ts/latest/api/router/index/Router-class.html" rel="nofollow">https://angular.io/docs/ts/latest/api/router/index/Router-class.html</a></li> <li><a href="https://angular.io/docs/js/latest/api/router/index/UrlSerializer-class.html" rel="nofollow">https://angular.io/docs/js/latest/api/router/index/UrlSerializer-class.html</a></li> <li><a href="https://angular.io/docs/ts/latest/api/common/index/Location-class.html" rel="nofollow">https://angular.io/docs/ts/latest/api/common/index/Location-class.html</a></li> </ul> <p><a href="https://plnkr.co/edit/klWlfI8QzfQ355Od68jd?p=preview" rel="nofollow"><strong>Plunker example</strong></a></p>
Redirect is not working in LogSuccessfulLogin handle in Laravel Auth <p>I am using <code>Laravel 5.3</code> in which using <code>Auth</code>for user controller. So basically i create a <code>Listener</code> for <code>Auth</code> Event</p> <pre><code>'Illuminate\Auth\Events\Login' =&gt; [ 'App\Listeners\LogSuccessfulLogin', ], </code></pre> <p>and in <code>LogSuccessfulLogin</code> <code>handle()</code> function redirecting user on basic of <code>role</code>. but my redirecting function is not working. Its render the default page '\home' route.</p> <p>I am sharing My Files :- </p> <p>EventServiceProvider.php</p> <pre><code>&lt;?php namespace App\Providers; use Illuminate\Support\Facades\Event; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'App\Events\SomeEvent' =&gt; [ 'App\Listeners\EventListener', ], 'Illuminate\Auth\Events\Login' =&gt; [ 'App\Listeners\LogSuccessfulLogin', ], ]; /** * Register any events for your application. * * @return void */ public function boot() { parent::boot(); // } } </code></pre> <p>Route/web.php</p> <pre><code>&lt;?php //Auth::routes(); Route::get('logout', function(){ Auth::logout(); // logout user return Redirect::to('/'); }); #Route::get('/', 'HomeController@index')-&gt;name('homepage'); Route::get('/', function () {return view('welcome');}); Route::group(['middleware' =&gt; ['auth', 'checkrole:Admin'],'namespace' =&gt; 'Admin','prefix' =&gt; 'admin'], function () { Route::get('/123','DashboardController@index')-&gt;name('dashboard'); #Route::get('/','DashboardController@index')-&gt;name('dashboard'); Route::get('user/profile', function () { // Uses Auth Middleware }); }); </code></pre> <p>and here is LogSuccessfulLogin.php</p> <pre><code>&lt;?php namespace App\Listeners; use Illuminate\Auth\Events\Login; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; class LogSuccessfulLogin { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param Login $event * @return void */ public function handle(Login $event) { $user=Auth::User()-&gt;role-&gt;role_name; if($user=="Admin"){ return Redirect::route('dashboard'); #return redirect()-&gt;route('login'); } elseif($user == "Employer" ){ dd("hello"); } } } </code></pre> <p>and this is the default logincontroller of Auth</p> <pre><code>&lt;?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this-&gt;middleware('guest', ['except' =&gt; 'logout']); } } </code></pre> <p>Please let me know if i am doing some wrong. Actually i also tried in <code>LogSuccessfulLogin</code> Listener for redirect the page with <code>return redirect()-&gt;route('login');</code> but its also not working.</p>
<p>As one of possible solutions I would provide a response middleware that will be attached to login route. After getting response you should check if user is logged and if yes - apply your custom redirection login. In that case you will overwrite default Laravel 5.3 logic of redirection. Smth like this:</p> <pre><code>class PostLoginMiddleware { public function handle($request, Closure $next, $guard = null) { // here you've already have response and it's usually redirect $response = $next($request); // if user logged in if (\Auth::id()) { $customRedirectResponse = // ...apply your custom logic return $customRedirectResponse; } return $response; } } </code></pre> <p>You should define this middleware in app/Http/Kernel.php in</p> <pre><code>protected $routeMiddleware = [ 'custom-redirect' =&gt; \YourNamespace\PostLoginMiddleware::class ]; </code></pre> <p>And then apply it on login route</p> <pre><code>/* Authentication Routes */ $this-&gt;get('login', 'Auth\AuthController@showLoginForm'); $this-&gt;post('login', ['middleware' =&gt; 'custom-redirect', 'uses' =&gt; 'Auth\AuthController@login']); $this-&gt;get('logout', 'Auth\AuthController@logout'); </code></pre>
Not able to show Google Map in android version 4.1 whereas map is visible in android higher then version 5 <p>In this i have alse implemented firebase service of google previously i was not using firebase service so that time my compile 'com.google.android.gms:play-services-location:8.3.0' it was working fine in 4.1 and all the other version of android and now becoz of firebase service i m not able to see map in android 4.1 becoz i have to upgraded the version of google play service to 9.4.0</p> <p>build.gradle file</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "app.beeonline.com.attendance" minSdkVersion 11 targetSdkVersion 23 versionCode 1 versionName "1.0" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } dexOptions { javaMaxHeapSize "4g" } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.google.android.gms:play-services-location:9.4.0' compile 'com.android.support:design:23.4.0' compile 'com.google.android.gms:play-services:9.4.0' compile 'com.android.support:support-v4:23.4.0' compile 'com.android.support:multidex:1.0.1' compile 'com.google.firebase:firebase-messaging:9.4.0' compile 'com.mcxiaoke.volley:library-aar:1.0.0' } apply plugin: 'com.google.gms.google-services' </code></pre>
<p>First, remove the line <code>'com.google.android.gms:play-services:9.4.0'</code> because it will add all the Google Play and Firebase libraries to you app. It will also increase the build time and the size of the APK file. So replace it with the library that you only need. Here is the <a href="https://developers.google.com/android/guides/setup" rel="nofollow">link</a> for the Google Play libraries. And this <a href="https://firebase.google.com/docs/android/setup#available_libraries" rel="nofollow">link</a> for the Firebase libraries.</p> <p>Lastly, I don't see the library for Google Maps, it seems that you forgot to include it.</p> <pre><code>com.google.android.gms:play-services-maps:9.4.0 </code></pre> <p>And make sure your classpath is like this when using Firebase, because sometimes it is the problem.</p> <pre><code>buildscript { dependencies { // Add this line classpath 'com.google.gms:google-services:3.0.0' } } </code></pre>
How can I play MIDI tracks created using python-midi package? <p>I want to create MIDI tracks in a Python program and be able to play them instantly (preferably without writing to disk). I have recently discovered the package <a href="https://github.com/vishnubob/python-midi" rel="nofollow">python-midi</a> which looks great. However I haven't figured out how to play the tracks created with this package. Do I need an additional package? Help would be appreciated.</p>
<p>My solution if anyone is interested:</p> <p>I ended up using <a href="https://github.com/olemb/mido" rel="nofollow">mido</a> for my Python MIDI API, with Pygame as the backend. Works like a charm :)</p>
Taking photo with custom camera Swift 3 <p>in Swift 2.3 I used this code to take a picture in custom camera:</p> <pre><code> func didPressTakePhoto(){ if let videoConnection = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo) { stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (sampleBuffer, error) -&gt; Void in if sampleBuffer != nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let dataProvider = CGDataProviderCreateWithCFData(imageData) let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault) let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right) self.captureImageView.image = image } }) } } </code></pre> <p>But his line: <code>stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (sampleBuffer, error) -&gt; Void in</code> </p> <p>Shows this error:</p> <blockquote> <p>Value of type 'AVCapturePhotoOutput' has no member 'captureStillImageAsynchronouslyFromConnection'</p> </blockquote> <p>I tried solving my problem but I always get more and more errors so that is why I post my original code.</p> <p>Does anybody know how to make my code work again?</p> <p>Thank you.</p>
<p>You can use <code>AVCapturePhotoOutput</code>like this in Swift 3:</p> <p>You need the <code>AVCapturePhotoCaptureDelegate</code> which returns the <code>CMSampleBuffer</code>.</p> <p>You can get as well a preview image if you tell the <code>AVCapturePhotoSettings</code> the previewFormat</p> <pre><code>class CameraCaptureOutput: NSObject, AVCapturePhotoCaptureDelegate { let cameraOutput = AVCapturePhotoOutput() func capturePhoto() { let settings = AVCapturePhotoSettings() let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first! let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType, kCVPixelBufferWidthKey as String: 160, kCVPixelBufferHeightKey as String: 160, ] settings.previewPhotoFormat = previewFormat self.cameraOutput.capturePhoto(with: settings, delegate: self) } func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: NSError?) { if let error = error { print(error.localizedDescription) } if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) { print(image: UIImage(data: dataImage).size) } else { } } } </code></pre>
angularjs firebase user auth service not communicating with the views <p>I have a service which passes on the parameter <code>pseudonym</code> to the evironment. I call on this <code>pseudonym</code> in my views, but it doesn't appear at all.<br /> How can I fix this to display the value in my views?<br /></p> <p><strong>MyUser service</strong>:<br /></p> <pre><code>app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) { var pseudonym =""; var userId = firebase.auth().currentUser.uid; return { pseudonym: function() { DatabaseRef.ref('/users/' + userId).once('value') .then(function (snapshot) { pseudonym = snapshot.val().pseudonym; console.log("pseudony: ", pseudonym); return pseudonym; }); } } }]); </code></pre> <p><strong><em>in my console, I see the value for the <code>pseudonym</code>. but not in my view html using {{pseudonym}}</em></strong><br /> and here is the example view controller:<br /></p> <pre><code>app.controller('ExampleCtrl', ["MyUser", function (MyUser) { $scope.pseudonym = MyUser.pseudonym(); }]); </code></pre>
<p>Return the promise created by the <code>.then</code> method:</p> <pre><code>app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) { //var pseudonym =""; var userId = firebase.auth().currentUser.uid; return { getUserName: function() { //return promise return ( DatabaseRef.ref('/users/' + userId).once('value') .then(function onSuccess(snapshot) { let pseudonym = snapshot.val().pseudonym; console.log("pseudony: ", pseudonym); return pseudonym; }) ); } } }]); </code></pre> <p>Then extract the value from that promise:</p> <pre><code>var app = angular.module('app', []); app.controller('loginController',['$scope', 'MyUser',function($scope, MyUser) { let promise = MyUser.getUserName(); //Extract data from promise promise.then( function onSuccess(pseudonym) { $scope.pseudonym = pseudonym; console.log($scope.pseudonym); }); }]); </code></pre> <p>The <code>.then</code> method of an object always returns a promise derived from the value (or promise) returned by the handler function furnished as an argument to that <code>.then</code> method.</p>
Displaying normalized data in the react UI component <p>Let' say we have normalized object like this one in redux store.</p> <pre><code>{ entities: { plans: { 1: {title: 'A', exercises: [1, 2, 3]}, 2: {title: 'B', exercises: [5, 6]} }, exercises: { 1: {title: 'exe1'}, 2: {title: 'exe2'}, 3: {title: 'exe3'} 5: {title: 'exe5'} 6: {title: 'exe6'} } }, currentPlans: [1, 2] } </code></pre> <p>I want to display for each plan exercise details in the UI component. Something like.</p> <pre><code>plan 1 title A exercises exercise 1 title: 'exe1' exercise 2 title: 'exe2' .......... plan 2 title B exercises exercise 5 title: 'exe5' ........ </code></pre> <p>Do I have to denormalize again ? How do I transform data and where ? Do I use connectStateToProps to do something like</p> <pre><code> plans: some mapping function that will create nested plans-&gt;exercise array </code></pre> <p>or is there another way ?</p>
<p>Yup, you have to denormalize before displaying. For example if you have list of active users stored as denormalized list of user ids, you have to map through those and for each fetch respective object from the state tree. </p> <p>Yes, probably do this in mapStateToProps. </p> <p>Sort-of recommended approach is to use a function of (state) => data that will read whatever is needed from state and form a final structure that will be provided to your component.</p> <p>It's common to use <a href="https://github.com/reactjs/reselect" rel="nofollow">https://github.com/reactjs/reselect</a> for this purpose as it will also memoize output of your selectors for better performance. Note that just like most things in redux, it isn't magic, and you can absolutely go without it. Especially if you're just toying with the framework for now.</p>
How to escape double quotes and colon in ACK in powershell <p>I am using Ack version 2.04, in powershell. I want to search texts like <strong>"jsonClass":"Page"</strong> (quotes included) inside text files.</p> <p>I cant seem to get the quoting and escaping correctly.</p> <pre><code>ack -c --match '"jsonClass":"Page"' </code></pre> <p>Doesn't work in powershell, I guess ack's picking up the single quotes as well. Escaping the double quotes gives invalid regex error.</p> <pre><code>ack -c --match "\"jsonClass\":\"Page\"" Invalid regex '\': Trailing \ in regex m/\/ at C:\CHOCOL~1\lib\ACK2~1.04\content\ack.pl line 315 </code></pre> <p>I tried the literal option as well, but I think ack's interpreting the colon as file params.</p> <pre><code>ack -c -Q --match "jsonClass":"Page" ack.pl: :Page: No such file or directory </code></pre> <p>Any idea what i am missing ?</p> <p><strong>EDIT</strong>: I am using powershell v2</p>
<p>To complement <a href="http://stackoverflow.com/a/40058586/45375">JPBlanc's effective answer</a> with a <strong>PowerShell v3+</strong> solution:</p> <p>When <strong>invoking external programs</strong> such as <code>ack</code> , use of the so-called <strong>stop-parsing symbol, <code>--%</code></strong>, makes PowerShell <strong>pass the remaining arguments through <em>as-is</em></strong>, with the <em>exception</em> of expanding <code>cmd.exe</code>-style environment-variable references such as <code>%PATH%</code>:</p> <pre><code>ack --% -c --match "\"jsonClass\":\"Page\"" </code></pre> <p>This <strong>allows you to focus on the escaping rules of the target program only</strong>, without worrying about the complex interplay with PowerShell's own parsing and escaping.</p> <p>Thus, in PowerShell v3 or higher, the OP's own 2nd solution attempt would have worked by passing <code>--%</code> as the first parameter.</p> <p>See <a href="https://technet.microsoft.com/en-us/library/hh847892.aspx" rel="nofollow"><code>Get-Help about_Parsing</code></a>.</p> <hr> <p>Note that the <em>exact</em> equivalent of the above command without the use of <code>--%</code> (that also works in <strong>PSv2</strong> and is generally helpful <strong>if you want to include PowerShell-expanded variables / expressions in other arguments</strong>) would look like this:</p> <pre><code>ack -c --match '"\"jsonClass\":\"Page\""' </code></pre> <p>That is, the <strong>entire argument to be passed as-is is enclosed in <em>single</em> quotes</strong>, which ensures that PowerShell doesn't interpret it.</p> <p><sup>Note the inner enclosing <code>"</code> that aren't present in JPBlanc's answer (as of this writing). They guarantee that the argument is ultimately seen as a <em>single</em> argument by <code>ack</code>, even if it contains whitespace.</sup></p>
Call a Method From Inside dom-repeat in Polymer <p>I'm having this situation where I need to call a method from the dom-repeat. Below is my code</p> <pre><code>&lt;template is='dom-repeat' items="[[_dataArray]]" as="rowItem"&gt; &lt;template is='dom-repeat' items="[[_objectArray]]" as="columnItem"&gt; &lt;template&gt; &lt;span&gt;[[_getColumnItemValue(rowItem, columnItem)]]&lt;/span&gt; &lt;/template&gt; &lt;/template&gt; &lt;/template&gt; </code></pre> <p>and in my <code>_getColumnItemValue</code> method, I want to get the value for an object with key specified by the <code>columnData</code> attribute.</p> <p>Like <code>rowData[columnData]</code></p> <pre><code>_getColumnItemValue: function(rowData, columnData) { return rowData[columnData]; } </code></pre> <p>My problem is the method <code>_getColumnItemValue</code> is not being called. Is there any better way to do achieve this?</p>
<p>If your code is exactly as you pasted, then you have one too many <code>&lt;template&gt;</code> tags.</p> <pre><code>&lt;template is='dom-repeat'&gt; &lt;template is='dom-repeat'&gt; &lt;span&gt;&lt;/span&gt; &lt;/template&gt; &lt;/template&gt; </code></pre> <p>The innermost template must be removed. You are rendering that instead of the <code>&lt;span&gt;</code>.</p>
Scala: Write log to file with log4j <p>I am trying to build a scala based jar file in eclipse that uses log4j to make logs. It prints out perfectly in the console but when I try to use log4j.properties file to make it write to a log file, nothing happens.</p> <p>The project structure is as follows</p> <p><a href="https://i.stack.imgur.com/XbujQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/XbujQ.png" alt="Maven project with scala nature"></a></p> <p>loggerTest.scala</p> <pre><code>package scala.n*****.n**** import org.apache.log4j.Logger object loggerTest extends LogHelper { def main(args : Array[String]){ log.info("This is info"); log.error("This is error"); log.warn("This is warn"); } } trait LogHelper { lazy val log = Logger.getLogger(this.getClass.getName) } </code></pre> <p>log4j.properties</p> <pre><code># Root logger option log4j.rootLogger=WARN, stdout, file # Redirect log messages to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Redirect log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=/home/abc/test/abc.log log4j.appender.file.encoding=UTF-8 log4j.appender.file.MaxFileSize=2kB log4j.appender.file.MaxBackupIndex=1 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n </code></pre> <p>pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;loggerTest&lt;/groupId&gt; &lt;artifactId&gt;loggerTest&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;loggerTest&lt;/name&gt; &lt;description&gt;loggerTest&lt;/description&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;scala-tools.org&lt;/id&gt; &lt;name&gt;Scala-tools Maven2 Repository&lt;/name&gt; &lt;url&gt;http://scala-tools.org/repo-releases&lt;/url&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;maven-hadoop&lt;/id&gt; &lt;name&gt;Hadoop Releases&lt;/name&gt; &lt;url&gt;https://repository.cloudera.com/content/repositories/releases/&lt;/url&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;cloudera-repos&lt;/id&gt; &lt;name&gt;Cloudera Repos&lt;/name&gt; &lt;url&gt;https://repository.cloudera.com/artifactory/cloudera-repos/&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;pluginRepositories&gt; &lt;pluginRepository&gt; &lt;id&gt;scala-tools.org&lt;/id&gt; &lt;name&gt;Scala-tools Maven2 Repository&lt;/name&gt; &lt;url&gt;http://scala-tools.org/repo-releases&lt;/url&gt; &lt;/pluginRepository&gt; &lt;/pluginRepositories&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;/properties&gt; &lt;build&gt; &lt;plugins&gt; &lt;!-- mixed scala/java compile --&gt; &lt;plugin&gt; &lt;groupId&gt;org.scala-tools&lt;/groupId&gt; &lt;artifactId&gt;maven-scala-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;compile&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;/goals&gt; &lt;phase&gt;compile&lt;/phase&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;test-compile&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;testCompile&lt;/goal&gt; &lt;/goals&gt; &lt;phase&gt;test-compile&lt;/phase&gt; &lt;/execution&gt; &lt;execution&gt; &lt;phase&gt;process-resources&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;fully.qualified.MainClass&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. --&gt; &lt;plugin&gt; &lt;groupId&gt;org.eclipse.m2e&lt;/groupId&gt; &lt;artifactId&gt;lifecycle-mapping&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;configuration&gt; &lt;lifecycleMappingMetadata&gt; &lt;pluginExecutions&gt; &lt;pluginExecution&gt; &lt;pluginExecutionFilter&gt; &lt;groupId&gt;org.scala-tools&lt;/groupId&gt; &lt;artifactId&gt; maven-scala-plugin &lt;/artifactId&gt; &lt;versionRange&gt; [2.15.2,) &lt;/versionRange&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;goal&gt;testCompile&lt;/goal&gt; &lt;/goals&gt; &lt;/pluginExecutionFilter&gt; &lt;action&gt; &lt;execute&gt;&lt;/execute&gt; &lt;/action&gt; &lt;/pluginExecution&gt; &lt;/pluginExecutions&gt; &lt;/lifecycleMappingMetadata&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-core_2.10&lt;/artifactId&gt; &lt;version&gt;1.5.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-hive_2.10&lt;/artifactId&gt; &lt;version&gt;1.5.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-sql_2.10&lt;/artifactId&gt; &lt;version&gt;1.5.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.scala-lang&lt;/groupId&gt; &lt;artifactId&gt;scala-library&lt;/artifactId&gt; &lt;version&gt;2.10.4&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p>When I run it as a maven build, it generates a jar file in "target" folder.</p> <p>I copy the jar to /home/abc/test</p> <p>I run that jar in spark shell with command</p> <pre><code> $ spark-submit --class scala.n*****.n*****.loggerTest loggerTest-0.0.1-SNAPSHOT.jar </code></pre> <p>The console come out alright but it should write to a file in /home/abc/log which it does not.</p> <p>Could someone please help?</p>
<p>Hello while you are deploying you application you should define log4j file for executor and driver as follows</p> <pre><code>spark-submit --class MAIN_CLASS --driver-java-options "-Dlog4j.configuration=file:PATH_OF_LOG4J" --conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:PATH_OF_LOG4J" --master MASTER_IP:PORT JAR_PATH </code></pre> <p>For more details and step by step solution you can check this link <a href="https://blog.knoldus.com/2016/02/23/logging-spark-application-on-standalone-cluster/" rel="nofollow">https://blog.knoldus.com/2016/02/23/logging-spark-application-on-standalone-cluster/</a></p>
How do I pass an array of line specifications or styles to plot? <p>I want to plot multiple lines with one call to <code>plot()</code>, with different line styles for each line. Here's an example:</p> <p>Both</p> <pre><code>plot([1,2,3]', [4,5;6,7;8,9], {'-o', '-x'}) </code></pre> <p>and</p> <pre><code>hs = plot([1,2,3]', [4,5;6,7;8,9]) set(hs, 'LineStyle', {'--'; '-'}) </code></pre> <p>don't work. I've tried a whole bunch of arcane combinations with square and curly braces, but nothing seems to do the trick.</p> <p>I know it's possible to loop through the columns in Y and call <code>plot()</code> for each one (like in <a href="http://stackoverflow.com/questions/5210514/how-to-plot-multiple-lines-with-different-markers">this question</a>), but that isn't what I'm after. I would really like to avoid using a loop here if possible.</p> <p>Thanks.</p> <p>PS: I found this <a href="https://www.cs.ubc.ca/~schmidtm/Software/prettyPlot.html" rel="nofollow">'prettyPlot'</a> script which says it can do something like this, but I want to know if there's any built-in way of doing this.</p> <p>PPS: For anyone who wants a quick solution to this, try this:</p> <pre><code>for i = 1:length(hs) set(hs(i), 'Marker', markers{i}); set(hs(i), 'LineStyle', linestyles{i}); end </code></pre> <p>e.g. with <code>markers = {'+','o','*','.','x','s','d','^','v','&gt;','&lt;','p','h'}</code></p>
<p>Referring to <a href="http://www.mathworks.com/help/matlab/ref/plot.html" rel="nofollow">http://www.mathworks.com/help/matlab/ref/plot.html</a>, this is how to draw multiple lines with a single plot command:</p> <pre><code>plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn) </code></pre> <p>So your idea of </p> <pre><code>plot([1,2,3]', [4,5;6,7;8,9], {'-o', '-x'}) </code></pre> <p>must be written as:</p> <pre><code>plot([1,2,3]', [4,6,8], '-o', [1,2,3]',[5,7,9],'-x') </code></pre> <p>resulting: </p> <p><a href="https://i.stack.imgur.com/iOEfA.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/iOEfA.jpg" alt="Multiple lines with single plot command"></a></p> <p>Reorganize input parameters into cell arrays and use cellfun to apply plot command to each cell element. </p> <pre><code>x = [1,2,3]'; xdata = {x;x}; ydata = {[4,6,8];[5,7,9]}; lspec = {'-o';'-x'}; hold all; cellfun(@plot,xdata,ydata,lspec); </code></pre>
Distance formula in SQL <pre><code>SQL&gt; SELECT sighting_id, distance FROM sightings WHERE distance = SQRT(POWER(latitude -(-28),2) + POWER(longitude -(151),2)) GROUP BY sighting_id, distance; </code></pre> <p>Receiving the error PLS-306: wrong number or types of arguments in call to 'OGC_DISTANCE'. Any ideas?</p> <pre><code> Name Null? Type -------------- -------- -------------------------------- SIGHTING_ID NOT NULL NUMBER SPOTTER_ID NUMBER BIRD_ID NUMBER LATITUDE NUMBER LONGITUDE NUMBER SIGHTING_DATE DATE DESCRIPTION VARCHAR2(255) </code></pre>
<p>try using some other name for 'distance' column, looks like it is some internal GEO function or synonym already defined in your Oracle DB. Please also check if all latitude and longitude values in the table are valid numbers, not null etc. </p> <p>You may need to add some coalesce() wrapper for null latitude and longitude occurrences or add the "AND latitude IS NOT NULL AND longitude IS NOT NULL" into WHERE clause.</p>
Downloading an Excel file with plots and dataframes from shiny. (Not working for plots) <p>Hello fellow shiny users. </p> <p>I am running across a problem I can't seem to find any solution to on the various forums and websites. I will share a relatively simple reproducible example that illustrates my problem. </p> <p>I want to do the following: Upload some data, do some processing and analysis, then put the whole bunch of outputs into an Excel file and finally download it. I have no trouble creating that Excel in the shiny server part, and putting dataframes/tables into it. But I can't put images in the Excel file.</p> <p>It is because the AddPicture function from the xlsx package I use requires the following things:</p> <hr> <p>addPicture(file, sheet, scale=1, startRow=1, startColumn=1)</p> <p>file<br> the absolute path to the image file.</p> <p>sheet<br> a worksheet object as returned by createSheet or by subsetting getSheets. The picture will be added on this sheet at position startRow, startColumn.</p> <p>"The absolute path to the image file" is the problem. I can't have an absolute path to the file, as when I execute a similar script with R. Or can I?</p> <hr> <p>Here is some code that shows the error:</p> <p>If you execute it as it stands, you will be able to download an Excel file with a dataframe in the first sheet no problem. (Because there is no absolute path needed, just a dataframe object) The part with # in the server part is what bring me problems. You can uncomment it to see the error (Error : no applicable method for 'grid.draw' applied to an object of class "NULL" ) . Does anyone have an idea on how to solve this? </p> <p>SERVER</p> <pre><code>library(shiny) library(xlsx) library(ggplot2) server &lt;- function(input, output) { output$download.Excel &lt;- downloadHandler( filename = function() { paste("Excelfile.xlsx")}, content = function(file){ example_plot=plot(1:10,1:10) Results_Workbook &lt;- createWorkbook(type='xlsx') A=as.data.frame(matrix(2,2,2)) sheet.1 &lt;- createSheet(Results_Workbook, sheetName = "Data frame") addDataFrame(A, sheet=sheet.1, startRow=4, startColumn=2,row.names=FALSE) setColumnWidth(sheet.1,colIndex=c(1:100),colWidth=30) sheet.2 &lt;- createSheet(Results_Workbook, sheetName = "Plot") # ggsave("plot",example_plot, device="emf") # addImage(file = "plot.emf", sheet = sheet.2, scale = 55, # startRow = 4, startColumn = 4) saveWorkbook(Results_Workbook,file) } ) } </code></pre> <p>UI</p> <pre><code>library(shiny) ui &lt;- fluidPage( titlePanel("Simple classification script with R/Shiny"), sidebarLayout( sidebarPanel( downloadButton('download.Excel', 'Download') ), mainPanel(p("Description of the results") ) ) ) </code></pre> <p>Best regards,</p> <p>Joël</p>
<p>Here is a working <code>server.R</code> file. Note that I couldn't get the emf file format to work, but jpeg works.</p> <pre><code>library(shiny) library(xlsx) library(ggplot2) server &lt;- function(input, output) { output$download.Excel &lt;- downloadHandler( filename = function() { paste("Excelfile.xlsx")}, content = function(file){ example_plot=qplot(1:10,1:10) Results_Workbook &lt;- createWorkbook(type='xlsx') A=as.data.frame(matrix(2,2,2)) sheet.1 &lt;- createSheet(Results_Workbook, sheetName = "Data frame") addDataFrame(A, sheet=sheet.1, startRow=4, startColumn=2,row.names=FALSE) setColumnWidth(sheet.1,colIndex=c(1:100),colWidth=30) sheet.2 &lt;- createSheet(Results_Workbook, sheetName = "Plot") ggsave("plot.jpeg",example_plot, device="jpeg") addPicture(file = paste0(getwd(), "/plot.jpeg"), sheet = sheet.2, scale = 1,startRow = 4, startColumn = 4) saveWorkbook(Results_Workbook,file) } ) } </code></pre>
AS3 error 1119: Access of undefined property CHANGE through a reference with static type flash.events:MouseEvent <p>This might be a bug in AS3 because the event its listing in the error is not associated with a mouseEvent, but I'd really like to get to the bottom of this. I've been working on this project and have a movieclip for a search feature with 3 combos and 2 input text fields inside. When user enters text into text field I want to disable the combos, set the selected index to -1. If user clears the text fields I want the combos enabled. CS4 is throwing the above error. It's so weird or is it me?</p> <p>My code:</p> <pre><code>fltr.btn.addEventListener(MouseEvent.CLICK, shwSrch); function shwSrch(Event:MouseEvent):void{ popcmb1(); //function to populate combo 1 srch.canNow.button.addEventListener(MouseEvent.CLICK, cans); srch.srchNow.button.addEventListener(MouseEvent.CLICK, gos); srch.npt1.it.addEventListener(Event.CHANGE, txtchng); srch.npt1.it.dispatchEvent(new Event(Event.CHANGE)); } function txtchng(event:Event):void{ if (srch.npt1.it.length &gt;0){ //DISABLE COMBO AND NPT2 srch.cmb1.cmb.enabled = false; srch.cmb1.cmb.selectedIndex = -1; srch.cmb1.cmb.prompt = "All"; cmb1si = gSrch.cmb1.cmb.selectedIndex; } else{ srch.cmb1.cmb.enabled = true; srch.npt1.it.selectable = true; srch.npt1.it.type = TextFieldType.INPUT; srch.npt1.it.borderColor = 0x000000; } npt1 = srch.npt1.text; } </code></pre> <p>So, When I run this newly added code it throws error 1046: Type was not found or was not a compile-time constant: Event. I have already the line 'import flash.events.Event;' I've experimented quite a bit and noted that if I create a separate function for listeners and then call it from with the shwSrch function thus:</p> <pre><code>function lstnrs():void{ srch.npt1.it.addEventListener(Event.CHANGE, txtchng); srch.npt1.it.dispatchEvent(new Event(Event.CHANGE)); } </code></pre> <p>It works... Is there anyone that can shine some light on this?</p>
<p>The problem is how you are naming your variables.</p> <pre><code>function shwSrch(Event:MouseEvent):void </code></pre> <p>Here you use <code>Event</code> as the parameter name which is a bad choice, because it's the same name the <code>Event</code> class has. Later, you add a listener.</p> <pre><code>srch.npt1.it.addEventListener(Event.CHANGE, txtchng); </code></pre> <p>Now it's unclear if you are referring to the class or the parameter variable name. For the latter, you receive the error.</p> <p>To solve the problem, use the convention to start variable names with a lower case letter and class names with capital ones.</p> <pre><code>function shwSrch(mouseEvent:MouseEvent):void </code></pre> <p>Side note: do you really need to display the event after adding the listener for it like here for example?</p> <pre><code> srch.npt1.it.addEventListener(Event.CHANGE, txtchng); srch.npt1.it.dispatchEvent(new Event(Event.CHANGE)); </code></pre> <p>If you do not use the parameter in the handler function, you could simply do</p> <pre><code> srch.npt1.it.addEventListener(Event.CHANGE, txtchng); txtchng(null); </code></pre>
How to get DUID <p>How to get a DUID for Tizen tablet. Connection Explorer - Device - Properties didn't get such information:</p> <p><a href="https://i.stack.imgur.com/vUm69.png" rel="nofollow"><img src="https://i.stack.imgur.com/vUm69.png" alt="enter image description here"></a></p>
<p>As I know DUID is not standard specification of Tizen.</p> <p>It is served only Gear devices.</p> <p>You can get it with following command.</p> <pre><code>sdb shell /opt/etc/duid-gadget </code></pre> <p><code>/opt/etc/duid-gadget</code> is not in specification of Tizen. so it can be changed in any time. (But currently it works in Gear S, S2)</p>
Find netMask on Android device <p>I have to find information about the network to which the Android device is connected. Basically the Android device is a Android TV and it has WiFi and Ethernet connectivity.<br> I am working with WiFi and getting all the correct information except <code>netMask</code> as it is always showing <b>0</b> (zero), whereas it should show <b>255.255.255.0</b></p> <p>Following is the code that I'm using:</p> <pre><code>wifiMgr= (WifiManager) getSystemService(Context.WIFI_SERVICE); dhcpInfo=wifiMgr.getDhcpInfo(); vDns1="DNS 1: "+intToIp(dhcpInfo.dns1); vDns2="DNS 2: "+intToIp(dhcpInfo.dns2); vGateway="Default Gateway: "+intToIp(dhcpInfo.gateway); vIpAddress="IP Address: "+intToIp(dhcpInfo.ipAddress); vLeaseDuration="Lease Time: "+String.valueOf(dhcpInfo.leaseDuration); vNetmask="Subnet Mask: "+intToIp(dhcpInfo.netmask); vServerAddress="Server IP: "+intToIp(dhcpInfo.serverAddress); </code></pre> <p>Definition for <code>intToIp(int)</code>:</p> <pre><code>public String intToIp(int i) { return ((i &gt;&gt; 24 ) &amp; 0xFF ) + "." + ((i &gt;&gt; 16 ) &amp; 0xFF) + "." + ((i &gt;&gt; 8 ) &amp; 0xFF) + "." + ( i &amp; 0xFF) ; } </code></pre> <p>The <code>AndroidManifest.xml</code>:</p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/&gt; &lt;uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /&gt; </code></pre> <p>Why is this happening and how can I fix it?</p>
<p>It's <a href="https://code.google.com/p/android/issues/detail?id=82477" rel="nofollow">an android bug</a>.</p> <p>According to the bug report, you can either use the following workaround (copied from the report):</p> <pre><code>WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); try { InetAddress inetAddress = InetAddress.getByAddress(extractBytes(dhcpInfo.ipAddress)); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress); for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { //short netPrefix = address.getNetworkPrefixLength(); Log.d(TAG, address.toString()); } } catch (IOException e) { Log.e(TAG, e.getMessage()); } </code></pre> <p>... or stop using this API altogether and use the <a href="https://developer.android.com/reference/android/net/ConnectivityManager.html#getLinkProperties(android.net.Network)" rel="nofollow">LinkProperties</a> API instead.</p>
create file containing '/' in file name in python <p>how can I create a file in python if the filename contains '/'</p> <pre><code>url='https://www.udacity.com/cs101x/index.html' f=open(url,'w') f.write('123') f.close() </code></pre> <p>above code produces an error as</p> <pre><code>Traceback (most recent call last): File "9.py", line 2, in &lt;module&gt; f=open(url,'w') IOError: [Errno 22] invalid mode ('w') or filename:https://www.udacity.com/cs101x/index.html' </code></pre>
<p>Use os.path.basename() to isolate the filename.</p> <pre><code>import os url='https://www.udacity.com/cs101x/index.html' filename = os.path.basename(url) f=open(filename,'w') f.write('123') f.close() </code></pre> <p>This will create a file called index.html</p>
SQL group by coalesce not working as expected <p>I have following MySQL table (<code>images</code>):</p> <pre><code>+----+------------+-----------------------+ | id | gallery_id | path | +----+------------+-----------------------+ | 58 | NULL | 58.jpg | 59 | NULL | 59.jpg | 66 | 9 | 9-001.jpg | 67 | 9 | 9-002.jpg | 68 | 10 | 10-001.jpg | 69 | 10 | 10-002.jpg ... </code></pre> <p>I want to select rows where gallery_id is null or group it by gallery_id if it not null. So expected result is:</p> <pre><code>+----+------------+-----------------------+ | id | gallery_id | path | +----+------------+-----------------------+ | 58 | NULL | 58.jpg | 59 | NULL | 59.jpg | 66 | 9 | 9-001.jpg | 68 | 10 | 10-001.jpg ... </code></pre> <p>I tried to use <code>coalesce</code> function to achieve this result: </p> <pre><code>select * from `images` group by coalesce(gallery_id, id); </code></pre> <p>But it returns only rows where <code>gallery_id</code> is null. Tell me please what am I doing wrong? Thanks in advance.</p>
<p>You could use a when in with subselect and group by</p> <pre><code>select * from `images` where (gallery_id, id ) in (select gallery_id, min(id) from `images` where gallery_id is not null group by gallery_id) </code></pre>
Auto-open perspective <p>I'm developing an eclipse plugin in which I included a custom perspective.<br> I'd like to get a similar behaviour to the Java perspective. That is that when creating a Java project eclipse will ask you whether you want to open the respective perspective for this... </p> <p>I found out that I can set a <code>finalPerspective</code> as well as <code>preferredPerspectives</code> for a wizard but nothing happens if I specify my perspective there. </p> <p>So what do I have to do in order to get the desired behaviour?</p>
<p>Your New Project wizard should call </p> <pre><code>BasicNewProjectResourceWizard.updatePerspective(configElement); </code></pre> <p>in your <code>performFinish</code> when the project has been created.</p> <p><code>configElement</code> is the <code>IConfigurationElement</code> for your new wizard. You get this by making your wizard implement <code>IExecutableExtension</code> which adds the method:</p> <pre><code>public void setInitializationData(IConfigurationElement config, String propertyName, Object data) </code></pre> <p>which gives you the configuration element.</p>
PostgreSQL: stored proc to return a fake row from several ones with a condition <p>consider the following table:</p> <pre><code>Value1 Value2 Value3 1 1 0.9 1 2 0.8 1 3 0.1 2 1 0.1 2 2 0.15 </code></pre> <p>I need to return only rows those match the following conditions: Considering grouping by Value1:</p> <ol> <li>From each group return all rows with Value3 >= 0.8.</li> <li>If all rows in a group have their Value3 &lt;= 0.2, then return only one fake row with Value2 = 0 and Value3 = max(Values3 in the group).</li> </ol> <p>For the table mentioned the result would be:</p> <pre><code>Value1 Value2 Value3 1 1 0.9 1 2 0.8 2 0 0.15 </code></pre> <p>How is such logic implemented in PostgreSQL (e.g. with a stored procedure)?</p> <p>Thanks in advance.</p>
<p>Use <code>union</code>:</p> <pre><code>select * from a_table where value3 &gt;= 0.8 union all select value1, 0, max(value3) from a_table group by value1 having max(value3) &lt;= 0.2; </code></pre> <p>It is easy to create an sql function based on the query, e.g.:</p> <pre><code>create or replace function select_from_a_table(limit1 numeric, limit2 numeric) returns setof a_table language sql as $$ select * from a_table where value3 &gt;= limit1 union all select value1, 0, max(value3) from a_table group by value1 having max(value3) &lt;= limit2; $$; select * from select_from_a_table(0.8, 0.2); value1 | value2 | value3 --------+--------+-------- 1 | 1 | 0.9 1 | 2 | 0.8 2 | 0 | 0.15 (3 rows) </code></pre>
EventKitUI/EKCalendarChooser needs access to contacts - why? <p>I have an existing app since 2010, and with iOS 10 it is now required that the app is having strings in the <code>Info.plist</code> describing the usage, as explained here: <a href="http://useyourloaf.com/blog/privacy-settings-in-ios-10/" rel="nofollow">http://useyourloaf.com/blog/privacy-settings-in-ios-10/</a></p> <p>However, I already added the corresponding key in my Info.plist. Still, users report app crashes when the app tries to access calendars. One of the users now managed to send me a crash report, which looks like this:</p> <pre><code>Termination Reason: TCC, This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data. Triggered by Thread: 2 Filtered syslog: None found Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0: 0 libsystem_kernel.dylib 0x00000001812501a8 0x18124f000 + 4520 1 libdispatch.dylib 0x000000018113b7ec 0x181128000 + 79852 2 Contacts 0x000000018aa2c63c 0x18a9c8000 + 411196 3 Contacts 0x000000018a9f7c40 0x18a9c8000 + 195648 4 Contacts 0x000000018aa08578 0x18a9c8000 + 263544 5 EventKitUI 0x000000018f18b5a4 0x18f169000 + 140708 6 EventKitUI 0x000000018f2a9628 0x18f169000 + 1312296 7 EventKitUI 0x000000018f2aa3a8 0x18f169000 + 1315752 8 UIKit 0x000000018843b1b4 0x1880e8000 + 3486132 </code></pre> <p>Now the question is, why is my app needing access to <em>contacts</em>, but my app only wants to read/write calendars? </p> <p>In the crashing code I am opening a <code>EKCalendarChooser</code>, and previously I asked the user for permission using <code>eventStore requestAccessToEntityType:EKEntityTypeEvent completion:(...)</code></p> <p>In my Info.plist I have:<br> <code>&lt;key&gt;NSCalendarsUsageDescription&lt;/key&gt;</code><br> <code>&lt;string&gt;Storing of leave data&lt;/string&gt;</code></p> <p>So how do I fix this? Must I add <code>NSContactsUsageDescription</code> as indicated by the crash report? Why? And will it lead to a popup prompt for contacts access, which would most users probably consider as a bad thing?</p> <p>Note: the weirdest thing is, that on none of my devices this crash can be reproduced, I only have a couple of users reporting this kind of crash.</p>
<p>I've just had the same problem and believe it is because the EKCalendarChooser can show which of your Contacts is sharing a calendar. I just turned off all sharing including removing family members from iCloud Family and it no longer requires access to Contacts. I then tried to share a calendar with a contact using the EKCalendarChooser and it prompted for permission after I had chosen the contact.</p> <p>It is a bit of a pain, but the solution is to probably go ahead and add a usage description that tells the user permission is required to show / modify calendar sharing details. Another (and more painful) alternative would be to create your own view for choosing calendars.</p> <p>I'm not sure if this is intentional by Apple or a bug as I don't know if there is any way for developers to gain access to the contact information from the EKCalendarChooser view anyway.</p>
What is axis in Python with Numpy module? <p>when I use np.stack, sometimes have to use axis, like axis=1. I don't understand what the axis means for it. for exmaple,</p> <pre><code>c1 = np.ones((2, 3)) c2 = np.zeros((2, 3)) c = np.stack([c1, c2], axis = 1) </code></pre> <p>this shows like,</p> <pre><code>array([[[1., 1., 1.], [0., 0., 0.]], [[1., 1., 1.], [0., 0., 0.]]]) </code></pre> <p>what rules make the result?</p>
<p>Axis means the dimension . For a simple example consider <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.sum.html" rel="nofollow">numpy.sum</a> </p> <pre><code>import numpy as np a=np.array([1,2,3],[2,3,1]) sum1=np.sum(a,axis=0) sum2=np.sum(a,axis=1) print sum1,sum2 </code></pre> <p>This will give me sum1=12 and sum2=[3,5,4]</p> <p>My array has two dimensions/axis. The first one is of length 2 and the second one is of length 3. So by specifying axis you simpy tell your code along which dimension you want to do your job. </p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.html" rel="nofollow">numpy.ndarray.ndim</a> can tell you how many axes do you have</p>
Keeping subdomain name in address bar - Wordpress <p>I'm completely new to the community and have a question which might seem stupid.</p> <p>I've created a page in my Wordpress site (which is not finished yet) which I want to use as a landing page. However, I want this page to be seen as a subdomain of my website.</p> <p>The website is event-lab.ro and the subdomain should be webdesign.event-lab.ro (which actually points to event-lab.ro/webdesign).</p> <p>Now, what I want is to rewrite the Wordpress name as the subdomain, so that whenever someone goes to the link or someone inserts webdesign.event-lab.ro in the address bar, the name in the address bar stays webdesign.event-lab.ro.</p> <p>I'm new to .htaccess, but I've combed the Internet and tried variations of code, with no luck.</p> <p>Here's what I did:</p> <p>1) I created a new folder named "webdesign" in my "public_html" folder (that being where my website is stored).</p> <p>2) I created an .htaccess file in said folder with the following code...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>RewriteEngine on RewriteCond %{HTTP_HOST} ^webdesign\.event\-lab\.ro$ [OR] RewriteCond %{HTTP_HOST} ^www\.webdesign\.event\-lab\.ro$ RewriteRule ^(.*)$ "http\:\/\/event\-lab\.ro\/webdesign" [R=301,L]</code></pre> </div> </div> </p> <p>3) And I also created an index.php file in the same folder, that simply load the Wordpress theme, environment and Template...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php /** * Front to the WordPress application. This file doesn't do anything, but loads * wp-blog-header.php which does and tells WordPress to load the theme. * * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ $_GET['page_id']=25140; define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require('../wp-blog-header.php');</code></pre> </div> </div> </p> <p>4) I should point out that I'm using a childtheme.</p> <p>I've tried all sorts of variations of the .htaccess code, but nothing works. Whenever I try to go to webdesign.event-lab.ro I'm simply redirected to event-lab.ro/webdesign.</p> <p>Any ideas? </p> <p><strong>UPDATE:</strong> Ok, so after some more checks, my hosting company confirmed that mod_proxy is activated. However, the redirect still doesn't work right. If I use the proxy flag, the page doesn't display at all. It just keeps loading until it times out.</p> <p>My current code in the .htaccess file is:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>RewriteEngine on RewriteCond %{HTTP_HOST} ^webdesign\.event\-lab\.ro$ [OR] RewriteCond %{HTTP_HOST} ^www\.webdesign\.event\-lab\.ro$ RewriteRule ^ http://event-lab.ro/webdesign [P]</code></pre> </div> </div> </p>
<p>There are two ways to modify the response to a request, rewrite and redirect.</p> <ul> <li><p>Rewrite is just declaring, what should be sent to a client for some given request.</p></li> <li><p>Redirect tells the client, where it should fetch the response.</p></li> </ul> <p>A redirect is triggered explicitly by the <a href="https://httpd.apache.org/docs/current/rewrite/flags.html#flag_r" rel="nofollow"><code>R|redirect</code></a> flag, or implicitly by giving a full external URL. In your case, you do both <code>http://event-lab.ro/webdesign</code> and <code>R=301</code>.</p> <p>If the requested subdomain and the target document tree is located on the same server, you can just give the path component and omit the <code>R</code> flag.</p> <pre><code>RewriteCond %{HTTP_HOST} ^webdesign\.event-lab\.ro$ [OR] RewriteCond %{HTTP_HOST} ^www\.webdesign\.event-lab\.ro$ RewriteRule ^ /webdesign [L] </code></pre> <hr> <p>Unrelated, you don't need to quote the target. And as an aside, <em>never</em> test with <a href="http://stackoverflow.com/a/9204355/1741542"><code>R=301</code></a>!</p>
DEPRECATION WARNING after updating from Rails 5.0.0 to 5.0.0.1 <p>I updated my Rails app from 5.0.0 to 5.0.0.1 by running the command <code>bundle update rails</code></p> <p>Some commands that gives me this warning are:</p> <pre><code>rails s rails db:migrate rails db:seed git push heroku </code></pre> <p>The full warning are:</p> <pre><code>DEPRECATION WARNING: Sprockets method `register_engine` is deprecated. Please register a mime type using `register_mime_type` then use `register_compressor` or `register_transformer`. https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors (called from block (2 levels) in &lt;class:Railtie&gt; at /home/jeramae/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sass-rails-5.0.5/lib/sass/rails/railtie.rb:57) DEPRECATION WARNING: Sprockets method `register_engine` is deprecated. Please register a mime type using `register_mime_type` then use `register_compressor` or `register_transformer`. https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors (called from block (2 levels) in &lt;class:Railtie&gt; at /home/jeramae/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sass-rails-5.0.5/lib/sass/rails/railtie.rb:58) </code></pre>
<p>Upgrade <code>sass-rails</code> by adding <code>gem 'sass-rails', '~&gt; 5.0', '&gt;= 5.0.6'</code> to <code>Gemfile</code> or modifying the existing line to this and run <code>bundle install --without production &amp;&amp; bundle update</code> .</p>
DBCC Command Not Working Inside Procedure <p>I have below query. Logically, the procedure <code>usp_mytran</code> should RESEED the Identity to 1 for table <code>dbo.Sales</code>. But the last query is returning different values for <em>Max_ID_Value</em> and <em>Current_Seed_Value</em>. Can anyone please explain why DBCC command is not working inside procedure?</p> <pre><code>USE tempdb -- Create table CREATE TABLE dbo.Sales (ID INT IDENTITY(1,1), Address VARCHAR(200)) GO -- Procedure to Populate data into dbo.Sales CREATE PROCEDURE usp_mytran AS BEGIN BEGIN TRANSACTION INSERT dbo.Sales ( Address ) VALUES ( 'Dwarka, Delhi' ); -- Delete it for some reason DELETE FROM dbo.Sales; -- Code to check max ID value, and verify it again IDENTITY SEED DECLARE @MaxValue INT = (SELECT ISNULL(MAX(ID),1) FROM dbo.Sales) IF @MaxValue IS NOT NULL AND @MaxValue &lt;&gt; IDENT_CURRENT('dbo.Sales') DBCC CHECKIDENT ( 'tempdb.dbo.Sales', RESEED, @MaxValue ); ROLLBACK TRANSACTION END -- Ideally, this should RESEED the Identity of dbo.Sales table. EXEC usp_mytran -- Max_ID_Value &amp; Current_Seed_Value should be same SELECT ISNULL(MAX(ID),1) AS Max_ID_Value, IDENT_CURRENT('dbo.Sales') AS Current_Seed_Value FROM dbo.Sales </code></pre>
<p>Sorry for answering my own question. As pointed by @Kannan Kandasamy, it is the <code>ROLLBACK TRANSACTION</code> code that is reverting back the work done by <code>DBCC CHECKIDENT</code>. So to make it work, I have created a job with name <code>Reseed_Sales</code> containing code to RESEED Identity for table <code>dbo.Sales</code>. Below is the final query for procedure <code>usp_mytran</code>.</p> <pre><code>-- Procedure to Populate data into dbo.Sales ALTER PROCEDURE usp_mytran AS BEGIN BEGIN TRANSACTION INSERT dbo.Sales ( Address ) VALUES ( 'Dwarka, Delhi' ); -- Delete it for some reason DELETE FROM dbo.Sales; -- Code to check max ID value, and verify it again IDENTITY SEED DECLARE @MaxValue INT = (SELECT ISNULL(MAX(ID),1) FROM dbo.Sales) IF @MaxValue IS NOT NULL AND @MaxValue &lt;&gt; IDENT_CURRENT('dbo.Sales') EXEC msdb..sp_start_job @job_name = 'Reseed_Sales' ROLLBACK TRANSACTION END </code></pre>
caffe hdf5 H5LTfind_dataset(file_id, dataset_name_) Failed to find HDF5 dataset <p>I was using HDF5 as one of the input to feed caffe, the hdf5 file only contains some weight information to put in the sigmoidcrossentropyloss layer so it doesn't contain any <code>label</code>.This error occured:</p> <blockquote> <pre><code> I1015 07:08:54.605777 17909 net.cpp:100] Creating Layer weight28 I1015 07:08:54.605797 17909 net.cpp:408] weight28 -&gt; weight28 I1015 07:08:54.605834 17909 hdf5_data_layer.cpp:79] Loading list of HDF5 filenames from: /home/zhangyu/codes/unsupervised/data/weight28.txt I1015 07:08:54.605926 17909 hdf5_data_layer.cpp:93] Number of HDF5 files: 1 F1015 07:08:54.608682 17909 hdf5.cpp:14] Check failed: H5LTfind_dataset(file_id, dataset_name_) Failed to find HDF5 dataset weight28 *** Check failure stack trace: *** @ 0x7f17077ec9fd google::LogMessage::Fail() @ 0x7f17077ee89d google::LogMessage::SendToLog() @ 0x7f17077ec5ec google::LogMessage::Flush() @ 0x7f17077ef1be google::LogMessageFatal::~LogMessageFatal() @ 0x7f1707e4d774 caffe::hdf5_load_nd_dataset_helper&lt;&gt;() @ 0x7f1707e4bcf0 caffe::hdf5_load_nd_dataset&lt;&gt;() @ 0x7f1707e8fd78 caffe::HDF5DataLayer&lt;&gt;::LoadHDF5FileData() @ 0x7f1707e8ebf8 caffe::HDF5DataLayer&lt;&gt;::LayerSetUp() @ 0x7f1707e283b2 caffe::Net&lt;&gt;::Init() @ 0x7f1707e2ad85 caffe::Net&lt;&gt;::Net() @ 0x7f1707e6da5f caffe::Solver&lt;&gt;::InitTrainNet() @ 0x7f1707e6df7b caffe::Solver&lt;&gt;::Init() @ 0x7f1707e6e3e8 caffe::Solver&lt;&gt;::Solver() @ 0x7f1707e865a3 caffe::Creator_SGDSolver&lt;&gt;() @ 0x4116b1 caffe::SolverRegistry&lt;&gt;::CreateSolver() @ 0x40ac56 train() @ 0x406e32 main @ 0x7f17066adf45 (unknown) @ 0x4074b6 (unknown) </code></pre> </blockquote> <p>I <a href="http://stackoverflow.com/questions/38348238/error-h5ltfind-datasetfile-id-dataset-name-failed-to-find-hdf5-dataset-lab">searched</a> for this problem and it seems that my hdf5 file need a dataset <strong>label</strong>, but the fact is I don't need that. I only need a dataset of <code>91250x28x28</code>. And feed it to the loss layer as weights. Here is my h5 file:</p> <pre><code>HDF5 weight28.h5 Group '/' Dataset 'data' Size: 2555000x28 MaxSize: Infx28 Datatype: H5T_IEEE_F64LE (double) ChunkSize: 28x28 Filters: none FillValue: 0.000000 </code></pre> <p>I modified the sigmiodcrossentropy layer to add it as a third bottom layer:</p> <pre><code>// modified here const Dtype* pixelweights = bottom[2]-&gt;cpu-&gt;data(); Dtype loss = 0; for (int i = 0; i &lt; count; ++i) { loss -= pixelweights(i)*(input_data[i] * (target[i] - (input_data[i] &gt;= 0)) - log(1 + exp(input_data[i] - 2 * input_data[i] * (input_data[i] &gt;= 0)))); } top[0]-&gt;mutable_cpu_data()[0] = loss / num; } </code></pre> <p>The proto file:</p> <pre><code>layer { name: "loss_G" type: "SigmoidCrossEntropyLoss" bottom: "global_smR" bottom: "mask28" bottom: "weight28" //Added it here top: "loss_G" } </code></pre> <p>I was expected that a batch of the data in the h5 file will be read to the net as <code>bottom[2]</code>(size batchsize*28*28). Here is the question. </p> <ul> <li>Can I get what I expected from the code above?</li> <li>Do I have to add a label set in the h5 file to solve the error?</li> <li>If I add it to the h5 file, how should I handle the extra label data in the loss layer?</li> </ul> <p>Any advice will be appraciated, thanks!</p>
<p>Your <code>"HDF5Data"</code> has <code>top</code> named <code>"weight28"</code>, but your <code>h5</code> file has only dataset <code>"data"</code>. The <code>"top"</code> of <code>"HDF5Data"</code> layer <strong>must</strong> be the same as the Dataset name stored in the <code>h5</code> file. If you have more than one dataset dtored in the same file, you can have multiple <code>top</code>s with the names of the Datasets in the <code>h5</code> file.</p>
Android listview in scrollview <p>Hi i have try insert listview in scrollview but i have this problem: <a href="https://i.stack.imgur.com/sNHMg.png" rel="nofollow"><img src="https://i.stack.imgur.com/sNHMg.png" alt="enter image description here"></a></p> <p>the space that scrollview reserve to listview is little, i want that scrollview is than the screen , i want scrollview is visible only when listview becomes larger than the screen How i do?</p> <p>this is code:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView android:layout_height="wrap_content" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:id="@+id/activity_lista__eventi" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="14dp" android:paddingRight="14dp" android:paddingTop="@dimen/activity_vertical_margin" xmlns:android="http://schemas.android.com/apk/res/android" tools:context="com.example.fra87.eudroid.activity_class.Lista_Eventi"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="vertical"&gt; &lt;SearchView android:layout_width="match_parent" android:layout_height="50dp" android:queryHint="Evento" android:id="@+id/cercaEvento"/&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:id="@+id/linearLayoutEventi"&gt; &lt;ListView android:id="@+id/listViewEventi" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/cercaEvento" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre> <p>How i do this?</p>
<p>More solutions can be found here: <a href="http://stackoverflow.com/questions/18367522/android-list-view-inside-a-scroll-view">Android list view inside a scroll view</a></p> <p>This is a common issue that a lot of developer face. The issue is you are stacking a scrollable view inside another scrollable view. One solution to remove the listview from the scrollview. </p> <p>Another is the following code:</p> <pre><code>public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i &lt; listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); </code></pre> <p>}</p>
Duration of counting to a high number <p>I am trying to set the duration of my counter to be slow without having a large duration number set in the code for example:</p> <pre><code>duration: 99999; </code></pre> <p>Originally I had the counter set to a low number but the count is to reach 1,000,000,00 but i want to be able to control how fast this counts. </p> <p>Here is how I currently have it set up.</p> <pre><code>&lt;div class="counter" data-count="1000000"&gt;0&lt;/div&gt; </code></pre> <p>and my JS is as follows:</p> <pre><code>$('.counter').each(function() { var $this = $(this), countTo = $this.attr('data-count'); $({ countNum: $this.text()}).animate({ countNum: countTo }, { duration: 99999, easing:'linear', step: function() { $this.text(Math.floor(this.countNum)); } }); }); </code></pre> <p>I am a Junior at this so any other recommendations would be appreciated.</p> <p>Thanks</p>
<p>If you want to set how quickly the count is being made, you can try setting the duration (which is measured in milliseconds) to match the <code>countTo</code> value. For example, if you want an increment to be made every second, do: <code>duration: parseInt(countTo)*1000</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.counter').each(function() { var $this = $(this), countTo = $this.attr('data-count'); $({ countNum: $this.text() }).animate({ countNum: countTo }, { duration: parseInt(countTo) * 1000, easing: 'linear', step: function() { $this.text(Math.floor(this.countNum)); }, complete: function() { // Ensure that the final value is updated correctly // ... especially when using very short durations $this.text(this.countNum); } }); });</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;div class="counter" data-count="1000000"&gt;0&lt;/div&gt;</code></pre> </div> </div> </p>
how to enable/disable specific dates in DateTimePicker winforms c# <p>I am programming a <code>C#</code> <code>Windows</code> application for a clinic and i stored days of works for every doctor for example </p> <p>Dr.John works every Monday and Tuesday how i can enable dates in <code>DateTimePicker</code> for dates that only match the specific days and disable other days .</p> <p>I don't know what are the methods and functions can help in that </p>
<p>Instead of the <code>DateTimePicker</code> you can </p> <ul> <li>create a form on the fly</li> <li>add a <code>MonthCalendar</code> to it</li> <li>add either valid or invalid dates to the <code>BoldDates</code> collection</li> <li>code the <code>DateChanged</code> event</li> <li>test to see if a valid date was selected</li> <li>add it to the list of dates picked</li> </ul> <p>Details depend on what you want: A single date or a range, etc.</p> <p>Make sure to trim the time portion, mabe like this for adding dates:</p> <pre><code>List&lt;DateTime&gt; bold = new List&lt;DateTime&gt;(); for (int i = 0; i &lt; 3; i++) bold.Add(DateTime.Now.AddDays(i*3).Date); monthCalendar1.BoldedDates = bold.ToArray(); </code></pre> <p>To select only valid dates maybe code like this:</p> <pre><code>List&lt;DateTime&gt; selected = new List&lt;DateTime&gt;(); private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e) { for (DateTime dt = monthCalendar1.SelectionStart.Date; dt.Date &lt;= monthCalendar1.SelectionEnd.Date; dt = dt.AddDays(1)) { if (!monthCalendar1.BoldedDates.Contains(dt) &amp;&amp; !selected.Contains(dt)) selected.Add(dt.Date); } } </code></pre> <p>Unfortunately the options to set any stylings are limited to bolding dates. No colors or other visual clues seem to be possible.</p> <p>So for anything really nice you will have to build a date picker yourself..</p>
.hide("slow") is synchronous or Asynchronous method? <p>As we know <code>$.ajax()</code> Is a asynchronous method , beacuse next statement starts executing before <code>ajax()</code> method is fully executed and 'ajax()' keep doing his stuff parallelly ,And <code>hide()</code> is a Synchronous method, because it immediately hides the element and next statement will execute when <code>hide()</code> really done his whole task, But I am really confused in the case of <code>hide("slow")</code>. It seems Asynchronous but I read, it sets the timer in browser and everything happen automatically(now <code>hide("slow")</code> is doing nothing parallelly) so in a way , It has also been done its whole task before the next statement start executing ,So <code>hide("slow")</code> also seems a synchronous method , </p> <p>I am very confused about this Synchronous Asynchronous concept </p> <p>Can someone help me to understand this concept ?</p>
<blockquote> <p>.hide(“slow”) is synchronous or Asyncronous method</p> </blockquote> <p>The <em>call</em> to the method is synchronous, but it starts an asynchronous process. So we would normally, loosely, call it an "asynchronous method" (in this case, where you're giving it a duration argument).</p> <p>When you call <code>hide("slow")</code>, you synchronously tell jQuery to <em>start</em> the process of of hiding the element slowly over time. The process of actually doing that takes place asynchronously, after the initial call to <code>hide</code> is complete. (This is also true of <code>ajax</code>: The method itself is synchronous, but the process it starts&nbsp;&mdash; doing the XMLHttpRequest&nbsp;&mdash; continues asynchronously.)</p> <p>Typically if the work of the method is completed <em>during</em> the call to it, we call it a synchronous method, but if it only <em>starts</em> work that completes later, we call it an asynchronous method. Technically the method itself isn't asynchronous, just the overall process that it initiates, but...</p> <p><a href="http://api.jquery.com/hide" rel="nofollow"><code>hide</code></a> itself, of course, is both a synchronous and asynchronous method depending on what argument(s) you pass it: If you call it with no duration (<code>.hide()</code>), it's synchronous; if you call it with a duration (<code>.hide("slow")</code>, <code>.hide(400)</code>), it's asynchronous.</p>
How to create a "LIKE" button on a cell and conform to MVC? <p>I want to create a like button on a table view cell, just like Instagram, Facebook, and 100s of other social network apps have, but I am struggling to understand how this can be done properly keeping in mind MVC paradigm. </p> <p>My structure looks like this:</p> <pre><code>Model - FeedPost class View - FeedCell class (UITableViewCell subclass) Controller - FeedTableViewController class (UITableViewController subclass) </code></pre> <p>The first thing that came to mind was to do the following:</p> <p>In FeedCell.swift:</p> <pre><code>@IBAction func likeButtonPressed(_ sender: AnyObject) { if let button = sender as? UIButton { post.like(completed: { if(completed){ button.isSelected = !button.isSelected } }) } } </code></pre> <p>And in FeedPost.class:</p> <pre><code>func like(completed: (Bool) -&gt; Void ) { //Make a request to a server and when it is done call completed(true) } </code></pre> <p>But this certainly breaks the MVC pattern, as I access my model from the view. So I probably want to work with my data and view via the view controller. The view controller stores the array of posts. So I want to do the following: - Respond to user pressing the button on the table view cell - Find out which post was liked - Perform the server request passing the id of the post or any other reference to it - Upon successful completion of the request, change button state to selected</p> <p>How would you do this while following the MVC pattern?</p> <p>Any examples or open source projects where this was done the right way will be highly appreciated.</p>
<p>How about something like:</p> <p>FeedCell.swift:</p> <pre><code>@IBOutlet var likeButton: UIButton! var likeButtonPressedHandler: (() -&gt; ())? var isLikeButtonSelected: Bool { get { return likeButton.isSelected } set { likeButton.isSelected = newValue } } @IBAction func likeButtonPressed(_ button: UIButton) { likeButtonPressedHandler?() } </code></pre> <p>FeedPost.class:</p> <pre><code>func like(completion: (Bool) -&gt; Void ) { //Make a request to a server and when it is done call completion(true) } </code></pre> <p>ViewController (UITableViewDataSource):</p> <pre><code>var posts: [FeedPost] func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as? FeedCell let post = posts[indexPath.row] cell.isLikeButtonSelected = post.isLiked cell.likeButtonPressedHandler = { [weak cell] in post.like { completed in if let cell = cell where completed { cell.isLikeButtonSelected = !cell.isLikeButtonSelected } }) } return cell } </code></pre>
Advanced array concatenation python <p>Say I have four multi-dimensional arrays - </p> <pre><code>a = [["a","a","a"], ["a","a","a"], ["a","a","a"]] b = [["b","b","b"], ["b","b","b"], ["b","b","b"]] c = [["c","c","c"], ["c","c","c"], ["c","c","c"]] d = [["d","d","d"], ["d","d","d"], ["d","d","d"]] </code></pre> <p>and I want to combine them into a single array like</p> <pre><code>total = [["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["a","a","a","b","b","b"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"], ["c","c","c","d","d","d"]] </code></pre> <p>How would I do it?</p> <p><em>I am doing it for spelunky-style map generation</em></p>
<p>Maybe like this:</p> <pre><code>top = list(x+y for x,y in zip(a,b)) bottom = list(x+y for x,y in zip(c,d)) total = top + bottom for r in total: print(r) </code></pre> <p>Output:</p> <pre><code>['a', 'a', 'a', 'b', 'b', 'b'] ['a', 'a', 'a', 'b', 'b', 'b'] ['a', 'a', 'a', 'b', 'b', 'b'] ['c', 'c', 'c', 'd', 'd', 'd'] ['c', 'c', 'c', 'd', 'd', 'd'] ['c', 'c', 'c', 'd', 'd', 'd'] </code></pre>
How to synchronize a google calendar with google spreadsheet? <p>My goal is to synchronize a google calendar with a google spreadsheet automatically. Every time an event is added to the calendar, rows should be appended to the google spreadsheet. I wrote a script that loads the list of the upcoming event into a google spreadsheet. This code is working and append the list of 10 events every time I run the script. However, what I want is to automatically run this script when an event is created via google calendar and I want to avoid duplicated events. What function is available for such event listener? </p> <pre><code>function listUpcomingEvents() { var calendarId = 'alueducation.com_rtjgosrsgo9f4c6hqm5urebs68@group.calendar.google.com'; var optionalArgs = { timeMin: (new Date()).toISOString(), showDeleted: false, singleEvents: true, maxResults: 10, orderBy: 'startTime' }; var response = Calendar.Events.list(calendarId, optionalArgs); var events = response.items; if (events.length &gt; 0) { for (i = 0; i &lt; events.length; i++) { var event = events[i]; var when = event.start.dateTime; if (!when) { when = event.start.date; } Logger.log('%s (%s)', event.summary, when); addEventToSheet(event.summary, when); } } else { Logger.log('No upcoming events found.'); } } function addEventToSheet(sumarry, date) { var sheet = SpreadsheetApp.getActiveSheet(); sheet.appendRow([sumarry, date]); } </code></pre>
<h1>Short answer</h1> <p>Use a time-drive trigger</p> <h1>Explanation</h1> <p>At this time Google Apps Script is not able to bound a script to a Google Calendar. The alternatives are to use a bounded to a spreadsheet or a standalone script, so it's not possible at this time to trigger an script when an event is created in contrast with the form response submission.</p> <h1>References</h1> <ul> <li><a href="https://developers.google.com/apps-script/guides/standalone" rel="nofollow">Types of Scripts</a></li> <li><a href="https://developers.google.com/apps-script/guides/triggers/" rel="nofollow">Triggers and Events</a></li> </ul>
mysqli_insert_id on compound query <p>I am using <code>mysqli_insert_id()</code> to get the last auto increment id on a table, but it always returns '0'. </p> <pre><code>$sql = "INSERT INTO inventory (SELECT * FROM tmptable)"; $result = mysqli_query($link, $sql); $newId = mysqli_insert_id($link); //$newID ends up being 0 </code></pre> <p>The <code>id</code> column of the <code>inventory</code> table is set to auto increment, and <code>mysqli_insert_id()</code> works fine on other <code>INSERT</code> queries to <code>inventory</code> that aren't inserting the result of a <code>SELECT</code> statement. Is the <code>SELECT</code> statement taking precedence as the last query for some reason, which would cause <code>mysqli_insert_id()</code> to return 0?</p>
<p>You're using <code>LAST_INSERT_ID()</code> incorrectly. <a href="http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id</a> It's the server feature underlying <a href="http://php.net/manual/en/mysqli.insert-id.php" rel="nofollow"><code>mysqli_insert_id()</code></a>.</p> <p>First, your INSERT statement doesn't mention a list of column names. That means it's inserting information into all the columns of the target table, including the autoincrementing column. When you specify the value of the autoincrementing column in your INSERT, you disable the autoincrementing feature, so you get zero back instead of an actual <code>id</code> value from <code>LAST_INSERT_ID()</code>.</p> <p>Second, if you insert more than one row, you only will get the id value of the first row inserted.</p>
difference between viewport and camera in libgdx? <p>I am new to LibGdx framework, and having trouble working with viewport and camera. Can anyone give a simple difference between each and use of both.</p>
<p>In a simple way, the camera is nothing but it's like our real life camera. in libgdx camera is used to show our game area. for example for making a movie the director will do so many preparation and everything will be capturing through the camera. in the same way in libgdx for our gameplay, we create so many sprites, textures ..etc and all these things captured by a camera and rendering into the screen. in a simple way we can tell that the camera displays the game area. The another important topic in libgdx is viewPort. which is mainly used to make our game compatible to the multiple device. different devices have different screen resolutions .so when we play the game on different devices it will show some resolution issues (stretching the image,character out of screen etc) .libgdx provideds the viewport to solve this multi screen issue . there are mainly three types of viewPorts are available 1)stretch view port 2)fill view port 3)fit view port</p> <p>for more details please go through the below link</p> <p><a href="https://github.com/libgdx/libgdx/wiki/Viewports" rel="nofollow">https://github.com/libgdx/libgdx/wiki/Viewports</a></p>
Floating action button: Error inflating class FloatingActionButton <p>I'm trying to use the floating action button in xamarin.forms from the NuGet <code>FAB.Forms</code> package(<a href="https://github.com/keannan5390/Xamarin.Plugin.FAB" rel="nofollow">github</a>). I tried to make my code like the example provided in the <code>Sample</code> folder</p> <p>Xamarin.Droid <code>MainActivity.cs</code> file</p> <pre><code>protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); FAB.Droid.FloatingActionButtonRenderer.InitControl(); LoadApplication(new App()); } </code></pre> <hr> <p>Xamarin.ios <code>AppDelegate.cs</code> file</p> <pre><code>public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); FAB.iOS.FloatingActionButtonRenderer.InitControl(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } </code></pre> <hr> <p>Xamarin.portable <code>App.cs</code> file</p> <pre><code>public App(){MainPage = new LatestNews();} </code></pre> <hr> <p>LatestNews.xaml file</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:fab="clr-namespace:FAB.Forms;assembly=FAB.Forms" x:Class="HuraApp.Pages.LatestNews"&gt; ... &lt;fab:FloatingActionButton x:Name="fabBtn" Source="plus.png" Size="Normal" Clicked="Handle_FabClicked" NormalColor="Green" RippleColor="Red" /&gt; ... &lt;/ContentPage&gt; </code></pre> <hr> <p>LatestNews.xaml.cs file</p> <pre><code>void Handle_FabClicked(object sender, System.EventArgs e) { this.DisplayAlert("Floating Action Button", "You clicked the FAB!", "Awesome!"); } </code></pre> <hr> <p>portable packages.config file</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;packages&gt; &lt;package id="FAB.Forms" version="2.1.1" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Microsoft.Bcl" version="1.1.10" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Microsoft.Net.Http" version="2.2.29" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Newtonsoft.Json" version="9.0.1" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="sameerIOTApps.Plugin.SecureStorage" version="1.2.1" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Xam.Plugin.Media" version="2.3.0" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Xamarin.Forms" version="2.3.2.127" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;package id="Xamarin.Forms.Maps" version="2.3.2.127" targetFramework="portable45-net45+win8+wpa81" /&gt; &lt;/packages&gt; </code></pre> <hr> <p>droid package.config file</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;packages&gt; &lt;package id="FAB.Forms" version="2.1.1" targetFramework="monoandroid60" /&gt; &lt;package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.Design" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.v4" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.v7.CardView" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.v7.RecyclerView" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Android.Support.Vector.Drawable" version="23.3.0" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Forms" version="2.3.2.127" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.Forms.Maps" version="2.3.2.127" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.GooglePlayServices.Base" version="29.0.0.1" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.GooglePlayServices.Basement" version="29.0.0.1" targetFramework="monoandroid60" /&gt; &lt;package id="Xamarin.GooglePlayServices.Maps" version="29.0.0.1" targetFramework="monoandroid60" /&gt; &lt;/packages&gt; </code></pre> <hr> <p>iOS package.config file</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;packages&gt; &lt;package id="FAB.Forms" version="2.1.1" targetFramework="xamarinios10" /&gt; &lt;package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="xamarinios10" /&gt; &lt;package id="Xamarin.Forms" version="2.3.2.127" targetFramework="xamarinios10" /&gt; &lt;package id="Xamarin.Forms.Maps" version="2.3.2.127" targetFramework="xamarinios10" /&gt; &lt;/packages&gt; </code></pre> <hr> <p>But when I run the application on android emulator it gives me the error message</p> <pre><code>`Android.Views.InflateException: Binary XML file line #1: Binary XML file line #1: Error inflating class android.support.design.widget.FloatingActionButton` </code></pre> <p>Why is that happening? What am I missing? and how can I solve this problem?</p>
<p>I had similar problem but i use Android. Just change the project parent theme to any Theme.AppCompat~, this resolved my problem, maybe your also. And add <code>global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity</code> to your <code>MainActivity.cs</code>.</p> <pre><code>[Activity(Label = "YourName", , Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); FAB.Droid.FloatingActionButtonRenderer.InitControl(); LoadApplication(new App()); } } </code></pre> <p>You can add theme like this in <code>style.xml</code></p> <pre><code>&lt;style name="MyTheme" parent="Base.AppTheme"&gt; &lt;/style&gt; &lt;style name="Base.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;item name="windowNoTitle"&gt;true&lt;/item&gt; &lt;/style&gt; </code></pre>
PHP form validation to do alert if no error <p>I have the following form validation.</p> <pre><code>&lt;?php $error_occured = 0; $error_name = ""; $error_email = ""; $error_contact = ""; $error_comments = ""; if(isset($_POST["tx_name"])) { if(($tx_name == "") || (!preg_match("/^[a-zA-Z ]*$/",$tx_name))) { $error_occured = 1; $error_name = "Please enter a valid name"; } if(($tx_email == "") || (!filter_var($tx_email, FILTER_VALIDATE_EMAIL))) { $error_occured = 1; $error_email = "Please enter a valid email"; } if(($tx_contact == "") || !(is_numeric($tx_contact))) { $error_occured = 1; $error_contact = "Please enter a valid contact number"; } if($tx_comments == "") { $error_occured = 1; $error_comments = "Please enter your message"; } } if(isset($_POST["tx_name"]) &amp;&amp; $error_occured = 0) { echo "&lt;script&gt;alert('Hi!');&lt;/script&gt;"; } ?&gt; </code></pre> <p>The validation works fine and if there is no error, its supposed to do an alert. However, when I submit the form with no error, I do not see the alert message. How do I fix this?</p>
<p>Try like this</p> <pre><code>&lt;?php $error_occured = 0; $error_name = ""; $error_email = ""; $error_contact = ""; $error_comments = ""; if(isset($_POST["tx_name"])) { if(($tx_name == "") || (!preg_match("/^[a-zA-Z ]*$/",$tx_name))) { $error_occured = 1; $error_name = "Please enter a valid name"; } if(($tx_email == "") || (!filter_var($tx_email, FILTER_VALIDATE_EMAIL))) { $error_occured = 1; $error_email = "Please enter a valid email"; } if(($tx_contact == "") || !(is_numeric($tx_contact))) { $error_occured = 1; $error_contact = "Please enter a valid contact number"; } if($tx_comments == "") { $error_occured = 1; $error_comments = "Please enter your message"; } if($error_occured != 1) { echo "&lt;script&gt;alert('Hi!');&lt;/script&gt;"; } } ?&gt; </code></pre>
Download a web page using wget and define a new filename <p>I need to write a script in bash using <code>wget</code> which download a web page which has been passed to an argument and then the script should put the extracted page in a new <em>file.html</em> and then also extract all the tags of the web page in a second file and keep only the content of the web page.</p> <p>This is the beginning of my script :</p> <pre><code>#!/bin/bash $page = "https://fr.wikipedia.org/wiki/Page_web" wget -r -np '$page' file.html </code></pre> <p>From the second part, I am blocked.</p>
<p>This will work:</p> <pre><code>page="https://fr.wikipedia.org/wiki/Page_web" wget -O file.html -r -np "$page" </code></pre> <ol> <li>Variable assignment: <code>var_name=value</code> (no space allowed around <code>=</code>)</li> <li>Bash is not PHP, <code>$var=val</code> is not correct, <code>var=val</code> is.</li> <li>Use double quote to allow variable expansion (<code>"$page"</code>)</li> </ol> <p>From <code>wget</code> manual:</p> <blockquote> <pre><code>-O file --output-document=file The documents will not be written to the appropriate files, but all will be concatenated together and written to file. </code></pre> </blockquote>
How to find oracle J2EE tutorial? <p><a href="https://docs.oracle.com/javaee/7/tutorial/" rel="nofollow">https://docs.oracle.com/javaee/7/tutorial/</a></p> <p>I can`t find this tutorial; I am a beginner with j2EE.</p> <p>Thanks in advance. </p>
<p>check this link please <a href="http://docs.oracle.com/javaee/7/tutorial/" rel="nofollow">Java Platform, Enterprise Edition: The Java EE Tutorial</a> </p> <p>They have just restructured the documentation.</p>
Theano learning AND gate <p>I wrote a simple neural network to learn an AND gate. I'm trying to understand why my cost never decreases and the predictors are always 0.5:</p> <pre><code>import numpy as np import theano import theano.tensor as T inputs = [[0,0], [1,1], [0,1], [1,0]] outputs = [[0], [1], [0], [0]] x = theano.shared(value=np.asarray(inputs), name='x') y = theano.shared(value=np.asarray(outputs), name='y') alpha = 0.1 w_array = np.asarray(np.random.uniform(low=-1, high=1, size=(2, 1)), dtype=theano.config.floatX) w = theano.shared(value=w_array, name='w', borrow=True) output = T.nnet.sigmoid(T.dot(x, w)) cost = T.sum((y - output) ** 2) updates = [(w, w - alpha * T.grad(cost, w))] train = theano.function(inputs=[], outputs=[], updates=updates) test = theano.function(inputs=[], outputs=[output]) calc_cost = theano.function(inputs=[], outputs=[cost]) for i in range(60000): if (i+1) % 10000 == 0: print(i+1) print(calc_cost()) train() print(test()) </code></pre> <p>The output is always the same:</p> <pre><code>10000 [array(1.0)] 20000 [array(1.0)] 30000 [array(1.0)] 40000 [array(1.0)] 50000 [array(1.0)] 60000 [array(1.0)] [array([[ 0.5], [ 0.5], [ 0.5], [ 0.5]])] </code></pre> <p>It always seems to predict 0.5 regardless of the input because the cost is not deviating from 1 during learning</p> <p>If I switch the outputs to <code>[[0], [1], [1], [1]]</code> for learning an OR gate, I get the correct predictions, and correctly decreasing cost</p>
<p>Your model is of form</p> <pre><code>&lt;w, x&gt; </code></pre> <p>thus it cannot build any separation which <strong>does not cross the origin</strong>. Such equation can only express lines going through point (0,0), and obviously line separating AND gate ((1, 1) from anything else) does not cross the origin. You have to add <strong>bias</strong> term, so your model is</p> <pre><code>&lt;w, x&gt; + b </code></pre>
Split strings with specified step in python <p>I have a string in python without white space and I want python to split this string for every 3 letters so like <code>'antlapcap'</code>, For example would be <code>['ant', 'lap', 'cap']</code> is there any way to do this? </p>
<p>not sure if theres a more efficient way of doing it but ,try:</p> <pre><code>string = "antlapcap" list = [] i = 0 for i in range(i,len(string)): word =string[i:i+3] list.append(word) i=i+3 j = list b =j[::3] print(b) </code></pre>
Method not calling of RestController of Spring mvc4 <p>I wrote Code for restful api but method is not calling, getting error "Context Root Not Found".</p> <p>I am using liberty profile</p> <p>Here is a my code Controller</p> <pre><code>@RestController public class demoAPIController { @RequestMapping(value = "/restcall", method = RequestMethod.GET, produces = "application/json") public ResponseEntity&lt;String&gt; GetParseResume() { return new ResponseEntity("hello", HttpStatus.OK); } } </code></pre> <p>WebAppInitializer </p> <pre><code>public class WebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { WebApplicationContext context = getContext(); servletContext.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("*.html"); dispatcher.addMapping("*.pdf"); dispatcher.addMapping("*.json"); } private AnnotationConfigWebApplicationContext getContext() { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(WebConfig.class); return context; } } </code></pre> <p>here WebConfig.java</p> <pre><code> @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.demo") public class WebConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver getInternalResourceViewResolver() { InternalResourceViewResolver viewResolve = new InternalResourceViewResolver(); viewResolve.setPrefix("/WEB-INF/jsp/"); viewResolve.setSuffix(".jsp"); return viewResolve; } } </code></pre> <p>Error showing in Spring tool suite while start liberty server</p> <pre><code>[ERROR ] CWWKZ0002E: An exception occurred while starting the application demo1. The exception message was: java.lang.IllegalStateException: com.ibm.wsspi.adaptable.module.UnableToAdaptException: java.util.zip.ZipException: invalid LOC header (bad signature) </code></pre>
<p>Possible cause would be your liberty does not support servlet 3.0+. So you should do some tweaking according to spring recommends</p> <blockquote> <p>Spring Boot uses Servlet 3.0 APIs to initialize the ServletContext (register Servlets etc.) so you can’t use the same application out of the box in a Servlet 2.5 container. It is however possible to run a Spring Boot application on an older container with some special tools. If you include org.springframework.boot:spring-boot-legacy as a dependency (maintained separately to the core of Spring Boot and currently available at 1.0.2.RELEASE), all you should need to do is create a web.xml and declare a context listener to create the application context and your filters and servlets. </p> </blockquote> <p><a href="http://docs.spring.io/spring-boot/docs/current/reference/html/howto-traditional-deployment.html#howto-servlet-2-5" rel="nofollow">http://docs.spring.io/spring-boot/docs/current/reference/html/howto-traditional-deployment.html#howto-servlet-2-5</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;demo.Application&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter&gt; &lt;filter-name&gt;metricFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;metricFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextAttribute&lt;/param-name&gt; &lt;param-value&gt;org.springframework.web.context.WebApplicationContext.ROOT&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt;</code></pre> </div> </div> </p>
Many to many naming conventions <p>What I've understand so far is that many to many table naming conventions for Laravel are:</p> <p><code>users &amp; privileges = user_privilege</code></p> <p>But what is the case with more complex names like:</p> <p><code>attributes &amp; composed_attributes = ?</code></p> <p>As you can see there is a underscore symbol in the second table. Is that underscore in the way of Laravel recognizing the pivot by default? Is <code>attribute_composed_attribute</code> going to work? If so what is the proper name for the second table in order to work?</p> <p>Appreciate your kind help.</p>
<p>It will be <code>attribute_composed_attribute</code>.</p> <blockquote> <p>Name of the pivot table should consist of singular names of both tables, separated by undescore symbole and these names should be arranged in alphabetical order</p> </blockquote> <p><a href="http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/" rel="nofollow">http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/</a></p>
How do javascript engine count number of tag of the HTML document is ill-formed? <p>From this question: <a href="https://stackoverflow.com/questions/40057381/finding-the-missing-sequence-number-in-a-file">Finding the missing sequence number in a file</a></p> <p>The author gave this example:</p> <pre><code>&lt;p&gt;have a great &lt;a id="page-1"/&gt;day. How are you.&lt;/p&gt; &lt;p&gt;&lt;a id="page-2"/&gt;Have a nice day.&lt;/p&gt; &lt;p&gt;How &lt;a id="page-5"/&gt;are you&lt;/p&gt; &lt;p&gt;Life is so exciting&lt;a id="page-6"/&gt;&lt;/p&gt; &lt;p id="tag_count"&gt;&lt;/p&gt; </code></pre> <p><a href="https://stackoverflow.com/users/5104748/mohammad">Mohammad</a> had convinced me that the given html document is ill-formed by running:</p> <pre><code>document.getElementById('tag_count').innerHTML = document.getElementsByTagName("a").length; </code></pre> <p>And the tag with id <code>tag_count</code> is changed to 11.</p> <p>My question is how do javascript engine make that? It's consistent with both Firefox and Chrome. Is it consistent with other browser or it's some kind of "undefined behavior"?</p>
<blockquote> <p>My question is how do javascript engine make that?</p> </blockquote> <p>It doesn't. By the time you're using JavaScript to access the resulting DOM document, the structural problems like unclosed tags have <em>already</em> been resolved by the browser's HTML parser. All that's happening in the line of code that you've shown is that the JavaScript engine is asking the DOM how many <code>a</code> elements ended up being in the document <strong>after</strong> the HTML, with all its issues, had been parsed.</p> <p>The <a href="https://www.w3.org/TR/html5/" rel="nofollow">HTML specification</a> has a lot to say about recovering from invalid markup, information and techniques that were determined over a period of 20 years by various browser implementations and eventually agreed to by the members of the <a href="https://whatwg.org/" rel="nofollow">WHAT-WG</a> as a common set of error-correction approaches.</p>
In which class I can write this function as per OOP standards? <p>I have Institute class and Branch class. Institute have multiple branches, so as per OOP standard, when I need branches of particular institute with function getBranches($institute_id), then in which class I need to write this function, In Institute or Branch class? I am using PHP</p>
<p>In General you should place getBranches in Institute class.</p> <p>But depending on the case and the problem you are solving the implementation may vary.</p>
Recommended way to export variables in Node.js <p>I have a <code>worker.js</code> file which periodically updates the values of few variables. In other files of my Node.js server I want to access to those vars.</p> <p>I know how to export them, but it seems they are exported by value - i.e. they have the value they had at the moment I issued the <code>require</code> function.</p> <p>Of course, I'm interested to access to their latest value. What's the recommended way to do this? A "getter" function or else?</p>
<p>A possible way to export them by reference is to actually manipulate the <code>module.exports</code> object - like so:</p> <pre><code>//worker.js module.exports.exportedVar = 1; var byValueVar = 2; setInterval(foo, 2000); function foo() { module.exports.exportedVar = 6; x = 8; } //otherfile.js var worker = require('./worker'); console.log(worker.exportedVar); //1 console.log(worker.byValueVar) //2 setInterval(foo, 3000); function foo() { console.log(worker.exportedVar); //6 console.log(worker.byValueVar); //2 } </code></pre>
What Kind of technology is this? <p>I have recently been awestruck by this Javascript based technology i saw on a webiste. I just want to know how these guys are doing that. Are they using any frameworks or is it RAW JS or Jquery.</p> <p>Please take a look at this - <a href="http://startit.select-themes.com/tech-business/" rel="nofollow">Click Here</a></p> <p>So, in the main featured Image (I don't even know if it is just an image), whenever you move your pointer in between a set of moving dots, all the dot's automatically connects to your pointer and if you move your pointer to next set of dots, the connected lines just slide to the next section.</p> <p>Can anybody please explain, what kind of technology is this and how can i achieve this if i want to implement in my website.</p> <p>Thanks for taking a look</p>
<p>Take a look at this: <a href="https://github.com/VincentGarreau/particles.js/" rel="nofollow">https://github.com/VincentGarreau/particles.js/</a></p> <p>The readme explains everything in detail.<br><br> Basically you create a <code>&lt;div id="particles-js"&gt;&lt;/div&gt;</code> and you include the needed files like <code> &lt;script src="plugins/particles/particles.js"&gt;&lt;/script&gt; &lt;script src="plugins/particles/app.js"&gt;&lt;/script&gt;</code></p>
How do I make a file inaccessible with Apache? <p>all!</p> <p>First of all, a list of what software &amp; frameworks I use:<br> - XAMPP<br> - Apache 2.4<br> - Modal-view-controller (mvc) framework with Bootstrap/Twig/Altorouter/PSR4</p> <p>I have a folder on my site, with a .json file which contains my database login information. Of course, I don't want anybody to have access to this file. At the moment when I go to "127.0.0.1/protected/settings.json" with a browser, it will show me the file (which is a huge security flaw obviously). I thought that I would have to change my .htaccess file to exclude the settings.json file. But I can't seem to find out how.</p> <p>This is my current .htaccess file:</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php [L] </code></pre> <p>Thanks in advance!<br> Mats de Waard.</p>
<p>Basically, you have to edit your htaccess file in the specified directory where settings.json is.</p> <pre><code> &lt;Files ~ "\.json"&gt; Order allow,deny Deny from all &lt;/Files&gt; </code></pre> <p>This would prevent any json file to be opened. make it as </p> <pre><code>&lt;Files ~ "\settings.json"&gt; Order allow,deny Deny from all </code></pre> <p></p> <p>This should work. Works for me though!</p>
setTransform () for SurfaceView <p>When recording via TextureView to the screen is not mirrored used setTransform () method:</p> <pre><code>Matrix txform = new Matrix(); mTextureView.getTransform(txform); txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight); txform.postTranslate(xoff, yoff); mTextureView.setTransform(txform); </code></pre> <p>And in my case I use SurfaceView instead TextureView and it turns out there is this method ...</p> <p>Question: What should I do in order to mirror does not reflect, and what to use instead setTransform ()?</p>
<p>In order to mirror over Y axis use this:</p> <pre><code>txform.setScale(-(float) newWidth / viewWidth, (float) newHeight / viewHeight, viewWidth / 2.f , 0); </code></pre>
Import settings from the file <p>I would like to import settings from a yaml file, but make them available as regular variables in the current context.</p> <p>for example I may have a file:</p> <pre><code>param1: 12345 param2: test11 param3: a: 4 b: 7 c: 9 </code></pre> <p>And I would like to have variables <code>param1</code>, <code>param2</code>, <code>param3</code> in my code.</p> <p>I may want to use this from any function and do not want to have them available globally.</p> <p>I have heard about <code>locals()</code> and <code>globals()</code> functuons, but did not get how to use them for this.</p>
<p>Even though the trick is great in @baldr's answer, I suggest moving the variable assignments out of the function for better readability. Having a function change its caller's context seems very hard to remember and maintain. So, </p> <pre><code>import yaml def get_settings(filename): with open(filename, 'r') as yf: return yaml.load(yf.read()) def somewhere(): locals().update(get_settings('foo.yaml')) print(param1) </code></pre> <p>Even then I would strongly suggest simply using the dictionary. Otherwise, you risk very strange bugs. For instance, what if your yaml file contains a <code>open</code> or a <code>print</code> key? They will override python's functions, so the <code>print(param1)</code> in the example will raise a <code>TypeError</code> exception.</p>
Cypher: All paths without loops <p>I have trouble to get all possible paths between to nodes without loops. I use neo4j 3.0.4. I prepared an example but first of all a short explanation. I have nodes from A to Z. These nodes can be connected in each way. I want to get all possible paths without loops, meaning a specific node is not visited more than once.</p> <p>Here the example:</p> <pre><code>CREATE (newNode {name:'A'}) RETURN newNode; CREATE (newNode {name:'B'}) RETURN newNode; CREATE (newNode {name:'C'}) RETURN newNode; CREATE (newNode {name:'D'}) RETURN newNode; CREATE (newNode {name:'E'}) RETURN newNode; CREATE (newNode {name:'Z'}) RETURN newNode; MATCH (n1), (n2) WHERE n1.name = 'A' AND n2.name = 'B' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'A' AND n2.name = 'C' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'B' AND n2.name = 'C' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'C' AND n2.name = 'D' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'D' AND n2.name = 'E' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'E' AND n2.name = 'Z' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'D' AND n2.name = 'Z' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'D' AND n2.name = 'A' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH (n1), (n2) WHERE n1.name = 'B' AND n2.name = 'A' CREATE (n1)-[r:CONNECTED_TO]-&gt;(n2) RETURN n1, n2, r; MATCH p=(from{name:'A'}), (to{name:'Z'}), path = (from)-[r*]-&gt;(to) RETURN path </code></pre> <p>If I run the last query, I will get also paths like A->B->A->C->D->Z. I want to avoid this loop A->B->A. The allShortestPaths does not work for me because it will just provide the paths with the fewest hops. But I want to get all paths without loops, the number of hops is not relevant. It will be necessary to limit the result or the path length because the query is very expensive.</p> <pre><code>path = (from)-[r*20]-&gt;(to) </code></pre> <p>But that is not the solution to avoid the loops because they can occur also in short paths.</p> <p>EDIT1: Ok, now I come up with a possible solution for this:</p> <pre><code>MATCH (from{name:'A'}), (to{name:'Z'}), path = (from)-[:CONNECTED_TO*]-&gt;(to) WHERE NONE (n IN NODES(path) WHERE SIZE(FILTER(x IN NODES(path) WHERE n = x))&gt; 1) RETURN path, LENGTH(path) as length ORDER BY length; </code></pre> <p>This query seems to work, but I assume that it is very expensive. Can someone offer a better solution?</p>
<p>Your filter will fail out slightly faster if you change it to this:</p> <pre><code>WHERE ALL(x IN NODES(path) WHERE SINGLE(y IN NODES(path) WHERE y = x)) </code></pre> <p>But I don't believe you'll find a fundamentally more efficient way. Usually your options are pretty limited when your question contains the words "all paths" and your sample has an unbounded relationship :)</p>
Adding space in an array in JavaScript <p>I am trying to make a hangman game. So I have a function that takes the word and makes a new array of the underscore dashes. I have that working perfectly but now I am trying to add the functionality of have spacing so multiply words. But now it adds random spaces instead. </p> <p>Any Help?</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 dash(word) { var dash = []; for (var i = word.length - 1; i &gt;= 0; i--) { if (word[i] == " ") { dash.push("&amp;nbsp;"); } else { dash.push("_"); } } return dash; }</code></pre> </div> </div> </p>
<p>This spaces aren't random – they inverted.<br>It's because of you running your word from back to front:<br> instead of <code>for (var i = word.length - 1; i &gt;= 0; i--)</code> try it:</p> <pre><code>function dash(word) { var dash = []; for (var i = 0; i &lt; word.length; i++) { if (word[i] == " ") { dash.push("&amp;nbsp;"); } else { dash.push("_"); } } return dash; } </code></pre>
Autoplay youtube video on hover/mouseover <p>I am trying to play the youtube video for auto play when the iframe tag is on focus. Tried the following but it is not working. Error with my jquery? I want to add &amp;autoplay=1 to the src of iframe when it is focus.</p> <p>Html :-</p> <pre><code>&lt;div class="vid-wrapper" &gt; &lt;iframe width="100%" height="100%" id="video1" src="https://www.youtube.com/embed/bxgorUGjCIw?rel=0" frameborder="0" allowfullscreen scrolling="auto" &gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>Css :-</p> <pre><code>.vid-wrapper{ width: 100%; position: relative; padding-bottom: 56.25%; height: 0; z-index:-20; } .vid-wrapper video, .vid-wrapper iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index:-1; } </code></pre> <p>Jquery :-</p> <pre><code>$(document).ready(function() { $("#video1").mouseenter(function(){ $(this).attr("src",$(this).attr("src") + "&amp;amp;autoplay=1"); }); $("#video1").mouseleave(function(){ var src= $(this).attr("src"); var arr_str = src.split("&amp;amp;"); $(this).attr("src",arr_str[0]); }); }); </code></pre> <p>Any help? Thanks in advance.</p>
<p>Actually you don't really want to change the <code>src</code> attribute, but to use <a href="https://developers.google.com/youtube/iframe_api_reference" rel="nofollow">youtube's api</a> for that:</p> <blockquote> <p>The snippet will <strong>not</strong> work due to cross-origin problems (specifically in stackoverflow) but the code works.</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'M4Xrh8OP1Jk' }); } $(document).on('mouseover', '#player', function() { player.playVideo(); }); $(document).on('mouseout', '#player', function() { player.pauseVideo(); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//www.youtube.com/player_api"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="player"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Here is a working jsfiddle:<br> <a href="https://jsfiddle.net/rurc8rb9/" rel="nofollow">https://jsfiddle.net/rurc8rb9/</a></p>
Webix Datatable onclick cannot get selected row data <p>I am putting together a webix UI for country data.<br><br> The working code is here: <a href="http://sahanaya.net/webix/flags3.html" rel="nofollow">http://sahanaya.net/webix/flags3.html</a><br><br> I cannot get the datatable row data when clicked. I want to click a datatable row, grab the country name and display related country data in the bottom in another webix row. Eg: Cities, Drives on right/left, Major Attractions etc. <br><br> Code is below:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Country Data&lt;/title&gt; &lt;script type="text/javascript" src="http://cdn.webix.io/edge/webix.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="http://cdn.webix.io/edge/webix.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class='sample_comment'&gt;Country Data&lt;/div&gt; &lt;div id="testD"&gt;&lt;/div&gt; &lt;script type="text/javascript" charset="utf-8"&gt; webix.ready(function(){ gridd = webix.ui({ rows: [ { view:"template", template:"some text", type:"header" },], container:"testD", view:"datatable", columns:[ { id:"data0", header:"test id", css:"rank", width:50}, { id:"data1", header:["Country", {content:"textFilter"}], width:200, sort:"string"}, { id:"data2", header:"Flag" , width:80}, { id:"data3", header:"Capital" , width:80}, { id:"data4", header:"Dialing Code", width:80}, { id:"data5", header:"Area", width:100}, { id:"data6", header:"Population", width:150}, { id:"data7", header:"President", width:150}, { id:"data8", header:["Languages",{content:"textFilter"}],width:150}, { id:"data9", header:"Currency", width:250}, { id:"data10", header:"Continent", width:250}, ], select:"row", autoheight:true, autowidth:true, datatype:"jsarray", data:[ [1,"Abkhazia","&lt;img src='32/Abkhazia.png' height=32 width=32&gt;","Sukhumi","+840", "8,660 km²","242,862 (2012)","Raul Khajimba","Abkhaz, Russian","Russian ruble, Abkhazian apsar","continent"], [2,"Afghanistan","&lt;img src='32/Afghanistan.png' height=32 width=32&gt;","Kabul","+93", "652,864 km²","30.55 million (2013)","Ashraf Ghani","Pashto, Dari","Afghan afghani","continent"], [3,"Bahamas","&lt;img src='32/Bahamas.png' height=32 width=32&gt;","Nassau","+840", "8,660 km²","242,862 (2012)","Raul Khajimba","Abkhaz, Russian","Russian ruble, Abkhazian apsar","continent"], [4,"Canada","&lt;img src='32/Canada.png' height=32 width=32&gt;","Ottawa","+840", "9.985 million km²","242,862 (2012)","Justin Trudeau","English, French","Canadian Dollar","North America"], ], on:{ "onItemClick":function(id, e, trg){ //id.column - column id //id.row - row id var item = this.getSelectedItem(id); //webix.message(id+"Click on row: " + id.row+", column: " + id.column); webix.message("item:"+item); console.log(id); var myObject = JSON.stringify(item); alert(myObject); } } }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>You are required to get the selected item from its id and then access its data members directly. Hence, in the <strong>onItemClick</strong> function you can write as:</p> <pre><code>onItemClick:function(id){ var item = this.getItem(id); //to get the selected item from its id var country = item.data1; // to access country which is data1 in your code webix.message("country:"+ country); } </code></pre> <p>Please check the snippet <a href="http://webix.com/snippet/e576edbe" rel="nofollow">here</a>.</p>
How to hide images based on src 301 redirect URL attribute? <p>I can hide all images with matching src attribute using a CSS3 attribute selector. For example:</p> <pre><code>img[src*="photo_unavailable"] { display: none; } </code></pre> <p>will hide images with src containing "photo_unavailable".</p> <p>However, what about an image like this:</p> <pre><code>https://farm7.static.flickr.com/6180/6172064687_834c859b5c_b.jpg </code></pre> <p>which redirects to:</p> <pre><code>https://s.yimg.com/pw/images/en-us/photo_unavailable_l.png </code></pre> <p>Is there a way to hide the image based on a string "photo_unavailable" found in the redirected src?</p>
<p>No, that is not possible. Because the <code>src</code> attribute correspond to the "broken" image link, not the "photo_unavailable" link.</p>
create new dataframe from missing values <p>Consider a vector x:</p> <pre><code>x &lt;- c(0, 5, 10, 25, 30) </code></pre> <p>I would like to create a new vector with "missing values," which means all the values that were "skipped" if I were to have a sequence with intervals of 5.</p> <p>So for this example, the output shouldbe:</p> <pre><code>xna &lt;- c(15, 20) </code></pre> <p>Additionally, I would have to make a function so that I can do this to any vector x.</p> <pre><code>nats &lt;- function(x){ lastvalue &lt;- x[length(x)] firstvalue &lt;-x[1] xseq &lt;- seq(firstvalue, lastvalue, 5) for i in xseq { # if x is not in x seq put it into a vecotr xna # } xna } </code></pre> <p>I really have no idea how to do this. Would really appreciate suggestions or if there is already a function that can do this.</p> <p>Please help,</p>
<p>If you need as a function, </p> <pre><code>nats &lt;- function(x, interval){ lastvalue &lt;- x[length(x)] firstvalue &lt;-x[1] xseq &lt;- seq(firstvalue, lastvalue, interval) xna &lt;- xseq[!xseq %in% x] return(xna) } x &lt;- c(0,5,10, 15,25,30) nats(x, 5) #[1] 20 x &lt;- c(3, 6,18) nats(x, 3) #[1] 9 12 15 </code></pre>
How do convert an enum int value to a string in ionic template <p>I have a template in AngularJS that has the following content</p> <pre><code>&lt;li&gt;{{item.Day }},{{item.Time}},{{item.Notes}}&lt;/li&gt; </code></pre> <p>Problem is that <code>item.Day</code> is an int from <code>0</code> to <code>6</code>, representing the javascript <code>Date</code> equivalent for a day, i.e. <code>0=Sunday, 1= Monday...6=Saturday</code>. </p> <p>Now I would like by view to show <code>Sun</code>, <code>Mon</code>..etc.. rather than <code>1,2,3</code> etc.. </p> <p>How can I do that in ionic? </p> <p>I am using <code>linq-js</code> to generate the data, however I'm not sure how to convert it there so I'm open to a solution in the controller, but ideally in the template view. </p> <p>For completeness, controller code is here: </p> <pre><code>var data = $linq(allMassTimesData); // get mass times of just this church.. var val = data.where("x =&gt; x.ShopID == " + selectedShopID ) .orderBy(function (x) { return x.Day; }) </code></pre>
<p>Why don't You just use it like this, First create a array object for days in string like</p> <p><code>$scope.days=['Sun','Mon','tue','Wed','Thur','Fri','Sat'];</code></p> <p>Then in your template just use</p> <pre><code>&lt;li&gt;{{days[item.Day]}},{{item.Time}},{{item.Notes}}&lt;/li&gt; </code></pre> <p>Thanks</p>
Google Maps: Unable to add auto search options in map contains marks from database <p>I am trying to add store markers from database in Google map, and auto search option to zoom the particular location.</p> <p>I am able to add markers from database, but i am unable to add auto search options in map contains marks from database.</p> <pre><code> &lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Maplocator.aspx.cs" Inherits="Maplocator" %&gt; &lt;!DOCTYPE html&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;Show/Add multiple markers to Google Maps from database in asp.net website&lt;/title&gt; &lt;style type="text/css"&gt; html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map_canvas { height: 100% } &lt;/style&gt; &lt;script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MyKey&amp;sensor=false"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; function initialize() { var markers = JSON.parse('&lt;%=ConvertDataTabletoString() %&gt;'); var mapOptions = { center: new google.maps.LatLng(markers[0].lat, markers[0].lng), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); var input = (document.getElementById('txtsearch')); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); var searchBox = new google.maps.places.SearchBox((input)); for (i = 0; i &lt; markers.length; i++) { var data = markers[i] var myLatlng = new google.maps.LatLng(data.lat, data.lng); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: data.title }); (function(marker, data) { // Attaching a click event to the current marker google.maps.event.addListener(marker, "click", function(e) { infoWindow.setContent(data.Descriptions); infoWindow.open(map, marker); }); })(marker, data); google.maps.event.addListener(map, 'bounds_changed', function() { var bounds = map.getBounds(); searchBox.setBounds(bounds); }); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload="initialize()"&gt; &lt;form id="form1" runat="server"&gt; &lt;div style="width: 500px; height: 200px"&gt; &lt;/div&gt; &lt;input id="txtsearch" class="apply" type="text" placeholder="Enter Search Place e.g C# Corner Noida" /&gt; &lt;div id="map_canvas" style="width: 600px; height: 500px"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Code behind:</p> <pre><code> public string ConvertDataTabletoString() { DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,Descriptions from LocationDetails", con)) { con.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); List&lt;Dictionary&lt;string, object&gt;&gt; rows = new List&lt;Dictionary&lt;string, object&gt;&gt;(); Dictionary&lt;string, object&gt; row; foreach (DataRow dr in dt.Rows) { row = new Dictionary&lt;string, object&gt;(); foreach (DataColumn col in dt.Columns) { row.Add(col.ColumnName, dr[col]); } rows.Add(row); } return serializer.Serialize(rows); } } } </code></pre>
<p>As mentioned in <a href="https://developers.google.com/places/web-service/autocomplete#place_autocomplete_results" rel="nofollow">Place Autocomplete Results</a></p> <blockquote> <p>The Place Autocomplete response does not include the scope or alt_ids fields that you may see in search results or place details. This is because Autocomplete returns only Google-scoped place IDs. <strong>It does not return app-scoped place IDs that have not yet been accepted into the Google Places database.</strong></p> </blockquote> <p>Additionally, when you <a href="https://developers.google.com/places/web-service/add-place" rel="nofollow">add a place</a>, </p> <blockquote> <p>the new place also enters a moderation queue to be considered for Google Maps.</p> </blockquote> <p>That means, you only get to see those added markers or places in auto search option if they passed the moderation process and are being accepted into Google Places database. </p> <p><strong>Important Note:</strong></p> <blockquote> <p>To make it more likely that the place will pass the moderation process and be added to the Google Maps database, the add request should include as much information as possible. In particular, the following fields are most likely to improve the chances of passing the moderation process: phone number, address and website.</p> </blockquote>
Iterator which only ever yields a single value? <p>Some STL algorithms (and STL-like algorithms one could think up in other contexts) take their inputs via iterators. I sometimes find myself wanting to pass a (const) iterator as one of their inputs which just keeps yielding the same value (or const reference to the same value in memory). You can use that, for example, to implement <code>std::fill</code> using <code>std::copy_n</code> and <code>std::distance</code> (assuming you have the end of your target).</p> <p>So, does the standard library or one of the TS'es have this anywhere (C++17 or earlier)?</p> <p><strong>Note:</strong> I'm not talking about a const iterator, but rather an iterator which never advances and keeps yielding the same thing.</p>
<p>Just create a class implementing a <a href="http://en.cppreference.com/w/cpp/concept/ForwardIterator" rel="nofollow">forward iterator interface</a>, and whose dereference operator returns your single value.</p>
Read text or number from mobile camera <p>I don't know if is it possible to read specific text from mobile camera with Javascript. </p> <p>I'm trying to make an webapp which read a ISBN number from a book and then import it in a database. There are some websites which convert webapp into apk and I need it because I want to use the mobile camera to read ISBN and then my script goes find informations with Amazon Api etc. </p> <p>But how can I read from camera mobile please, and is it possible? :p</p>
<blockquote> <p>I don't know if is it possible to read specific text from mobile camera with Javascript.</p> </blockquote> <p>The first challenge you will have is to read the image from the mobile device camera, you can do that by using with multiple approaches, one of them is a simple</p> <pre><code>&lt;input type="file" accept="image/*;capture=camera"&gt; </code></pre> <p>Check this <a href="https://www.html5rocks.com/en/tutorials/getusermedia/intro/" rel="nofollow">reference</a> for more options</p> <blockquote> <p>I'm trying to make an webapp which read a ISBN number from a book.</p> </blockquote> <p>The second challenge will be to read the ISBN from that image. One possibility is that the ISBN is printed on books as a barcode. So you have to read that from the static image and for that you also have several approaches, one example is to use a JS bar code that works on browser, like <a href="https://serratus.github.io/quaggaJS/" rel="nofollow">quaggaJS</a></p> <p>If you ISBN is a pure text, you can use an OCR to extract (like <a href="http://tesseract.projectnaptha.com/" rel="nofollow">tesseract</a> for example) the text and use some regex to match the ISBN from the text read from the image.</p> <blockquote> <p>and then import it in a database</p> </blockquote> <p>You will need a werbserver for that that receieves the ISBN value and store it on the database. There are several solutions as services, like <a href="https://firebase.google.com/docs/database/" rel="nofollow">Firebase Database</a> for example, that will make your job much easier in the beginning. </p> <blockquote> <p>here are some websites which convert webapp into apk and I need it because I want to use the mobile camera to read ISBN</p> </blockquote> <p>Don't think you need that, everything I said so far is supposed to work on the browser just fine.</p>
Starting new Activity after finish of several Async-Tasks <p>I tried to Download and Unzip files if there is an update on a server and all works perfect. But I want to open the next Activity only after all files have been downloaded and unzipped, not when it started downloading.</p> <p>This is my Activity:</p> <pre><code>package com.example; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.WindowManager; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; public class Update extends AppCompatActivity { private ProgressDialog ringProgressDialog; private static Boolean finished = false; private String read(String fileName) { StringBuilder retString = new StringBuilder(); String zeilenumbruch = "\n"; BufferedReader reader = null; try { File file = new File(fileName); FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory().toString() + "/.example/Anleitungen/.data/Versions/" + fileName); reader = new BufferedReader(new InputStreamReader(in)); String zeile; while ((zeile = reader.readLine()) != null) { retString.append(zeile); } reader.close(); } catch (IOException ex) { Log.e(getPackageName(), ex.getMessage()); } return retString.toString(); } public static String getTextOfUrl(String uri) throws Exception { StringBuilder result = new StringBuilder(); URL url = new URL(uri); String line = null; BufferedReader reader = null; finished = false; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } finally { if (reader != null) { reader.close(); } finished = true; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); if (android.os.Build.VERSION.SDK_INT &gt; 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Updating"); wl.acquire(); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); AsyncTaskRunner runner = new AsyncTaskRunner(); runner.execute(); } private void downloadAndUnzipContent(String path, String urlPath) { String url = urlPath; DownloadFileAsync download = new DownloadFileAsync(path, this, new DownloadFileAsync.PostDownload() { @Override public void downloadDone(File file) { Log.i(getPackageName(), "file download completed"); // check unzip file now Decompress unzip = new Decompress(Update.this, file, true); unzip.unzip(); Log.i(getPackageName(), "File unzip completed"); } }); download.execute(url); } private void downloadContent(String path, String urlPath) { DownloadFileAsync download = new DownloadFileAsync(path, this, new DownloadFileAsync.PostDownload() { @Override public void downloadDone(File file) { Log.i(getPackageName(), "file download completed"); } }); download.execute(urlPath); } private class AsyncTaskRunner extends AsyncTask&lt;String, String, String&gt; { private String resp; @Override protected String doInBackground(String... params) { try { List&lt;String&gt; files = new ArrayList&lt;String&gt;(); files.add("Archiv"); files.add("Funkempfaenger"); files.add("Funkhandsender"); files.add("Funksender"); files.add("Funksensoren"); files.add("Hausautomatisierung"); files.add("Jalousieantriebe"); files.add("Rohrantriebe"); files.add("SensorenKabelgebunden"); files.add("Sonderantriebe"); files.add("Torantriebe"); files.add("Torsteuerungen"); files.add("WandgeraeteKabelgebunden"); for (int uI = 0; uI &lt; files.size(); uI++) { try { String newVersion = getTextOfUrl("http://www.example.com/zip/Versions/" + files.get(uI) + ".txt"); int nV = Integer.parseInt(newVersion); String readString = files.get(uI) + ".txt"; String oldVersion = read(readString); int iV = Integer.parseInt(oldVersion); if (iV &lt; nV) { while (!finished) { Log.i(getPackageName(), "Finished = False"); } String dlPath = Environment.getExternalStorageDirectory() + "/.example/Anleitungen/.data/" + files.get(uI) + ".zip"; String dlPath2 = Environment.getExternalStorageDirectory() + "/.example/Anleitungen/.data/Versions/" + files.get(uI) + ".txt"; downloadAndUnzipContent(dlPath, "http://www.example.com/zip/Versions/" + files.get(uI) + ".zip"); downloadContent(dlPath2, "http://www.example.com/zip/Versions/" + files.get(uI) + ".txt"); } } catch (Exception e) { e.printStackTrace(); publishProgress(e.toString()); } } } catch (Exception e) { e.printStackTrace(); } return "HI!"; } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(String result) { // execution of result of Long time consuming operation Toast.makeText(Update.this, getString(R.string.UpdateFinished), Toast.LENGTH_LONG).show(); Intent intent = new Intent(Update.this, Home.class); startActivity(intent); finish(); } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPreExecute() */ @Override protected void onPreExecute() { } /* * (non-Javadoc) * * @see android.os.AsyncTask#onProgressUpdate(Progress[]) */ @Override protected void onProgressUpdate(String... text) { Toast.makeText(Update.this, text[0], Toast.LENGTH_SHORT).show(); } } @Override public void onBackPressed() { Log.i(getPackageName(), "Back pressed"); } } </code></pre> <p>This is my <code>Decompress.class</code>:</p> <pre><code>package com.example; import android.content.Context; import android.util.Log; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class Decompress { private File _zipFile; private InputStream _zipFileStream; private Context context; private static String ROOT_LOCATION = "/sdcard"; private static final String TAG = "UNZIPUTIL"; private Boolean pathNew; public Decompress(Context context, File zipFile, Boolean path) { _zipFile = zipFile; this.context = context; pathNew = path; if (pathNew) { ROOT_LOCATION = "/sdcard/.example/Anleitungen"; } _dirChecker(""); } public Decompress(Context context, InputStream zipFile) { _zipFileStream = zipFile; this.context = context; _dirChecker(""); } public void unzip() { try { Log.i(TAG, "Starting to unzip"); InputStream fin = _zipFileStream; if(fin == null) { fin = new FileInputStream(_zipFile); } ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { Log.v(TAG, "Unzipping " + ze.getName()); if(ze.isDirectory()) { _dirChecker(ROOT_LOCATION + "/" + ze.getName()); } else { FileOutputStream fout = new FileOutputStream(new File(ROOT_LOCATION, ze.getName())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; // reading and writing while((count = zin.read(buffer)) != -1) { baos.write(buffer, 0, count); byte[] bytes = baos.toByteArray(); fout.write(bytes); baos.reset(); } fout.close(); zin.closeEntry(); } } zin.close(); Log.i(TAG, "Finished unzip"); } catch(Exception e) { Log.e(TAG, "Unzip Error", e); Toast.makeText(context, "Error while unzipping: " + e.toString(), Toast.LENGTH_LONG).show(); } } private void _dirChecker(String dir) { File f = new File(dir); Log.i(TAG, "creating dir " + dir); if(dir.length() &gt;= 0 &amp;&amp; !f.isDirectory() ) { f.mkdirs(); } } } </code></pre> <p>This is my <code>DownloadFileAsnyc.class</code>:</p> <pre><code>package com.example; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedInputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class DownloadFileAsync extends AsyncTask&lt;String, String, String&gt; { private static final String TAG ="DOWNLOADFILE"; public static final int DIALOG_DOWNLOAD_PROGRESS = 0; private PostDownload callback; private Context context; private FileDescriptor fd; private File file; private String downloadLocation; public DownloadFileAsync(String downloadLocation, Context context, PostDownload callback){ this.context = context; this.callback = callback; this.downloadLocation = downloadLocation; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... aurl) { int count; try { URL url = new URL(aurl[0]); URLConnection connection = url.openConnection(); connection.connect(); int lenghtOfFile = connection.getContentLength(); Log.d(TAG, "Length of the file: " + lenghtOfFile); InputStream input = new BufferedInputStream(url.openStream()); file = new File(downloadLocation); FileOutputStream output = new FileOutputStream(file); //context.openFileOutput("content.zip", Context.MODE_PRIVATE); Log.d(TAG, "file saved at " + file.getAbsolutePath()); fd = output.getFD(); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; publishProgress(""+(int)((total*100)/lenghtOfFile)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) {} return null; } protected void onProgressUpdate(String... progress) { //Log.d(TAG,progress[0]); } @Override protected void onPostExecute(String unused) { if(callback != null) callback.downloadDone(file); } public static interface PostDownload{ void downloadDone(File fd); } } </code></pre> <p>Please help me. Sorry for my bad English.</p> <p>Thank you.</p>
<p>You are starting the new Activity whenever AsyncTaskRunner finishes executing its background job. AsyncTaskRunner is basically just launching multiple DownloadFileAsync tasks. </p> <p>AsyncTaskRunner won't wait for the launched tasks to complete. It will just launch them and finish the task which causes your new Activity to start.</p> <p>The optimal way to fix this is to use only one AsyncTask that process each file sequentially. A <strong>dirty</strong> way would be to make AsyncTaskRunner wait for each DownloadFileAsync task to finish before launching the next. You can do this by calling the <a href="https://developer.android.com/reference/android/os/AsyncTask.html#get()" rel="nofollow">.get()</a> method on each task:</p> <pre><code>download.execute(url).get(); </code></pre> <p>But again, this defeats the purpose of AsyncTasks.</p>
How to prevent Emacs from scrolling with the mouse past the end of the buffer? <p>The default behavior is that Emacs keeps scrolling the last line to the center of the frame. How can I keep the last line at the bottom of the frame when I scroll using the mouse?</p>
<pre class="lang-lisp prettyprint-override"><code>(setq scroll-conservatively 101) </code></pre> <p>Here is the information from the <code>*Help*</code> window produced by <code>describe-variable</code>:</p> <pre><code>scroll-conservatively is a variable defined in `C source code'. Its value is 101 Original value was 0 Documentation: Scroll up to this many lines, to bring point back on screen. If point moves off-screen, redisplay will scroll by up to ‘scroll-conservatively’ lines in order to bring point just barely onto the screen again. If that cannot be done, then redisplay recenters point as usual. If the value is greater than 100, redisplay will never recenter point, but will always scroll just enough text to bring point into view, even if you move far away. A value of zero means always recenter point if it moves off screen. You can customize this variable. </code></pre>
how to compare two different XML with all tags and show the difference? <p>Expected XML</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;SOAP-ENV:Header/&gt; &lt;SOAP-ENV:Body&gt; &lt;bvoip:updateCustSiteDetailResponse xmlns:bvoip="http://dbor.att.com/bvoip/v1"&gt; &lt;bvoip:rowsAffected&gt;13&lt;/bvoip:rowsAffected&gt; &lt;bvoip:name&gt;JAK&lt;/bvoip:name&gt; &lt;/bvoip:updateCustSiteDetailResponse&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt;&lt;!-- P-V : 2016.10.21 --&gt; </code></pre> <p>TargetXML</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;SOAP-ENV:Body&gt; &lt;ns:updateCustSiteDetailResponse xmlns:ns="http://dbor.att.com/bvoip/v1"&gt; &lt;ns:rowsAffected&gt;14&lt;/ns:rowsAffected&gt; &lt;/ns:updateCustSiteDetailResponse&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>Output ------------ Expected rowsAffected 13 but rowsAffected is 14 Expected name is missing </p>
<p>There are 2 options</p> <p>a) Use a library like XMLUnit , get the differences and ignore the namespaces and compare text values</p> <p>b) Rollout a difference comparator of your own. If there only a specific tag you need to compare (and you do not want additional dependencies or JAXP) you can use this approach.</p> <pre><code>public static void main(String[] args) throws XPathExpressionException { String controlXML = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt; &lt;SOAP-ENV:Header/&gt; &lt;SOAP-ENV:Body&gt; &lt;bvoip:updateCustSiteDetailResponse xmlns:bvoip=\"http://dbor.att.com/bvoip/v1\"&gt;&lt;bvoip:rowsAffected&gt;13&lt;/bvoip:rowsAffected&gt;&lt;bvoip:name&gt;JAK&lt;/bvoip:name&gt;&lt;/bvoip:updateCustSiteDetailResponse&gt; &lt;/SOAP-ENV:Body&gt;&lt;/SOAP-ENV:Envelope&gt;"; String resultXML = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt; &lt;SOAP-ENV:Body&gt;&lt;ns:updateCustSiteDetailResponse xmlns:ns=\"http://dbor.att.com/bvoip/v1\"&gt; &lt;ns:rowsAffected&gt;14&lt;/ns:rowsAffected&gt; &lt;/ns:updateCustSiteDetailResponse&gt; &lt;/SOAP-ENV:Body&gt;&lt;/SOAP-ENV:Envelope&gt;"; String xPath = "//*[local-name()='rowsAffected']"; XPath xPathFactory = XPathFactory.newInstance().newXPath(); Document controlDocument = getXMLDocument(controlXML); Document resultDocument = getXMLDocument(resultXML); Assert.assertEquals(xPathFactory.compile(xPath).evaluate(controlDocument), xPathFactory.compile(xPath).evaluate(resultDocument)); } static private Document getXMLDocument(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document document = null; try { builder = factory.newDocumentBuilder(); document = builder.parse(new InputSource(new StringReader(xml))); } catch (Exception e) { e.printStackTrace(); } return document; } </code></pre> <p>The above code fails the assertion as expected and gives me the result</p> <pre><code>Exception in thread "main" junit.framework.ComparisonFailure: The text nodes do not match expected:&lt;1[3]&gt; but was:&lt;1[4]&gt; at junit.framework.Assert.assertEquals(Assert.java:81) at org.ram.so.SOProject.XMLCompare.main(XMLCompare.java:26) </code></pre>
Weird behaviour when running the script <p>I started to code a guess the number type of game. When I execute the program, it either flows perfectly, either doesn't work...</p> <pre><code>import random from random import randint print("Welcome to guess the number!\nDo you want to play the game?") question = input("") if question == "Yes".lower(): print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = int(input("Take a guess!\n")) if guess &gt; number: print("Your guess is too high") guess = int(input("Take a guess!\n")) if guess &lt; number: print("Your guess is too low") guess = int(input("Take a guess!\n")) if guess == number: print("Your guess was correct!") elif question == "No".lower(): print("Too bad! Bye!") quit() </code></pre> <p>I absolutely no idea whether it happens because of the code, or pycharm is to blame! </p>
<p>You really need a while loop. If the first guess is too high then you get another chance, but it then only tests to see if it is too low or equal. If your guess is too low then your second chance has to be correct.</p> <p>So you don't need to keep testing, you can simplify, but you should really do this at the design stage. Here is my version:</p> <pre><code>import random # from random import randint &lt;&lt; no need for this line print("Welcome to guess the number!") question = input("Do you want to play the game? ") if question.lower() == "yes": print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = None # This initialises the variable while guess != number: # This allows continual guesses guess = int(input("Take a guess!: ")) # Only need one of these if guess &gt; number: print("Your guess is too high") elif guess &lt; number: print("Your guess is too low") else: # if it isn't &lt; or &gt; then it must be equal! print("Your guess was correct!") else: # why do another test? No need. print("Too bad! Bye!") # No need for quit - program will exit anyway # but you should not use quit() in a program # use sys.exit() instead </code></pre> <p>Now I suggest you add a count of the number of guesses the player has before they get it right, and print that at the end!</p> <p>Edit: You will note that my <code>import</code> statement differs from that given by @Denis Ismailaj. We both agree that only one <code>import</code> is required, but hold different opinions as to which one. In my version I <code>import random</code>, this means that you have to say <code>random.randint</code> whereas in the other you only say <code>randint</code>.</p> <p>In a small program there isn't much to choose between them, but programs never get smaller. A larger program, which could easily be importing 6,7,8 or more modules, it is sometimes difficult to track-down which module a function comes from - this is known as <em>namespace pollution</em>. There will be no confusion with a well-known function like <code>randint</code>, and if you explicitly give the name of the function then it can easily be tracked back. It is only a question of personal preference and style.</p> <p>With number of guesses added:</p> <pre><code>import random print("Welcome to guess the number!") question = input("Do you want to play the game? ") if question.lower() == "yes": print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = None nrGuesses = 0 # Added # Allow for continual guesses while guess != number and nrGuesses &lt; 6: # Changed guess = int(input("Take a guess!: ")) # Only need one of these nrGuesses += 1 # Added if guess &gt; number: print("Your guess is too high") elif guess &lt; number: print("Your guess is too low") else: # if it isn't &lt; or &gt; then it must be equal! print("Your guess was correct!") else: print("Too bad! Bye!") print("Number of guesses:", nrGuesses) # Added </code></pre>
How to clear out commit history when submiting a PR on GitHub? <p>I'm new to Git. On GitHub, I forked a third-party project to make contributions to. Every time new PRs are merged to its master, I have to update my fork to stay current. On the home page of my forked repository, I click <code>New pull request</code>, swap base and head forks, create a new PR, and merge it to my own copy. </p> <p>However, I noticed this is creating an increasingly large list of commits in the commit history every time I submit a PR. How do I consolidate all those commits into one before or after I submit a PR? I'm using Visual Studio 2015.</p> <p>I think I need to squash commits, but I don't know how to do that on VS.</p>
<p>You shouldn't squash or use pull requests, instead add the remote for the original repo to your project and then you can rebase on top of their latest code.</p> <pre><code> git remote add theirs https://www.github.com/original/project.git git fetch theirs </code></pre> <p>Now in Visual Studio (or from the command line) you can right click the theirs/master branch and select <kbd>rebase onto</kbd>. This will rewrite your local history and will replay your changes on top of their latest code. </p> <p>It may be required to force push to your own github fork, because rebasing causes your local git commit-ids to change in some cases. You may have to merge changes as the rebase takes place, since their latest version will be leading and your local commits will be replayed on top of the latest version of their code.</p> <p>This process will give you the cleanest history that will include their latest changes. </p> <p>If the rebase/force-push daunts you, it's also possible to do a normal merge from theirs/master into your local branch. Make sure to fetch the latest changes from theirs after adding the remote and then you can right click their master branch in Visual Studio and select "Merge into" to merge their changes into your local working directory. </p>
A protocol message was rejected because it was too big (more than 67108864 bytes) on mesos <p>Kmeans on spark by mesos 16/10/15 19:10:41 WARN TaskSetManager: Stage 54 contains a task of very large size (212070 KB). The maximum recommended task size is 100 KB.</p> <pre><code>[Stage 54:&gt; (0 + 1) / 10]`` [Stage 54:&gt; (0 + 2) / 10] [Stage 54:&gt; (0 + 3) / 10] [Stage 54:&gt; (0 + 4) / 10] [Stage 54:&gt; (0 + 5) / 10] [Stage 54:&gt; (0 + 6) / 10] [Stage 54:&gt; (0 + 7) / 10] [Stage 54:&gt; (0 + 8) / 10] [Stage 54:&gt; (0 + 9) / 10] [Stage 54:&gt; (0 + 10) / 10][libprotobuf ERROR google/protobuf/io/coded_stream.cc:180] A protocol message was rejected because it was too big (more than 67108864 bytes). To increase the limit (or to disable these warnings), see CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h. F1015 19:10:48.392988 25634 construct.cpp:46] Check failed: parsed Unexpected failure while parsing protobuf *** Check failure stack trace: *** @ 0x7fa3dab98d18 google::LogMessage::Fail() @ 0x7fa3dab98c67 google::LogMessage::SendToLog() @ 0x7fa3dab98678 google::LogMessage::Flush() @ 0x7fa3dab9b3ac google::LogMessageFatal::~LogMessageFatal() @ 0x7fa3dab7f68b parse&lt;&gt;() @ 0x7fa3dab7e274 construct&lt;&gt;() @ 0x7fa3dab865d4 Java_org_apache_mesos_MesosSchedulerDriver_launchTasks__Ljava_util_Collection_2Ljava_util_Collection_2Lorg_apache_mesos_Protos_00024Filters_2 @ 0x7fa4d90127f8 (unknown) </code></pre>
<p>bin/spark-submit --name com.yonyou.ml.idfkmeans.SalesPurchasingKmeans --master mesos://zk://10.251.177.219:2181,10.163.122.93:2181,10.251.131.33:2181,10.174.236.104:2181,10.163.170.192:2181,10.164.14.172:2181/mesos --driver-cores 5.0 --driver-memory 30720M --class com.yonyou.ml.idfkmeans.SalesPurchasingKmeans --executor-memory 25G --conf spark.executor.extraJavaOptions="-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:MaxDirectMemorySize=6g" --conf spark.driver.maxResultSize=6000m --conf spark.kryoserializer.buffer.max=2047m --conf spark.driver.supervise=false --conf spark.app.name=com.yonyou.ml.idfkmeans.SalesPurchasingKmeans --conf spark.driver.memory=30g --conf spark.default.parallelism=10 --conf spark.kryoserializer.buffer=2000m --conf spark.driver.cores=5 --conf spark.mesos.coarse=false --conf spark.executor.memory=25G ../ml-kmeans_kmeans_test_8000_10000.jar</p>
Dictionary removing duplicate along with subtraction and addition of values <p>New to python here. I would like to eliminate duplicate dictionary key into just one along with performing arithmetic such as adding/subtracting the values if duplicates are found.</p> <p><strong>Current Code Output</strong></p> <blockquote> <p>{('GRILLED AUSTRALIA ANGU',): (('1',), ('29.00',)), ('Beer', 'Carrot Cake', 'Chocolate Cake'): (('10', '1', '1'), ('30.00', '2.50', '3.50')), ('<strong>Beer</strong>', '<strong>Beer</strong>'): (('<strong>1</strong>', '<strong>1</strong>'), ('<strong>3.00</strong>', '<strong>3.00</strong>')), ('Carrot Cake', 'Chocolate Cake'): (('1', '1'), ('2.50', '3.50')), ('Carrot Cake',): (('1',), ('2.50',)), ('BRAISED BEANCURD WITH',): (('1',), ('10.00',)), ('SAUSAGE WRAPPED WITH B', 'ESCARGOT WITH GARLIC H', 'PAN SEARED FOIE GRAS', 'SAUTE FIELD MUSHROOM W', 'CRISPY CHICKEN WINGS', 'ONION RINGS'): (('1', '1', '1', '1', '1', '1'), ('10.00', '12.00', '15.00', '9.00', '7.00', '6.00')), ('<strong>Beer</strong>', '<strong>Beer</strong>', '<strong>Carrot Cake</strong>', '<strong>Chocolate Cake</strong>'): (('<strong>-1</strong>', '<strong>10</strong>', '<strong>1</strong>', '<strong>1</strong>'), ('<strong>-3.00</strong>', '<strong>30.00</strong>', '<strong>2.50</strong>', '<strong>3.50</strong>')), ('Beer',): (('10',), ('30.00',))}</p> </blockquote> <p>What i want: example:</p> <p><strong>SUBTRACTION FOR DUPLICATE</strong></p> <blockquote> <p>{'Beer': [9, 27]} , {'carrot cake': [1, 2.5]} , {'Chocolate Cake': [1, 3.5]} </p> </blockquote> <p>notice that for duplicate item entry i trimmed Beer into one along with (10-1=9) for quantity amount and (30-3=27) for the cost. How do i automate this process?</p> <p><strong>ADDITION FOR DUPLICATE</strong></p> <blockquote> <p>{'Beer': [2, 6]}</p> </blockquote> <p>notice that I added beer and beer into one entry and along with the quantity (1+1) and cost (3+3=6)</p> <p><strong>My code:</strong></p> <pre><code>import csv from itertools import groupby from operator import itemgetter import re d = {} #open directory and saving directory with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out: reader = csv.reader(f) next(reader) writer = csv.writer(out) #the first column header writer.writerow(["item","quantity","amount"]) groups = groupby(csv.reader(f), key=itemgetter(0)) for k, v in groups: v = list(v) sales= [ x[1] for x in v[8:] ] salesstring= str(sales) #using re.findall instead of re.search to return all via regex for items itemoutput= re.findall(r"(?&lt;=\s\s)\w+(?:\s\w+)*(?=\s\s)",textwordfortransaction) #using re.findall instead of re.search to return all via regex for amount aka quantity amountoutput= re.findall(r"'(-?\d+)\s+(?:[A-Za-z ]*)",textwordfortransaction) #using re.findall instead of re.search to return all via regex for cost costoutput= re.findall(r"(?:'-?\d+[A-Za-z ]*)(-?\d+[.]?\d*)",textwordfortransaction) d[tuple(itemoutput)] = tuple(amountoutput),tuple(costoutput) #writing the DATA to output CSV writer.writerow([d]) #to remove the last entry else it would keep on stacking the previous d.clear() </code></pre> <p>link to csv file if needed <a href="https://drive.google.com/open?id=0B1kSBxOGO4uJOFVZSWh2NWx6dHc" rel="nofollow">https://drive.google.com/open?id=0B1kSBxOGO4uJOFVZSWh2NWx6dHc</a></p>
<p>Working with your current output as posted in the question, you can just <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> the different lists of tuples of items and quantities and prices to align the items with each other, add them up in two <code>defaultdicts</code>, and finally combine those to the result.</p> <pre><code>output = {('GRILLED AUSTRALIA ANGU',): (('1',), ('29.00',)), ...} from collections import defaultdict prices, quantities = defaultdict(int), defaultdict(int) for key, val in output.items(): for item, quant, price in zip(key, *val): quantities[item] += int(quant) prices[item] += float(price) result = {item: (quantities[item], prices[item]) for item in prices} </code></pre> <p>Afterwards, <code>result</code> is this: Note that you do <em>not</em> need a special case for subtracting duplicates when the quantity and/or price are negative; just add the negative number.</p> <pre><code>{'ESCARGOT WITH GARLIC H': (1, 12.0), 'BRAISED BEANCURD WITH': (1, 10.0), 'CRISPY CHICKEN WINGS': (1, 7.0), 'SAUSAGE WRAPPED WITH B': (1, 10.0), 'ONION RINGS': (1, 6.0), 'PAN SEARED FOIE GRAS': (1, 15.0), 'Beer': (31, 93.0), 'Chocolate Cake': (3, 10.5), 'SAUTE FIELD MUSHROOM W': (1, 9.0), 'Carrot Cake': (4, 10.0), 'GRILLED AUSTRALIA ANGU': (1, 29.0)} </code></pre> <hr> <p>If you want to keep the individual items separate, just move the declaration of <code>prices</code>, <code>quantities</code>, and <code>result</code> <em>inside</em> the outer loop:</p> <pre><code>for key, val in output.items(): prices, quantities = defaultdict(int), defaultdict(int) for item, quant, price in zip(key, *val): quantities[item] += int(quant) prices[item] += float(price) result = {item: (quantities[item], prices[item]) for item in prices} # do something with result or collect in a list </code></pre> <p>Example result for the two-beer line: </p> <pre><code>('Beer', 'Beer', 'Carrot Cake', 'Chocolate Cake') (('-1', '10', '1', '1'), ('-3.00', '30.00', '2.50', '3.50')) {'Chocolate Cake': (1, 3.5), 'Beer': (9, 27.0), 'Carrot Cake': (1, 2.5)} </code></pre> <p>If you prefer the <code>result</code> to group the items, quantities and prices together, use this:</p> <pre><code>items = list(prices) result = (items, [quantities[x] for x in items], [prices[x] for x in items]) </code></pre> <p>Result is this like this:</p> <pre><code>(['Carrot Cake', 'Beer', 'Chocolate Cake'], [1, 9, 1], [2.5, 27.0, 3.5]) </code></pre>
How the relevant part of the report sent to relevant party using SSRS <p>Sales report should be sent to all the relevant department heads. Ex: Plastic department should get only the plastic department sales while garment department should receive only its department data. How to accomplish this requirement using SSRS?</p>
<p>This is what I would to, and it is an easy approach. Plus, no Enterprise Edition needed for this.</p> <p>Add a department parameter to the report, and make sure the data uses the parameter value to filter the results, whether that is done at the dataset level (filtering the data at the database level in the <code>WHERE</code> clause), or using the filter in a Tablix (in the tablix properties, on the Filter page). </p> <p><a href="https://technet.microsoft.com/en-us/library/aa337432(v=sql.105).aspx" rel="nofollow">Adding Parameters to a Report (SSRS)</a></p> <p>The parameter filter would apply to the whole report, unless you use the value to show/hide parts of the report. With report subscriptions, you get the whole report, not just a part. Your question title makes me think you only want a part of the report to be delivered, and that is not possible.</p> <p>Then, when you set up a report subscription, choose the appropriate department depending on the recipients.</p> <p><a href="https://msdn.microsoft.com/en-us/library/ms157386(v=sql.105).aspx" rel="nofollow">How to: Subscribe to a Report</a></p> <p>This way, when a another department comes along that wants the report, then you can just create a new subscription, and you're done.</p>
How to change toolbar color on button click? <p>I have a app with a button and a Tool bar. I want to change the Tool bar color when button clicked. I don't want to launch any other activity, I just want when user click button the color of my Toolbar get changes.</p>
<p>Try this</p> <p><code>getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorAccent)));</code></p> <p>To change color of status bar you should add this code:</p> <pre><code>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.BLUE); } </code></pre>
Spring rest resource change path <p>I currently have a repository annotated with <code>@RepositoryRestResource</code>. I'm adding the following: </p> <pre><code>@RestResource(path="make", rel = "make", description = @Description("Get vehicles by make")) List&lt;Vehicle&gt; findByMake(@Param("make") String make); </code></pre> <p>This works fine but the path by default is <code>api/vehicles/search/make</code>.</p> <p>How can I remove the <code>/search</code> part and just have the path be <code>api/vehicles/make</code>?</p>
<p>Unfortunately it's not possible. I make some research in Spring Data Rest source code.</p> <p>There are constants that uses for URI building in <a href="https://github.com/spring-projects/spring-data-rest/blob/master/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java#L73-L74" rel="nofollow"><code>RepositorySearchController.java</code></a>:</p> <pre><code>private static final String SEARCH = "/search"; private static final String BASE_MAPPING = "/{repository}" + SEARCH; </code></pre> <p>And <strong><a href="https://github.com/spring-projects/spring-data-rest/blob/master/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositorySearchController.java#L170-L184" rel="nofollow">here</a></strong> is the action method that handle requests by services with <code>@RepositoryRestResource</code> annotation. So as you can see the <code>search</code> part is hardcoded and couldn't be changed.</p>
Complex JSON structure and databinding in NativeScript ListView <p>I have an interesting data set being returned from an API and I can't resolve the binding in the NativeScript listview for an object of objects within the parent binding context. The listview <code>items</code> (feeditems) is an ObservableArray(). Everything is working fine I'm just stumped on repeating the <code>feeds</code> object (which could have more than one item) in the <code>styles</code> object which is accessible and the other items accessing the parent bindingContext work fine.</p> <pre class="lang-xml prettyprint-override"><code>&lt;lv:RadListView items="{{ feedItems }}"&gt; &lt;lv:RadListView.itemTemplate&gt; &lt;GridLayout rows="auto, *, auto" columns="70, *, auto" class="feed-item"&gt; &lt;!-- Title and Description --&gt; &lt;Label text="{{ title }}" color="{{ $parents['RadListView'].styles[site_id]['entry_title_color'], $parents['RadListView'].styles[site_id]['entry_title_color'] }}" /&gt; &lt;Label text="&amp;#xf397;" color="{{ $parents['RadListView'].styles[site_id]['entry_btn_color'], $parents['RadListView'].styles[site_id]['entry_btn_color'] }}" /&gt; &lt;!-- Feed Image --&gt; &lt;Image src="{{ image }}" stretch="aspectFit" /&gt; &lt;!-- Details Row --&gt; &lt;!-- STUCK HERE TRYING TO REPEAT THE 'FEEDS' OBJECT --&gt; &lt;Repeater items="{{ $parents['RadListView'].styles[site_id]['feeds'], $parents['RadListView'].styles[site_id]['feeds'] }}"&gt; &lt;Repeater.itemTemplate&gt; &lt;Label text="{{ icon }}" /&gt; &lt;/Repeater.itemTemplate&gt; &lt;/Repeater&gt; &lt;Label text="{{ friendlytime }}" /&gt; &lt;/GridLayout&gt; &lt;/lv:RadListView.itemTemplate&gt; &lt;/lv:RadListView&gt; </code></pre> <p>Here is a sample of the <code>styles</code> JSON binded: </p> <pre><code>{"2": {"id":2,"name":"TEST","icon":"https://www.TEST.com/test.png", "entry_title_color":"#f00","entry_text_primary_color":"#3AF", "feeds": {"2": {"id":2,"type":"rss","icon":"","notify":1} } } } </code></pre>
<p>I don't see 'site_id' defined in the styles JSON. So probably just skipping the '[site_id]' part would be enough.</p> <p>And one off-topic: please remove the <strong>StackLayouts</strong> you don't need them. </p>
How to add an Integer object, and an Object, in Java? <p>I have to add two objects, one of type Integer, and the other of type ArrayList(i). Here is the function I am working on, I will need to find the average of the array. The error I get is: error: bad operand types for binary operator '+', for the line 7 here. That sum is of type Integer and a.get(i) is of type Object.</p> <pre><code> public static int brojDoProsek(ArrayList a){ //Code here... double average = 0.0; Integer sum = new Integer(0); for(int i = 0; i &lt; a.size(); i++){ sum = sum + a.get(i); } average = sum / a.size(); return 0; } </code></pre>
<pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Array&lt;E&gt; { public static int brojDoProsek(ArrayList a){ //Code here... double average = 0.0; Integer sum = new Integer(0); for(int i = 0; i &lt; a.size(); i++){ //sum = sum + a.get(i); } average = sum / a.size(); return 0; } public static void main(String[] args) throws IOException{ BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String s = stdin.readLine(); int N = Integer.parseInt(s); //Code here... ArrayList &lt;Integer&gt; niza = new ArrayList&lt;Integer&gt;(N); String b; for(int i = 0; i &lt; N; i++){ b = stdin.readLine(); int temp = Integer.parseInt(b); niza.add(i, temp); } System.out.println(brojDoProsek(niza)); } </code></pre> <p>}</p>
code igniter $this->form_validation->run() always returns false <pre><code> function form_submit (){ $this-&gt;load-&gt;library('form_validation'); $this-&gt;form_validation-&gt;set_rules('cname', 'Company Name', 'required'); $this-&gt;form_validation-&gt;set_rules('cpname', 'Contact Person Name', 'required'); $this-&gt;form_validation-&gt;set_rules('add1', 'Address Line 1 ', 'required'); if($this-&gt;form_validation-&gt;run() == TRUE) { echo 'sucess'; } else { echo validation_errors(); } } </code></pre> <p>here is my form</p> <pre><code> &lt;form id="form_sub" action="controller/form_submit"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6"&gt; &lt;label&gt;Company Name &lt;span&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input name="cname" type="text" value="" maxlength="100" /&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;label&gt;Contact Person &lt;span&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input name="cpname" type="text" value="" maxlength="100" /&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;label&gt;Address Line 1 &lt;span&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input name="add1" type="text" value="" maxlength="100" /&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;input type="submit" value="submit" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>All the time $this->form_validation->run() is returning false . What am i missing here , even if i give correct values and submit the form it gives error </p>
<p>You missed the <code>method</code> attribute in form tag. It should be </p> <pre><code>&lt;form id="form_sub" action="&lt;?php echo site_url('controller/form_submit');?&gt;" method="POST"&gt; </code></pre>
ruby : shoes installed but hello world program doesn not work <p>I installed shoes gem but I can't use it:</p> <pre><code>&gt; gem install green_shoes Successfully installed green_shoes-1.1.374 Parsing documentation for green_shoes-1.1.374 unable to convert "\xA9" from ASCII-8BIT to UTF-8 for lib/shoes/minitar.rb, skipping Done installing documentation for green_shoes after 1 seconds 1 gem installed olivier@FIXE C:\Users\olivier\Documents\ruby &gt; irb irb(main):001:0&gt; require 'green_shoes' LoadError: cannot load such file -- gobject-introspection from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/gdk_pixbuf2-3.0.9-x64-mingw32/lib/gdk_pixbuf2.rb:17:in `&lt;top (require d)&gt;' from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/green_shoes-1.1.374/lib/green_shoes.rb:5:in `&lt;top (required)&gt;' from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:133:in `require' from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:133:in `rescue in require' from C:/Ruby23-x64/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require' from (irb):1 from C:/Ruby23-x64/bin/irb.cmd:19:in `&lt;main&gt;' </code></pre> <p>can someone help me fix this issue?</p> <p>thank you</p> <p>olivier </p> <h2>EDIT:</h2> <p>I installed the 2 gems, but a simple demo program (which begins with "require 'green_shoes'", gives this error : </p> <blockquote> <blockquote> <p>ruby test1.rb C:/Ruby23/lib/ruby/site_ruby/2.3.0/rubygems/specification.rb:2288:in `raise_if_conflicts': Unable to activate gobject-introspection-3.0.8-x86-mingw32, because glib2-3.0.9-x86-mingw32 conflicts with glib2 (= 3.0.8) (Gem::ConflictError)</p> </blockquote> </blockquote> <p>here is the program:</p> <pre><code>require 'green_shoes' puts "hello world" puts Math.sqrt(9) def say_hi(name="!") puts "hello world #{name}" end say_hi("Olivier") say_hi class Greeter def initialize(name) @name=name end def say_hello puts "hello #{@name.capitalize}" end def to_s "I said hello!" end end g=Greeter.new("olivier") g.say_hello puts g # hello_world.rb Shoes.app do para "Hello World" end Shoes.app { button "Push me" } </code></pre> <p>it's a test program, it does not contain important things.</p> <p>olivier</p> <p>ps: I understand the conflict between the 2 versions of glib2, but I hesitate about which version to remove : I don't want to break my ruby installation. Which should I remove? </p> <h2>EDIT2:</h2> <p>there's still an issue : green_shoes requires the installation of pango and cairo, but of other versions that 3.0.8 :</p> <blockquote> <blockquote> <p>gem uninstall glib2 -v 3.0.9<br> You have requested to uninstall the gem:<br> glib2-3.0.9-x86-mingw32<br> atk-3.0.9 depends on glib2 (= 3.0.9)<br> gdk_pixbuf2-3.0.9 depends on glib2 (= 3.0.9)<br> pango-3.0.9 depends on glib2 (= 3.0.9) If you remove this gem, these dependencies will not be met.</p> </blockquote> </blockquote> <p>I don't know how I should do... which version of green_shoes have you got?</p> <p>thanks</p> <p>olivier </p> <p>ps: I just saw the rest of your edit; the strabge thing is that I have got the same version of green_shoes than yours...but for me was installed glib2-3.0.9, and for you glib2 3.0.8.... I thought at remove green_shoes, and its dependencies, then install some dependencies in 3.0.8 version, then install green_shoes and hope it does not requires 3.0.9 versions of its dependencies no more... What do you think about that?</p> <h2>EDIT3:</h2> <p>snif! it's what I was afraid of!</p> <p>here is the result of the installation of green_shoes:</p> <pre><code> &gt; gem install green_shoes Fetching: glib2-3.0.9-x86-mingw32.gem (100%) Successfully installed glib2-3.0.9-x86-mingw32 Fetching: green_shoes-1.1.374.gem (100%) Successfully installed green_shoes-1.1.374 </code></pre> <p>and now I have the 2 versions of glib2(3.0.8 &amp; 3.0.9)</p> <h2>EDIT4:</h2> <p>I don't understand anything : have a look at this:</p> <blockquote> <blockquote> <p>gem list glib2 </p> </blockquote> <p><strong>* LOCAL GEMS *</strong> glib2 (3.0.9 x86-mingw32)<br> olivier@FIXE C:\Users\olivier\Documents\ruby </p> <blockquote> <p>ruby test2.rb C:/Ruby23/lib/ruby/site_ruby/2.3.0/rubygems/specification.rb:2288:in `raise_if_conflic ts': Unable to activate gobject-introspection-3.0.8-x86-mingw32, because glib2-3.0.9-x 86-mingw32 conflicts with glib2 (= 3.0.8) (Gem::ConflictError)</p> </blockquote> </blockquote> <p>I removed glib2 v 3.0.8 but there is still a conflict... </p> <h2>EDIT5:</h2> <p>I followed your advice, and removed version 3.0.9, but strangely it seems that version 3.0.8 is still needed:</p> <blockquote> <blockquote> <p>ruby test2.rb C:/Ruby23/lib/ruby/site_ruby/2.3.0/rubygems/dependency.rb:310:in <code>to_specs': Could not find 'glib2' (= 3.0.9) - did find: [glib2-3.0.8-x86-mingw32] (Gem::MissingSpecVersionError) Checked in 'GEM_PATH=C:/Users/olivier/.gem/ruby/2.3.0;C:/Ruby23/lib/ruby/gems/2.3.0', execute</code>gem env` for more information</p> </blockquote> </blockquote> <p>althought I removed its 3.0.8 dependencies, and let the 3.0.9 stay. still, I don't understand</p>
<p>I recently reïnstalled green_shoes under Windows7 and Ruby 2.3.0 and had no difficulties, here the gdk versions that are used on my system. Install them seperate while specifying this version. Don't know if necessary here but it is always advisable to have the devkit in your path.</p> <p>Versions:</p> <pre><code>gdk3 (3.0.8 x64-mingw32) gdk_pixbuf2 (3.0.8 x64-mingw32) </code></pre> <p>Install them by</p> <pre><code>gem install gdk3 -v 3.0.8 gem install gdk_pixbuf2 -v 3.0.8 </code></pre> <p>EDIT</p> <p>My glib version is as follows, i suggest you check your current version with <code>gem list glib2</code>, note it down, install my version and if things break you can always gem uninstall glib2 and reinstall the old version.</p> <pre><code>glib2 (3.0.8 x64-mingw32) </code></pre> <p>The following command should list all the dependencies but doesn't seem to recurse so let me know if I need to go any deeper.</p> <pre><code>C:\Users\Gebruiker&gt;gem dependency green_shoes --reverse-dependencies Gem green_shoes-1.1.374 gtk2 (&gt;= 0) C:\Users\Gebruiker&gt;gem dependency gtk2 --reverse-dependencies Gem gtk2-3.0.8-x64-mingw32 atk (= 3.0.8) gdk_pixbuf2 (= 3.0.8) pango (= 3.0.8) Used by green_shoes-1.1.374 (gtk2 (&gt;= 0)) Gem pango-3.0.8-x64-mingw32 cairo (&gt;= 1.14.0) glib2 (= 3.0.8) Used by gdk3-3.0.8-x64-mingw32 (pango (= 3.0.8)) gtk2-3.0.8-x64-mingw32 (pango (= 3.0.8)) gtk3-3.0.8-x64-mingw32 (pango (= 3.0.8)) rsvg2-3.0.8-x64-mingw32 (pango (&gt;= 3.0.8)) </code></pre> <p>EDIT2</p> <p>I managed to get a full dependecy tree by using <a href="http://stackoverflow.com/questions/21108109/how-do-i-find-out-all-the-dependencies-of-a-gem">this</a> answer</p> <pre><code>{"green_shoes 1.1.374"=&gt; {"gtk2 3.0.8"=&gt; {"gtk2 3.0.8"=&gt; {"atk 3.0.8"=&gt; {"atk 3.0.8"=&gt; {"glib2 3.0.8"=&gt; {"glib2 3.0.8"=&gt; {"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}, "cairo 1.15.2"=&gt; {"cairo 1.15.2"=&gt; {"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}}}}}}}, "pango 3.0.8"=&gt; {"pango 3.0.8"=&gt; {"cairo 1.15.2"=&gt; {"cairo 1.15.2"=&gt;{"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}}}, "glib2 3.0.8"=&gt; {"glib2 3.0.8"=&gt; {"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}, "cairo 1.15.2"=&gt; {"cairo 1.15.2"=&gt; {"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}}}}}}}, "gdk_pixbuf2 3.0.8"=&gt; {"gdk_pixbuf2 3.0.8"=&gt; {"glib2 3.0.8"=&gt; {"glib2 3.0.8"=&gt; {"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}, "cairo 1.15.2"=&gt; {"cairo 1.15.2"=&gt; {"pkg-config 1.1.7"=&gt;{"pkg-config 1.1.7"=&gt;{}}}}}}}}}}}} </code></pre>
Why won't my text align with my image? <p>I want my logo, my description text and my nav bar to all sit along the same line at the top of my site. They won't align and I can't for the life of my figure out why. They are all on the same line, but the description text is sitting lower than the rest. Padding and margins don't seem to be making a difference.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Title Area */ #title { float: left; } .sep { padding: 20px; } .desc { padding: 20px 0px; } /*Topnav */ .nav-primary { float: right; margin-top: 1px; } ul.topnav { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: white; display: inline-block; } ul.topnav li { float: left; } ul.topnav li a { display: block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; } ul.topnav li a:hover { background-color: floralwhite; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="header"&gt; &lt;div id="title"&gt; &lt;p&gt; &lt;img src="http://i1379.photobucket.com/albums/ah150/beccaday02/blog%20title_zpsi4lf0fqz.png" /&gt; &lt;span class="sep"&gt;|&lt;/span&gt; &lt;span class="desc"&gt;Help For The Undomesticated Homemaker&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;nav class="nav-primary"&gt; &lt;ul class="topnav" id="myTopnav"&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/start-here.html"&gt;Start Here&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/write-for-us.html"&gt;Write For Me&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/advertise.html"&gt;Advertise&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/contact.html"&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.header:after { content: ''; display: block; clear: both; } #title { float: left; } #title p { margin: 0; } #title p &gt; * { display: inline-block; vertical-align: middle; } .nav-primary { float: right; } .nav-primary ul { margin: 0; padding: 0; list-style-type: none; } .nav-primary ul li { float: left; padding-right: 15px; line-height: 40px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="header"&gt; &lt;div id="title"&gt; &lt;p&gt; &lt;img src="http://i1379.photobucket.com/albums/ah150/beccaday02/blog%20title_zpsi4lf0fqz.png" /&gt; &lt;span class="sep"&gt;|&lt;/span&gt; &lt;span class="desc"&gt;Help For The Undomesticated Homemaker&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;nav class="nav-primary"&gt; &lt;ul class="topnav" id="myTopnav"&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/start-here.html"&gt;Start Here&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/write-for-us.html"&gt;Write For Me&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/advertise.html"&gt;Advertise&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.nappiesandnailpolish.com/p/contact.html"&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I have modified your CSS with the basic settings to align everything in 1 line, give the rest of the touch up as you wish</p> <pre><code>.header:after { content: ''; display: block; clear: both; } #title { float: left; } #title p { margin: 0; } #title p &gt; * { display: inline-block; vertical-align: middle; } .nav-primary { float: right; } .nav-primary ul { margin: 0; padding: 0; list-style-type: none; } .nav-primary ul li { float: left; padding-right: 15px; line-height: 40px; } </code></pre>
cordova net::ERR_CACHE_MISS <p>i have an cordova pp i am calling a post method in controller it works in browser , but in build and debug apk i get the error </p> <p>ionic.bundle.js:23826 POST <a href="http://somedomain.com/api/account/validation" rel="nofollow">http://somedomain.com/api/account/validation</a> net::ERR_CACHE_MISS</p> <p>my angular controller </p> <pre><code>.controller('splashCtrl', function ($scope, $state,$http, userManager, serverConfig) { //check if the user exist else it will redirect to login $scope.authenticate = function () { $http.post(serverConfig.serverUrl + '/api/account/validation').success(function (res,status) { if (status == '200') { //check if the user need to change password if (window.localStorage.getItem('shouldChangePassword') &amp;&amp; window.localStorage.getItem('shouldChangePassword')=='true') { $state.go('setPassword'); return; } $state.go('tab.category'); } }).error(function (data, status) { console.log(status) }) } $scope.authenticate(); }) </code></pre> <p>any suggestion ?</p>
<p>This Error means you don't have access to internet.There are two ways you can provide this access by changing these files</p> <p><strong>1.AndroidManifest.xml</strong></p> <p>add these following permission </p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.NETWORK_ACCESS" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; </code></pre> <p><strong>2. config.xml</strong></p> <p>For this you are going to need this plugin</p> <pre><code>cordova plugin add cordova-custom-config </code></pre> <p>after adding this plugin , add these lines in you config.xml</p> <pre><code>&lt;platform name="android"&gt; &lt;config-file target="AndroidManifest.xml" parent="/*"&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permissions.NETWORK_ACCESS" /&gt; &lt;uses-permission android:name="android.permissions.ACCESS_NETWORK_STATE" /&gt; &lt;/config-file&gt; &lt;/platform&gt; </code></pre> <p>You can try it . Hope it helps you .Thanks</p>
React Native Speech to Text <p>I am making a language app that records any new vocabulary a user is trying to learn. It would be great if users can add their words via a speech to text program, instead of having to enter it manually. I am having trouble achieving this task. I am aware that there is an API for apple but not android. Is there anyway possible of doing this, using an API? Like for instance, google speech to text API? But I guess I would first have to be able to access the device's microphone. I am a beginner and this would be very easy using the web. Is React Native still too young for this task? </p>
<p>You might wanna look at <a href="https://www.npmjs.com/package/react-native-android-voice" rel="nofollow">react-native-android-voice</a>, a React Native module that supports speech-to-text for Android. </p> <p>Alternatively, you can always write your custom native module using Android's <a href="https://developer.android.com/reference/android/speech/SpeechRecognizer.html" rel="nofollow">SpeechRecognizer</a> API. <a href="https://developer.android.com/reference/android/speech/package-summary.html" rel="nofollow">Here's</a> a summary of all the classes and interfaces you might need for this task. If you are familiar with developing native Android apps, it's pretty easy to create a native module and bind it to your React Native project. <a href="https://facebook.github.io/react-native/docs/native-modules-android.html" rel="nofollow">Here's the official documentation</a> of how to achieve this.</p>
C# Custom Attribute parameters <p>I saw this answer from this link <a href="http://stackoverflow.com/questions/270187/can-i-initialize-a-c-sharp-attribute-with-an-array-or-other-variable-number-of-a">Adding parameters to custom attributes</a> of how is to add parameters on Custom Attribute </p> <pre><code>class MyCustomAttribute : Attribute { public int[] Values { get; set; } public MyCustomAttribute(params int[] values) { this.Values = values; } } [MyCustomAttribute(3, 4, 5)] class MyClass { } </code></pre> <p>Now I am wondering if can't it be write like this?</p> <pre><code>class MyCustomAttribute : Attribute { private int[] _values; public MyCustomAttribute(params int[] values) { _values = values; } } [MyCustomAttribute(3, 4, 5)] class MyClass { } </code></pre> <p>I changed the property Values into a variable _values. I also made it private and it works fine when I tried it.</p> <p>Can someone enlighten me why the accepted answer is valid?</p>
<p>For <code>[MyCustomAttribute(3, 4, 5)]</code> the parameter list is unnamed, so the the constructor of <code>MyCustomAttribute</code> is used. </p> <p>Therefore it does not matter, if there is a public <code>Values</code> properties.</p> <p>In your first code sample it is acceptable to use <code>[MyCustomAttribute(3, 4, 5)]</code> and <code>[MyCustom(Values = new[] {3, 4, 5})]</code>.</p> <p>The second code sample "only" accepts <code>[MyCustomAttribute(3, 4, 5)]</code>.</p>
member function pointer with variadic templates <p>I am trying to write a class that "manages" delegates in c++. I already have the delegate class implemented for me. I want this delegate manager class to have two functions:</p> <ul> <li><p>One would take a pointer to instance of a delegate of a certain type with a given input-argument/return type, and cache it.</p></li> <li><p>The other function would take a member function of the right type in order to bind the cached delegate instance to it. </p></li> </ul> <p>Currently, I have:</p> <pre><code>template&lt;typename... Args&gt; struct FunctionParamsPack { }; </code></pre> <p>This is the container for the types of the parameters this function takes. ie for <code>foo(int i, double d)</code> that would be <code>int</code> and <code>double</code>. I am following the advice from <a href="http://stackoverflow.com/questions/22968182/is-it-possible-to-typedef-a-parameter-pack">here</a>.</p> <p>then I have the <code>DelegateInfoPack</code> class:</p> <pre><code>template&lt;typename FuncRetType,typename... FuncParams&gt; struct DelegateInfoPack{ //for look-up by components in the program typedef typename DelegateClass&lt;FuncRetType, FuncParams...&gt; _Delegate; //for the delegate manager typedef typename FuncRetType _FuncRetType; typedef typename FunctionParamsPack&lt;FuncParams...&gt; _FuncParams; }; </code></pre> <p>This struct is included by that the components in the program and it typedefs three typenames, two of which are to be used in the DelegateManger class:</p> <pre><code>template&lt;typename DelegateInfoPack&gt; class DelegateManager { typedef typename DelegateInfoPack::_Delegate _Delegate; typedef typename DelegateInfoPack::_FuncRetType _FuncRetType; typedef typename DelegateInfoPack::_FuncParams _FuncParams; void CacheDelegate(_Delegate* del,...) {} template&lt;typename UserClass&gt; void BindDelegate(..., _FuncRetType(UserClass::*fp)( _FuncParams())) {} //Doesn't work! } </code></pre> <p>My problem is with the <code>BindDelegate()</code> function. I am not able to create the correct signature for the member function of the type with a given return type and input parameter types.</p> <p>basically, I need to know the way to have the right function pointer type with a given return type and argument type so my BindDelegate takes it as an argument.</p>
<p>One approach is to use partial specialization:</p> <pre><code>template&lt;typename&gt; class DelegateManager; template&lt;typename FuncRetType,typename... FuncParams&gt; class DelegateManager&lt;DelegateInfoPack&lt;FuncRetType,FuncParams...&gt;&gt; { template&lt;typename UserClass&gt; void BindDelegate(_FuncRetType(UserClass::*fp)(FuncParams...)) { } }; </code></pre> <p>Another approach is to have a class which generates the appropriate function type</p> <pre><code>template &lt;typename FuncRetType,typename FuncParams&gt; struct FunctionPointer; template &lt;typename FuncRetType,typename...ARGS&gt; struct FunctionPointer&lt;FuncRetType,FunctionParamsPack&lt;ARGS...&gt;&gt; { typedef FuncRetType (Type)(ARGS...); }; </code></pre> <p>Then use that in your BindDelegate member function:</p> <pre><code>template&lt;typename UserClass&gt; void BindDelegate( typename FunctionPointer&lt;_FuncRetType,_FuncParams&gt;::Type UserClass::*fp ) { ... } </code></pre> <p>Or maybe even put this into your DelegateInfoPack class:</p> <pre><code>template&lt;typename FuncRetType,typename... FuncParams&gt; struct DelegateInfoPack { . . . typedef FuncRetType (_FuncType)(FuncParams...); }; </code></pre> <p>and use that in your DelegateManager</p> <pre><code>template&lt;typename DelegateInfoPack&gt; struct DelegateManager { . . . typedef typename DelegateInfoPack::_FuncType _FuncType; template&lt;typename UserClass&gt; void BindDelegate(_FuncType UserClass::*fp) { } }; </code></pre>
DynamoDB global index on a field with small amount of distinct values <p>In official Amazon docs there's this text:</p> <blockquote> <p>For example, suppose you have an Employee table with attributes such as Name, Title, Address, PhoneNumber, Salary, and PayLevel. Now suppose that you had a global secondary index named PayLevelIndex, with PayLevel as the partition key. Many companies only have a very small number of pay codes, often fewer than ten, even for companies with hundreds of thousands of employees. Such an index would not provide much benefit, if any, for an application.</p> </blockquote> <p>I really don't understand how such index wouldn't be beneficial. What if we need to list all employees with a specific <code>payLevel</code>? Even if we have only 2 distinct <code>payLevels</code>, the index should help, right?</p>
<p>Its not really going to help. High cardinality is generally your goal when it comes to indexes in any database.</p> <p>Consider also that this is their recommendation. Trust the documentation until you see something that conflicting in actual practice. </p>
How Can I sum up the column with decimal value in C# crystal report <p>Why is it not summing up. The datatype of totalamount due is decimal and When I insert a summary there is no sum in calculate summary. </p> <p><a href="https://i.stack.imgur.com/JEdko.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/JEdko.jpg" alt="enter image description here"></a></p>
<p>I did it when i created a formula and convert it to Number and then Create another formula where it will hold the sum</p>
TextView with setAutoLinkMask(Linkify.WEB_URLS) firing android.util.AndroidRuntimeException when tapping the link <p>I'm inflating views programatically and I need the links inside the <code>TextViews</code> to be clickable.</p> <p>I'm doing it this way:</p> <pre><code>((TextView) newView).setAutoLinkMask(Linkify.WEB_URLS); ((TextView) newView).setMovementMethod(LinkMovementMethod.getInstance()); </code></pre> <p>But when I tap a link, this <code>Exception</code> is thrown:</p> <blockquote> <p>Exception in MessageQueue callback: handleReceiveCallback</p> <p>E/MessageQueue-JNI: android.util.AndroidRuntimeException: </p> <p>Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?</p> </blockquote>
<p>You probably passed the "wrong" context in your adapter. Here is a helpful article: <a href="https://possiblemobile.com/2013/06/context/" rel="nofollow">https://possiblemobile.com/2013/06/context/</a></p>
In what terms does new operator is considered harmful? <p>Factory pattern is supposed to be used when using new operator for creating object is considered harmful. In what terms does new operator is considered harmful</p>
<p>The main reason you use factory pattern is that you don't need a lot of constructors for a object;</p> <pre><code>public Person(int age, String firstName, String lastName); public Person(int age, String firstName, String middleName, String lastName); public Person(int age, String firstName, String lastName, String socialNumber); .... </code></pre> <p>With factory pattern you can create a lot of different objects that are initialised with different parameters without writing so many constructor methods.</p> <p>new object() is usually used in order to create an instance of the object to use it's non-static methods. I read about some issues using new operator and how it's allocating heap memory(you might not want that). Ignoring that there is no issue using new.</p>
Restoring the exact angle from std::cos(angle) using std::acos <p>Is it guaranteed by the C++ standard that <code>angle == std::acos(std::cos(angle))</code> if <code>angle</code> is in the range [0, Pi], or in other words is it possible to restore the exact original value of <code>angle</code> from the result of <code>std::cos</code> using <code>std::acos</code> given the mentioned range limit?</p> <p>The marginal cases when <code>angle</code> is <code>infinity</code> or <code>NaN</code> are omitted.</p>
<p>Answer by StoryTeller:</p> <blockquote> <p>The standard cannot make that guarantee, simply because the result of <code>std::cos</code> may not be representable exactly by a <code>double</code>, so you get a truncation error, which will affect the result of <code>std::acos</code>.</p> </blockquote>
using multiple redux stores one for each app user <p>in a react native app, i'm using redux. currently the whole app have single store and i use redux-persist to cache store to localstorage. </p> <p>my app is username and password protected, you must create account to use it.</p> <p>now i want to provide ability so that my user can switch between his accounts -if he have more than one account- . this is causing lots of trouble because now i have to clear storage and reset state everytime user switch between accounts.</p> <p>so i was considering may be i can use multiple stores, one for every users ?</p> <p>for example my app state looks like </p> <pre><code>{ chat:{}, highscores:{}, gameHistory:{}, } </code></pre> <p>now if a user have account lets say <code>User1@gmail.com</code> the state will be populated with his data. and his state will be saved to LocalStorage,</p> <p>once he switch account to <code>User2@gmail.com</code> now i have to reset the app to its initialState, then somehow load the User2 state from localStorage</p> <p>i dont want the state of the app to be lost everytime user switch between accounts.</p> <p>so i was considering may be in this case it would be a good option to use a multiple Redux Stores, one for every user.</p> <p>did anyone had an app that is designed to be used by multiple users before ? how can we do this in redux ?</p>
<p>I don't think having a store for each user is a good idea. See this SO answer: <a href="http://stackoverflow.com/a/33633850/3794660">http://stackoverflow.com/a/33633850/3794660</a></p> <p>Why don't you namespace the data you have in your reducer by user id? Something like this:</p> <pre><code>{ currentUserId: "1", chat:{ "1": { // Chats for user id 1 }, "2": { // Chats for user id 2 }}, highscores:{ // Same structure as above }, gameHistory:{ // Same structure as above }, } </code></pre> <p>When you switch user account, you simply update the currentUserId in the state.</p> <p>I'd recommend using selectors to encapsulate the logic to read the data from the store.</p> <p>A simple selector to get all the chats for the current account could look like this:</p> <pre><code>const getCurrUserId = state =&gt; state.currentUserId const getChats = state =&gt; { const userId = getCurrUserId(state); return state.chat[userId]; } </code></pre> <p>You then use your simple getChats selector in your <code>mapStateToProps</code> to pass the data to your components. In this way you encapsulate the logic to retrieve the data from the state and your components don't need to know these details, so you're free to change your strategy if you need to.</p>
Can't select added element <p>I faced this problem while doing some exercises. Can't select recently added button number two, and cant call alert method</p> <pre><code>$('#but').click(function() { $('#but').after('&lt;button id="but2"&gt;Кнопка 2&lt;/button'); }); $('#but2').click(function() { alert('something'); }); </code></pre> <p>Having only this HTML code:</p> <pre><code>&lt;button id="but"&gt;Кнопка 1&lt;/button&gt; </code></pre>
<p>Your <code>htmlString</code> is lacking a <code>&gt;</code> on its closing tag:</p> <pre><code>.after('&lt;button id="but2"&gt;Кнопка 2&lt;/button'); ^ </code></pre> <p>And use event delegation for dynamic elements:</p> <pre><code>$(document).on('click','#but2',function(){ alert('something'); }); </code></pre>
Why can yield be indexed? <p>I thought I could make my python (2.7.10) code simpler by directly accessing the index of a value passed to a generator via <code>send</code>, and was surprised the code ran. I then discovered an index applied to <code>yield</code> doesn't really do anything, nor does it throw an exception:</p> <pre><code>def gen1(): t = yield[0] assert t yield False g = gen1() next(g) g.send('char_str') </code></pre> <p>However, if I try to index <code>yield</code> thrice or more, I get an exception:</p> <pre><code>def gen1(): t = yield[0][0][0] assert t yield False g = gen1() next(g) g.send('char_str') </code></pre> <p>which throws</p> <pre><code>TypeError: 'int' object has no attribute '__getitem__' </code></pre> <p>This was unusually inconsistent behavior, and I was wondering if there is an intuitive explanation for what indexing yield is actually doing?</p>
<p>You are not indexing. You are yielding a list; the expression <code>yield[0]</code> is really just the same as the following (but without a variable):</p> <pre><code>lst = [0] yield lst </code></pre> <p>If you look at what <code>next()</code> returned you'd have gotten that list:</p> <pre><code>&gt;&gt;&gt; def gen1(): ... t = yield[0] ... assert t ... yield False ... &gt;&gt;&gt; g = gen1() &gt;&gt;&gt; next(g) [0] </code></pre> <p>You don't <em>have</em> to have a space between <code>yield</code> and the <code>[0]</code>, that's all.</p> <p>The exception is caused by you trying to apply the subscription to the contained <code>0</code> integer:</p> <pre><code>&gt;&gt;&gt; [0] # list with one element, the int value 0 [0] &gt;&gt;&gt; [0][0] # indexing the first element, so 0 0 &gt;&gt;&gt; [0][0][0] # trying to index the 0 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not subscriptable </code></pre> <p>If you want to index a value sent to the generator, put parentheses around the <code>yield</code> expression:</p> <pre><code>t = (yield)[0] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; def gen1(): ... t = (yield)[0] ... print 'Received: {!r}'.format(t) ... yield False ... &gt;&gt;&gt; g = gen1() &gt;&gt;&gt; next(g) &gt;&gt;&gt; g.send('foo') Received: 'f' False </code></pre>
How to save parts of linprog solutions <p>I am solving a serie of linear programing problems using linprog by indexing each problem in a for-loop:</p> <pre><code>from scipy.optimize import linprog for i in range(1,N): sol[i] = linprog(coa3[N][0], A_ub = coa4[i], b_ub = chvneg[i], options= {"disp": True}) </code></pre> <p>I would like to save in a list (still indexed over i) the function minimization result and the array displaying the values of the variables. I guess I need to add in the for-loop something like minfval[i] = ??? and xval[i] = ???, but actually I don't know how to extract these values from the results provided by linprog. Any suggestions? Thanks a lot.</p>
<p>Consider reading the <a href="http://docs.scipy.org/doc/scipy/reference/optimize.linprog-simplex.html" rel="nofollow">docs</a> as it's pretty clearly explained what exactly linprog returns.</p> <p>The good thing is, that you are actually storing these values with your code already because you are storing the whole <strong>scipy.optimize.OptimizeResult</strong>.</p> <p>It's now just a matter of accessing it:</p> <pre><code>from scipy.optimize import linprog for i in range(1,N): sol[i] = linprog(coa3[N][0], A_ub = coa4[i], b_ub = chvneg[i], options= {"disp": True}) # iterate over solution-vectors for i in range(1,N): print(sol[i].x) # iterate over objectives for i in range(1,N): print(sol[i].fun) </code></pre> <p>You should also check out the field <code>success</code> just to be safe!</p> <p>Extraction of the docs (link above) on what is contained in linprog's result:</p> <pre><code>x : ndarray The independent variable vector which optimizes the linear programming problem. fun : float Value of the objective function. slack : ndarray The values of the slack variables. Each slack variable corresponds to an inequality constraint. If the slack is zero, then the corresponding constraint is active. success : bool Returns True if the algorithm succeeded in finding an optimal solution. status : int An integer representing the exit status of the optimization:: 0 : Optimization terminated successfully 1 : Iteration limit reached 2 : Problem appears to be infeasible 3 : Problem appears to be unbounded nit : int The number of iterations performed. message : str A string descriptor of the exit status of the optimization. </code></pre>
Python Indention Block? Why? <p>I have tried untabifying region.. and did not mix spaces/tabs.. What could be wrong here? When I run the module it traces to <code>if result["geo"]:</code> and says "There's an error in your program: expected an indention block"</p> <pre><code>from twitter import * import sys import csv latitude = 8.8015 longitude = 125.7407 max_range = 1000 num_results = 500 outfile = "nimal.csv" config = {} execfile("config.py", config) twitter = Twitter( auth = OAuth(config["access_key"], config["access_secret"], config["consumer_key"], config["consumer_secret"])) csvfile = file(outfile, "w") csvwriter = csv.writer(csvfile) row = [ "date", "user", "text", "latitude", "longitude" ] csvwriter.writerow(row) result_count = 0 last_id = None while result_count &lt; num_results: query = twitter.search.tweets(q = "urios", geocode = "%f,%f,%dkm" % (latitude, longitude, max_range), count = 100, since_id = 2016-10-8, max_id = last_id) for result in query["statuses"]: if result["geo"]: date = result["created_at"] user = result["user"]["screen_name"] text = text.encode('ascii', 'replace') latitude = result["geo"]["coordinates"][0] longitude = result["geo"]["coordinates"][1] row = [ date, user, text, latitude, longitude ] csvwriter.writerow(row) result_count += 1 last_id = result["id"] print "got %d results" % result_count csvfile.close() print "written to %s" % outfile </code></pre>
<p>here is the problem :</p> <pre><code>for result in query["statuses"]: if result["geo"]: date = result["created_at"] </code></pre> <p>python has specific syntax and it has to be considered <br /> you have to change it to:</p> <pre><code>for result in query["statuses"]: if result["geo"]: date = result["created_at"] </code></pre>
How to use multiple values in between clause <p>Hi all is there any way that i can use multiple values in between clause as column_name between 0 and 100 or 200 and 300 like this Any help would be appreciated here is my query <code>SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100</code> i just want to append multiple values in between clause</p> <p>This is full query</p> <pre><code>SELECT ROW_NUMBER() OVER ( order by Vendor_PrimaryInfo.Vendor_ID asc )AS RowNumber , Unit_Table.Unit_title, Vendor_Base_Price.Base_Price, Vendor_Base_Price.showprice, Category_Table.Title, Vendor_Registration.Business_Name, Vendor_PrimaryInfo.Street_Address, Vendor_PrimaryInfo.Locality, Vendor_PrimaryInfo.Nearest_Landmark, Vendor_PrimaryInfo.City, Vendor_PrimaryInfo.State, Vendor_PrimaryInfo.Country, Vendor_PrimaryInfo.PostalCode, Vendor_PrimaryInfo.Latitude, Vendor_PrimaryInfo.Longitude, Vendor_PrimaryInfo.ImageUrl, Vendor_PrimaryInfo.ContactNo, Vendor_PrimaryInfo.Email,Vendor_PrimaryInfo.Vendor_ID FROM Unit_Table INNER JOIN Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID INNER JOIN Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID INNER JOIN Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID INNER JOIN Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID LEFT JOIN Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID LEFT JOIN Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID where Vendor_Registration.Category_ID=5 and Vendor_PrimaryInfo.City='City' AND( value_text in('Dhol Wala$Shahnai Wala') or (SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100 ) </code></pre>
<p>You can do this using <code>AND/OR</code> logic</p> <pre><code>value_text NOT LIKE '%[^0-9]%' and ( value_text between 0 and 100 Or value_text between 101 and 200 ) </code></pre> <p>If you don't want to repeat the column name then frame the range in table valued constructor and join with your table</p> <pre><code>SELECT Row_number() OVER ( ORDER BY Vendor_PrimaryInfo.Vendor_ID ASC )AS RowNumber, Unit_Table.Unit_title, Vendor_Base_Price.Base_Price, Vendor_Base_Price.showprice, Category_Table.Title, Vendor_Registration.Business_Name, Vendor_PrimaryInfo.Street_Address, Vendor_PrimaryInfo.Locality, Vendor_PrimaryInfo.Nearest_Landmark, Vendor_PrimaryInfo.City, Vendor_PrimaryInfo.State, Vendor_PrimaryInfo.Country, Vendor_PrimaryInfo.PostalCode, Vendor_PrimaryInfo.Latitude, Vendor_PrimaryInfo.Longitude, Vendor_PrimaryInfo.ImageUrl, Vendor_PrimaryInfo.ContactNo, Vendor_PrimaryInfo.Email, Vendor_PrimaryInfo.Vendor_ID FROM Unit_Table INNER JOIN Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID INNER JOIN Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID INNER JOIN Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID INNER JOIN Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID LEFT JOIN Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID LEFT JOIN Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID JOIN (VALUES (0, 100), (101, 200), (201, 300)) tc (st, ed) ON Try_cast(value_text AS INT) BETWEEN st AND ed OR Try_cast(value_text AS VARCHAR(100)) = 'Dhol Wala$Shahnai Wala' WHERE Vendor_Registration.Category_ID = 5 AND Vendor_PrimaryInfo.City = 'City' </code></pre> <p><strong>Note :</strong> You have stored two different information's in a single column which causes lot of pain when you want to extract the data like this. Consider changing your table structure </p>
Flyway cannot connect to db after Heroku Postgres upgrade <p>I am upgrading my heroku database from a hobby dev to Standard 0 (using the official instructions <a href="https://devcenter.heroku.com/articles/upgrading-heroku-postgres-databases#upgrade-with-pg-copy-default" rel="nofollow">https://devcenter.heroku.com/articles/upgrading-heroku-postgres-databases#upgrade-with-pg-copy-default</a>).</p> <p>All went well, until I promoted the new database and restarted the app. I then get the following error:</p> <pre><code>o.s.boot.SpringApplication : Application startup failed ... org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Unable to obtain Jdbc connection from DataSource ... Caused by: org.flywaydb.core.api.FlywayException: Unable to obtain Jdbc connection from DataSource ... Caused by: org.postgresql.util.PSQLException: FATAL: no pg_hba.conf entry for host "54.xxx.xx.xxx", user "u94bf9vxxxxxx", database "d2mqk0b6xxxxxx", SSL off ... </code></pre> <p>If I swap back to the old database again, everything works again. The only thing that I am changing is the promoted database.</p> <p>Is there a difference between connecting to hobby and standard databases that I need to be aware of?</p> <p>The relevant part of my application.yml looks as follows:</p> <pre><code>spring: datasource: driverClassName: org.postgresql.Driver url: ${JDBC_DATABASE_URL} username: ${JDBC_DATABASE_USERNAME} password: ${JDBC_DATABASE_PASSWORD} flyway: enabled: true locations: classpath:db/migrations </code></pre> <p>Any suggestions on how I can debug this would be very welcome too.</p>
<p>Looks like you aren't connecting with SSL where it is required by Heroku PostgreSQL installs.</p> <p>See Herokus <a href="https://devcenter.heroku.com/articles/heroku-postgresql#external-connections-ingress" rel="nofollow">documentation on SSL for PostgreSQL</a>.</p> <p>See also Herokus <a href="https://devcenter.heroku.com/articles/connecting-to-relational-databases-on-heroku-with-java#connecting-to-a-database-remotely" rel="nofollow">documentation for enabling SSL</a> on JDBC connections.</p> <p>You will need to add something like <code>&amp;ssl=true&amp;sslfactory=org.postgresql.ssl.NonValidatingFactory</code> to your JDBC URL.</p>
Slider - Active blur <p>I currently have this</p> <p><a href="https://i.stack.imgur.com/AkAq7.png" rel="nofollow"><img src="https://i.stack.imgur.com/AkAq7.png" alt="enter image description here"></a></p> <p>and I want it to look like </p> <p><a href="https://i.stack.imgur.com/LYnsV.png" rel="nofollow"><img src="https://i.stack.imgur.com/LYnsV.png" alt="enter image description here"></a></p> <p>I tried many things which havent worked please help me!</p> <p>I am using owl Carousel</p> <p>My CSS:</p> <pre><code>#owl-slider .item{ padding: 30px 0px; margin: 10px; color: #FFF; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; text-align: center; } .customNavigation{ text-align: center; } .customNavigation a{ -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } .image-fade-left { -webkit-mask-image: -webkit-linear-gradient(right, rgba(0,0,0,1), rgba(0,0,0,0)); } .image-fade-right { -webkit-mask-image: -webkit-linear-gradient(left, rgba(0,0,0,1), rgba(0,0,0,0)); } </code></pre> <p>My html:</p> <pre><code>&lt;div class="image-fade-right"&gt; &lt;div class="image-fade-left"&gt; &lt;div id="owl-slider" class="owl-carousel"&gt; &lt;div class="item"&gt; &lt;img class="lazyOwl" data-src="" alt=""&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="lazyOwl" data-src="" alt=""&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="lazyOwl" data-src="" alt=""&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="lazyOwl" data-src="" alt=""&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="lazyOwl" data-src="" alt=""&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="lazyOwl" data-src="" alt=""&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Full Code : <a href="http://hastebin.com/hevogeqijo.xml" rel="nofollow">http://hastebin.com/hevogeqijo.xml</a></p> <p>Thank You!</p>
<p>You can probably do this using only one class instead of two by doing this :</p> <pre><code>.image-fade { -webkit-mask-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,1), rgba(0,0,0,0)); } </code></pre> <p>What I did is add more "anchor" points to the gradient, so that it's white in the two borders (<code>rgba(0,0,0,0)</code>) and transparent (<code>rgba(0,0,0,1)</code>) in the center.</p> <p>Or, if you want to modify your code at least at possible, try this :</p> <pre><code>.image-fade-left { -webkit-mask-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0), rgba(0,0,0,1)); } .image-fade-right { -webkit-mask-image: -webkit-linear-gradient(left, rgba(0,0,0,1), rgba(0,0,0,0), rgba(0,0,0,0)); } </code></pre>
Feature branching for mobile development <p>I use feature branching for my web projects, where, for each feature, I create a new branch and open a pull request when the feature is ready to be tested by other members of the team. </p> <p>Using <a href="https://devcenter.heroku.com/articles/github-integration-review-apps" rel="nofollow">Heroku review apps</a> and <a href="https://github.com/features" rel="nofollow">Github collaborative code review</a> we can review the code and test the feature seamlessly (no pull, build, and so on..).</p> <p>Now, we are developing a mobile app for ios/android using ionic2 and the testflight (ios) / beta (android) programs. The problem is that you can only have one build at a time, so features have to be tested one by one (i.e. PR1, B1, Merge PR1, open PR2, B2, Merge PR2 and so on). It considerably slows our development process.</p> <p>So, do you known extra tooling/options/process for having many mobile builds on test at the same time ? </p>
<p>I think you could use <a href="https://hockeyapp.net/" rel="nofollow">HockeyApp</a>. You can have different builds there (one for each feature for example), and the tester is able to choose what version to install.</p>
Where am I wrong in the loop? <p>It is supposed to print multiplication table of number 1-10. </p> <pre><code>&lt;script&gt; //Multiplication table of 1 to 10; var a=b=1; for (a==1; a&lt;=10; a++){ for(b==1; b&lt;=10; b++){ document.write(a + "x" + b + "=" + (a*b) + "&lt;br /&gt;"); } } &lt;/script&gt; </code></pre>
<p>Change <code>a==1</code> and <code>b==1</code> to <code>a=1</code> and <code>b=1</code>. <code>==</code> is a comparison sign.</p>
Vertical LinearLayout, making the map shrink the more controls are added <p>I want to display a Google map and 2 controls below it. How do I achieve this?! I tried it this way:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:map="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/map" tools:layout="@android:layout/browser_link_context_header" /&gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;EditText android:id="@+id/edOrderLocation" android:layout_height="wrap_content" android:layout_width="match_parent" /&gt; &lt;Spinner android:id="@+id/spinJobType" android:layout_height="wrap_content" android:layout_width="match_parent" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>The controls are not visible, the whole screen takes up the map. I want the controls to be visible at the bottom of the screen and thus reduzing the size of the fragment accordingly</p>
<p>Try this - </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;fragment android:layout_alignParentTop="true" android:layout_above="@+id/controls_container" xmlns:tools="http://schemas.android.com/tools" xmlns:map="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/map" tools:layout="@android:layout/browser_link_context_header" /&gt; &lt;LinearLayout android:id="@id/controls_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_alignParentBottom="true"&gt; &lt;EditText android:id="@+id/edOrderLocation" android:layout_height="wrap_content" android:layout_width="match_parent" /&gt; &lt;Spinner android:id="@+id/spinJobType" android:layout_height="wrap_content" android:layout_width="match_parent" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre>
String.split(String regex) Symbol avoidance <p>I have </p> <pre><code>String text2 = "Samaras did something by Papandreou's government."; </code></pre> <p>When I use </p> <pre><code>String[] w2 = text2.split("\\s+"); </code></pre> <p>it takes the "Papandreou's" as a whole word (as its supposed to do). But how can I avoid the <code>'s</code> after the word? </p>
<pre><code>text2.split("(\\'s)?\\s+"); </code></pre> <p>This regular expression splits the <strong><em>'s</em></strong> as optional, so it means either <strong>"Split 's follow with spaces"</strong> or <strong>"Split only spaces"</strong>.</p>