title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Sometimes request.session.session_key is None
<p>I hit a problem when get session_key from <code>request.session</code>.</p> <p>I am using Django1.8 and Python2.7.10 to set up a RESTful service.</p> <p>Here is snippet of my login view:</p> <pre><code>user = authenticate(username=userName, password=passWord) if user is not None: # the password verified for the user if user.is_active: # app_logger.debug("User is valid, active and authenticated") if hasattr(user, 'parent') : login(request, user) request.session['ut'] = 4 # user type 1 means admin, 2 for teacher, 3 for student, 4 for parents request.session['uid'] = user.id description = request.POST.get('description','') request.session['realname'] = user.parent.realname request.session['pid'] = user.parent.id devicemanage.update_user_device(devicetoken, user.id, ostype, description) children = parentmanage.get_children_info(user.parent.id) session_id = request.session.session_key user.parent.login_status = True user.parent.save() return JsonResponse({'retcode': 0,'notify_setting':{'receive_notify':user.parent.receive_notify,'notify_with_sound':user.parent.notify_with_sound,'notify_sound':user.parent.notify_sound,'notify_shake':user.parent.notify_shake},'pid':user.parent.id,'children':children,'name':user.parent.realname,'sessionid':session_id,'avatar':user.parent.avatar,'coins':user.parent.coins}) </code></pre> <p>Now when this function is called, I see sometimes <code>session_id</code> is <code>None</code> within the response.</p> <p>So, after debugging (I set breakpoint at the <code>return JsonResponse(...)</code> line), I see that when I hit the breakpoint the <code>request.session._session_key</code> is <code>None</code>, but <code>request.session.session_key</code> is <code>u'j4lhxe8lvk7j4v5cmkfzytyn5235chf1'</code> and <code>session_id</code> is also <code>None</code>. </p> <p>Does anyone know how can this happen? Why isn't the value of <code>session_key</code> set when assigning it to <code>session_id</code> before returning the response?</p>
0
BitmapFactory.decodeStream from Assets returns null on Android 7
<p>How to decode bitmaps from Asset directory in Android 7?</p> <p>My App is running well on Android versions up to Marshmallow. With Android 7 it fails to load images from the Asset directory.</p> <p>My Code:</p> <pre><code>private Bitmap getImage(String imagename) { // Log.dd(logger, "AsyncImageLoader: " + ORDNER_IMAGES + imagename); AssetManager asset = context.getAssets(); InputStream is = null; try { is = asset.open(ORDNER_IMAGES + imagename); } catch (IOException e) { // Log.de(logger, "image konnte nicht gelesen werden: " + ORDNER_IMAGES + imagename); return null; } // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, PW, PH); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // Lesen des Bitmaps in der optimierten Groesse return BitmapFactory.decodeStream(is, null, options); } </code></pre> <p>As a result (only Android 7) <code>BitmapFactory.decodeStream</code> is null. It works correctly an older Android APIs.</p> <p>In debug mode I see the following Message:</p> <blockquote> <p>09-04 10:10:50.384 6274-6610/myapp D/skia: --- SkAndroidCodec::NewFromStream returned null</p> </blockquote> <p>Can someone tell me the reason and how to correct the coding?</p> <p>Edit: Meanwhile i found, that removing of the first BitmapFactory.decodeStream with inJustDecodeBounds=true leads to a successful BitmapFactory.decodeStream afterwards with inJustDecodeBounds=false. Don't know the reason and don't know how to substitute the measurement of bitmap size.</p>
0
How is dynamic strict applied in ElasticSearch
<p>I'm using ElasticSearch 2.3.3.</p> <p>I have the following mapping:</p> <pre><code>"mappings": { "entries": { "dynamic": "strict", "properties": { "Data": { "properties": { "Age": { "type": "long" }, "BirthDate": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss.SSS" }, "Cash": { "type": "boolean" }, "Cheque": { "type": "boolean" }, "Comments": { "type": "string" }, "CreditCard": { "type": "boolean" }, "FirstName": { "type": "string", "index": "not_analyzed" }, "Gender": { "type": "string", "index": "not_analyzed" }, "LastName": { "type": "string", "index": "not_analyzed" } } }, "MetaInfo": { "properties": { "CreatedDate": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss.SSS" }, "FormId": { "type": "string", "index": "not_analyzed" }, "FormName": { "type": "string", "index": "not_analyzed" }, "FormVersion": { "type": "integer" } } } } } } </code></pre> <p>Notice that I have put <code>"dynamic" : "strict"</code> at the root.</p> <p>Do I have to specify "dynamic":"strict" to all levels of embedded objects ? In other words, if I set "dynamic":"strict" at the root level then does it apply to embedded objects as well ?</p> <p>Documentation is not clear about this.</p>
0
Finding "maximum" overlapping interval pair in O(nlog(n))
<p><strong>Problem Statement</strong></p> <p><strong>Input</strong> set of n intervals; {[s_1,t_1], [s_2,t_2], ... ,[s_n,t_n]}.</p> <p><strong>Output</strong> pair of intervals; {[s_i,t_i],[s_j,t_j]}, with the <em>maximum</em> overlap among all the interval pairs.</p> <p><strong>Example</strong></p> <p>input intervals : {[1, 10], [2, 6], [3,15], [5, 9]}</p> <p>-> There are possible 6 interval pairs. Among those pairs, [1,10] &amp; [3,15] has the largest possible overlap of 7.</p> <p>output : {[1,10],[3,15]}</p> <p>A naive algorithm will be a brute force method where all n intervals get compared to each other, while the current maximum overlap value being tracked. The time complexity would be O(n^2) for this case.</p> <p>I was able to find many procedures regarding <em>interval trees</em>, <em>maximum number of overlapping intervals</em> and <em>maximum set of non-overlapping intervals</em>, but nothing on this problem. Maybe I would be able to use the ideas given in the above algorithms, but I wasn't able to come up with one. </p> <p>I spent many hours trying to figure out a nice solution, but I think I need some help at this point. </p> <p>Any suggestions will help!</p>
0
How to remove a current page from stack navigation Xamarin Forms
<p>I'm trying so hard to do something but i wasnt able to solve this problem. I have three pages, One is the MainPage, LoginUpPage and SignUpPage, inside of LoginUpPage has a button who navigates to SignUpPage, what i want to do is when I finish my logic navigates to another page CreatedPage, whitch contains a Label with a Message - Success and then after 2 seconds GoBack to the LoginPage, the problem is if I press the backbutton from device it will return to the last page that has the label with a message and I don't want that. I have a toobar with a BackButton to return to each page that i navigates. So far I have this:</p> <p>LoginPage to SignUpPage :</p> <pre><code>Navigation.PushAsync(new SignupPage()); </code></pre> <p>SignUpPage to CreatedPage :</p> <pre><code>await Navigation.PushModalAsync(new Created()); </code></pre> <p>And inside of CreatedPage in my Contructor, this Method :</p> <pre><code> public async void Redirect() { await Task.Delay(TimeSpan.FromSeconds(2)); await Navigation.PushAsync(new LoginPage()); } </code></pre> <p>I know by this <a href="https://stackoverflow.com/questions/25165106/how-do-you-switch-pages-in-xamarin-forms">question</a> there's basically three ways to navigate to another page :</p> <pre><code>Navigation.PushAsync(new OtherPage()); // to show OtherPage and be able to go back </code></pre> <p><code>Navigation.PushAsyncModal(new AnotherPage());// to show AnotherPage and not have a Back button</code></p> <p><code>Navigation.PopAsync();// to go back one step on the navigation stack</code></p> <p>At the same question has a example how to remove from a page from stack but it doesn't work.</p> <pre><code>item.Tapped += async (sender, e) =&gt; { await Navigation.PushAsync (new SecondPage ()); Navigation.RemovePage(this); </code></pre> <p>};</p>
0
Nested object and array destructuring
<p>I am trying to convert an object to a leaner version using destructuring.</p> <p>My object includes a nested array which also contains objects, from this array I would only like a few fields.</p> <p>I can do the nested object destructuring fine, and the array destructuring fine but not together?</p> <p>My current try looks like this:</p> <pre><code>var data = { title: "title1", bar: "asdf", innerData: [ { title: "inner-title1", foo: "asdf" }, { title: "inner-title2", foo: "asdf" } ] }; var { title, innerData: [ { title} ] } = data; console.log(title); for (var { title} of innerData) { console.log(title); } </code></pre> <p>But get a message saying <code>innerData is not defined.</code></p> <p>The outcome I would like might be:</p> <pre><code>{ title: "title1", innerData: [ { title: "inner-title1" }, { title: "inner-title2" } ] }; </code></pre>
0
What is the difference between isdigit() and isnumber()?
<p>I have the function isnumber() in my ctype.h. I don’t find references of this function in the books I have neither in <a href="http://www.cplusplus.com/reference/cctype/" rel="nofollow">http://www.cplusplus.com/reference/cctype/</a> for consult. I intend to detect and show the difference between isdigit() and isnumber() by a simple example, but there is not (besides, U+0C6A, U+0ED2 and ½ are undetectable by the functions). Is there any difference? How could I resolve that? </p> <pre><code>int main(int, char *[]) { string text("Hello½123, Poly౪ ໒girl0.5!!!"); decltype(text.size()) punct = 0, alpha = 0, number = 0, space = 0, digit = 0, graf = 0; for(auto i : text) { if(ispunct(i)){ cout &lt;&lt; i &lt;&lt; "&lt;punct "; ++punct; } if(isalpha(i)) { cout &lt;&lt; i &lt;&lt; "&lt;alpha "; ++alpha; } if(isnumber(i)) { cout &lt;&lt; i &lt;&lt; "&lt;number "; ++number; } if(isdigit(i)) { cout &lt;&lt; i &lt;&lt; "&lt;digit "; ++digit; } if(isgraph(i)) { cout &lt;&lt; i &lt;&lt; "&lt;graph "; ++graf; } if(isspace(i)) ++space; } cout &lt;&lt; endl &lt;&lt; "There is " &lt;&lt; endl; cout &lt;&lt; punct &lt;&lt; " puncts," &lt;&lt; endl; cout &lt;&lt; alpha &lt;&lt; " alphas," &lt;&lt; endl; cout &lt;&lt; number &lt;&lt; " numbers," &lt;&lt; endl; cout &lt;&lt; digit &lt;&lt; " digits," &lt;&lt; endl; cout &lt;&lt; graf &lt;&lt; " graphs," &lt;&lt; endl; cout &lt;&lt; space &lt;&lt; " spaces" &lt;&lt; endl; cout &lt;&lt; "in " &lt;&lt; text &lt;&lt; endl; return 0; } </code></pre> <p>A part of the result:</p> <pre><code>... 5 numbers, 5 digits, 23 graphs, 2 spaces in Hello½123, Poly౪ ໒girl0.5!!! </code></pre>
0
Injecting IHttpContextAccessor into ApplicationDbContext ASP.NET Core 1.0
<p>I am trying to figure out how to get access to the current logged in username outside of an ASP.NET Controller.</p> <p>For example I am trying to do this:</p> <p><a href="http://benjii.me/2014/03/track-created-and-modified-fields-automatically-with-entity-framework-code-first/" rel="noreferrer">Track Created and Modified fields Automatically with Entity Framework Code First</a></p> <p>To setup tracking on entities in the <code>DbContext</code>.</p> <p>Here is my <code>ApplicationDbContext</code> but I keep getting an error saying <code>_httpContextAccessor</code> is <code>null</code>:</p> <pre><code>private readonly IHttpContextAccessor _httpContextAccessor; public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options, IHttpContextAccessor httpContextAccessor) : base(options) { _httpContextAccessor = httpContextAccessor; } </code></pre>
0
Docker-Compose persistent data MySQL
<p>I can't seem to get MySQL data to persist if I run <code>$ docker-compose down</code> with the following <code>.yml</code></p> <pre><code>version: '2' services: # other services data: container_name: flask_data image: mysql:latest volumes: - /var/lib/mysql command: "true" mysql: container_name: flask_mysql restart: always image: mysql:latest environment: MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this MYSQL_USER: 'test' MYSQL_PASS: 'pass' volumes_from: - data ports: - "3306:3306" </code></pre> <p>My understanding is that in my <code>data</code> container using <code>volumes: - /var/lib/mysql</code> maps it to my local machines directory where mysql stores data to the container and because of this mapping the data should persist even if the containers are destroyed. And the <code>mysql</code> container is just a client interface into the db and can see the local directory because of <code>volumes_from: - data</code></p> <p>Attempted this answer and it did not work. <a href="https://stackoverflow.com/questions/34511336/docker-compose-persistent-data-trouble">Docker-Compose Persistent Data Trouble</a></p> <p><strong>EDIT</strong></p> <p>Changed my <code>.yml</code> as shown below and created a the dir <code>./data</code> but now when I run <code>docker-compose up --build</code> the <code>mysql</code> container wont start throws error saying</p> <pre><code> data: container_name: flask_data image: mysql:latest volumes: - ./data:/var/lib/mysql command: "true" mysql: container_name: flask_mysql restart: always image: mysql:latest environment: MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this MYSQL_USER: 'test' MYSQL_PASS: 'pass' volumes_from: - data ports: - "3306:3306" flask_mysql | mysqld: Can't create/write to file '/var/lib/mysql/is_writable' (Errcode: 13 - Permission denied) flask_mysql | 2016-08-26T22:29:21.182144Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). flask_mysql | 2016-08-26T22:29:21.185392Z 0 [ERROR] --initialize specified but the data directory exists and is not writable. Aborting. </code></pre>
0
How to map Page<ObjectEntity> to Page<ObjectDTO> in spring-data-rest
<p>When I hit the database with <code>PagingAndSortingRepository.findAll(Pageable)</code> I get <code>Page&lt;ObjectEntity&gt;</code>. However, I want to expose DTO's to the client and not entities. I can create DTO just by injecting entity into it's constructor, but how do I map the entities in Page object to DTO's? According to spring documentation, Page provides read-only operations.</p> <p>Also, Page.map is not possibility, as we don't have support for java 8. How to create the new Page with mapped objects manually?</p>
0
Carbon - why addMonths() change the day of month?
<p>Here's the simple example (today is 2016-08-29):</p> <pre><code>var_dump(Carbon::now()); var_dump(Carbon::now()-&gt;addMonths(6)); </code></pre> <p>Output:</p> <pre><code>object(Carbon\Carbon)#303 (3) { ["date"] =&gt; string(26) "2016-08-29 15:37:11.000000" } object(Carbon\Carbon)#303 (3) { ["date"] =&gt; string(26) "2017-03-01 15:37:11.000000" } </code></pre> <p>For <code>Carbon::now()-&gt;addMonths(6)</code> I'm expecting <code>2017-02-29</code>, not <code>2017-03-01</code>.</p> <p>Am I missing something about date modifications?</p>
0
Can I use ng2-file-upload with button instead of a file input?
<p>I'm using <a href="http://valor-software.com/ng2-file-upload/" rel="noreferrer">ng2-file-upload</a> (single upload example) and I want to use: <code>ng2FileSelect</code> with a button or a div instead of a file input. How can I do this?</p> <p>I want this to do something like this:</p> <pre><code>&lt;button ng2FileSelect [uploader]="uploader"&gt;Choose file&lt;/button&gt; </code></pre> <p>Instead of:</p> <pre><code>&lt;input type="file" ng2FileSelect [uploader]="uploader" /&gt; </code></pre> <p>If does not exist a clean way using <a href="http://valor-software.com/ng2-file-upload/" rel="noreferrer">ng2-file-upload</a>, do you know an alternative?</p>
0
FileUriExposedException in Android N with Camera
<p><strong>MainActivity</strong></p> <pre><code>import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Parcelable; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mBtn; private Context context; private static final int SELECT_PICTURE_CAMARA = 101, SELECT_PICTURE = 201, CROP_IMAGE = 301; private Uri outputFileUri; String mCurrentPhotoPath; private Uri selectedImageUri; private File finalFile = null; private ImageView imageView; private PermissionUtil permissionUtil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtn = (Button) findViewById(R.id.btn_img); imageView = (ImageView) findViewById(R.id.img_photo); permissionUtil = new PermissionUtil(); mBtn.setOnClickListener(this); context = this; } @Override public void onClick(View view) { selectImageOption(); } private void selectImageOption() { final CharSequence[] items = {"Capture Photo", "Choose from Gallery", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (items[item].equals("Capture Photo")) { if (permissionUtil.checkMarshMellowPermission()) { if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getCameraPermissions())) onClickCamera(); else ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getCameraPermissions(), SELECT_PICTURE_CAMARA); } else onClickCamera(); } else if (items[item].equals("Choose from Gallery")) { if (permissionUtil.checkMarshMellowPermission()) { if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getGalleryPermissions())) onClickGallery(); else ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getGalleryPermissions(), SELECT_PICTURE); } else onClickGallery(); } else if (items[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { selectedImageUri = data.getData(); cropImage(selectedImageUri); } else if (requestCode == CROP_IMAGE) { /*if (data != null) { // get the returned data Bundle extras = data.getExtras(); // get the cropped bitmap Bitmap selectedBitmap = extras.getParcelable("data"); imageView.setImageBitmap(selectedBitmap); }*/ Uri imageUri = Uri.parse(mCurrentPhotoPath); File file = new File(imageUri.getPath()); try { InputStream ims = new FileInputStream(file); imageView.setImageBitmap(BitmapFactory.decodeStream(ims)); } catch (FileNotFoundException e) { return; } } else if (requestCode == SELECT_PICTURE_CAMARA &amp;&amp; resultCode == Activity.RESULT_OK) { cropImage(Uri.parse(mCurrentPhotoPath)); } } } private void onClickCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) { File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { } if (photoFile != null) { Uri photoURI; if (Build.VERSION.SDK_INT &gt;= 24) { photoURI = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", photoFile); } else { photoURI = Uri.fromFile(photoFile); } takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA); } } } private void onClickGallery() { List&lt;Intent&gt; targets = new ArrayList&lt;&gt;(); Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_PICK); intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); List&lt;ResolveInfo&gt; candidates = getApplicationContext().getPackageManager().queryIntentActivities(intent, 0); for (ResolveInfo candidate : candidates) { String packageName = candidate.activityInfo.packageName; if (!packageName.equals("com.google.android.apps.photos") &amp;&amp; !packageName.equals("com.google.android.apps.plus") &amp;&amp; !packageName.equals("com.android.documentsui")) { Intent iWantThis = new Intent(); iWantThis.setType("image/*"); iWantThis.setAction(Intent.ACTION_PICK); iWantThis.putExtra(Intent.EXTRA_LOCAL_ONLY, true); iWantThis.setPackage(packageName); targets.add(iWantThis); } } if (targets.size() &gt; 0) { Intent chooser = Intent.createChooser(targets.remove(0), "Select Picture"); chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()])); startActivityForResult(chooser, SELECT_PICTURE); } else { Intent intent1 = new Intent(Intent.ACTION_PICK); intent1.setType("image/*"); startActivityForResult(Intent.createChooser(intent1, "Select Picture"), SELECT_PICTURE); } } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents if (Build.VERSION.SDK_INT &gt;= 24) { mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", image)); } else { mCurrentPhotoPath = String.valueOf(Uri.fromFile(image)); } return image; } private void cropImage(Uri selectedImageUri) { Intent cropIntent = new Intent("com.android.camera.action.CROP"); cropIntent.setDataAndType(selectedImageUri, "image/*"); cropIntent.putExtra("crop", "true"); cropIntent.putExtra("aspectX", 1); cropIntent.putExtra("aspectY", 1.5); cropIntent.putExtra("return-data", true); outputFileUri = Uri.fromFile(createCropFile()); cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(cropIntent, CROP_IMAGE); } private File createCropFile() { File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); // path = path + (timeStamp + "1jpg"); File file = null; try { file = File.createTempFile(timeStamp, ".jpg", storageDir); } catch (IOException e) { e.printStackTrace(); } mCurrentPhotoPath = String.valueOf(Uri.fromFile(file)); return file; } } </code></pre> <p><strong>PermissionUtil.java</strong></p> <pre><code>package com.example.shwetachauhan.imagecropasoebi; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.support.v4.app.ActivityCompat; public class PermissionUtil { private String[] galleryPermissions = { "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE" }; private String[] cameraPermissions = { "android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE" }; public String[] getGalleryPermissions(){ return galleryPermissions; } public String[] getCameraPermissions() { return cameraPermissions; } public boolean verifyPermissions(int[] grantResults) { if(grantResults.length &lt; 1){ return false; } for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public boolean verifyPermissions(Context context, String[] grantResults) { for (String result : grantResults) { if (ActivityCompat.checkSelfPermission(context, result) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public boolean checkMarshMellowPermission(){ return(Build.VERSION.SDK_INT&gt; Build.VERSION_CODES.LOLLIPOP_MR1); } public boolean checkJellyBean(){ return(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN); } } </code></pre> <ul> <li>This code is for pick image for crop from Camera or Gallery</li> <li>This code is works for all android OS but when I try to run On Android N device it crash when I open Camera. It works fine in Android N with Gallery.</li> </ul>
0
Composer memory exhausted on shared host
<p>A previously working sandbox on a shared FreeBSD host now fails to run composer update or install with a memory exhausted error. Before yesterday I was able to run <code>php ./composer.phar update</code> without a problem. I do not believe that more memory is required. I can update the project on a Windows system without any issue. What variables other than memory size contribute to the memory exhausted error?</p> <p>To test this I moved the contents of .../vendor and the composer.lock file to a different directory then ran <code>php ./composer.phar install --prefer-dist</code>. [Composer is in the project directory so that I can update it locally rather than expect the host master to keep it updated.] The above command results in:</p> <pre><code>% php ./composer.phar install --prefer-dist Loading composer repositories with package information Updating dependencies (including require-dev) PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 134217728 bytes) in phar:///home/projectmana/www3.projectmana.org/composer.phar/src/Composer/DependencyResolver/Solver.php on line 220 Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 134217728 bytes) in phar:///home/projectmana/www3.projectmana.org/composer.phar/src/Composer/DependencyResolver/Solver.php on line 220 </code></pre> <p>Composer is version 1.20</p> <p>composer.json used:</p> <pre><code>{ "name": "truckee/projectmana", "license": "MIT", "type": "project", "description": "Project MANA administrative application", "autoload": { "psr-0": { "": "src/" } }, "repositories": [ { "type": "package", "package": { "name": "jquery/jquery", "version": "1.11.1", "dist": { "url": "https://code.jquery.com/jquery-1.11.1.js", "type": "file" } } } ], "require": { "braincrafted/bootstrap-bundle": "~2.0", "doctrine/doctrine-bundle": "~1.4", "doctrine/doctrine-fixtures-bundle": "^2.3", "doctrine/orm": "^2.4.8", "friendsofsymfony/user-bundle": "~2.0@dev", "incenteev/composer-parameter-handler": "~2.0", "javiereguiluz/easyadmin-bundle": "~1.1", "jms/security-extra-bundle": "~1.5", "jquery/jquery": "1.11.*", "knplabs/knp-menu-bundle": "~2.0", "nelmio/alice": "^2.1", "oyejorge/less.php": "~1.5", "paragonie/random_compat": "^2.0", "php": "&gt;=5.3.9", "psliwa/pdf-bundle": "dev-master", "sensio/distribution-bundle": "~4.0", "sensio/framework-extra-bundle": "^3.0.2", "symfony/assetic-bundle": "dev-master", "symfony/monolog-bundle": "~2.4", "symfony/swiftmailer-bundle": "~2.3", "symfony/symfony": "2.8.*", "twbs/bootstrap": "3.0.*", "twig/extensions": "1.0.*" }, "scripts": { "post-install-cmd": [ "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile", "Braincrafted\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::install" ], "post-update-cmd": [ "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile", "Braincrafted\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::install" ] }, "config": { "bin-dir": "bin" }, "minimum-stability": "stable", "extra": { "symfony-app-dir": "app", "symfony-web-dir": "htdocs", "incenteev-parameters": { "file": "app/config/parameters.yml" }, "branch-alias": { "dev-master": "2.3-dev" }, "repositories": [ { "type": "composer", "url": "http://packages.zendframework.com/" }, { "type": "composer", "url": "http://packagist.org/" } ] }, "require-dev": { "liip/functional-test-bundle": "^1.4", "symfony/phpunit-bridge": "^3.0" } } </code></pre> <p>Edit: Available memory:</p> <pre><code>% php -r "echo(ini_get('memory_limit'));" 128M </code></pre> <p>Requested <code>free -m</code>: % free -m free: Command not found.</p> <p>with <code>-vv --profile</code>:</p> <pre><code>% composer update -vv --profile [9.9MB/0.01s] Loading composer repositories with package information [10.5MB/0.80s] Updating dependencies (including require-dev) PHP Fatal error: ... </code></pre> <p>Edit #2, fatal error (using composer 1.1.0) continued, as it differs from that above:</p> <pre><code>Allowed memory size of 1073741824 bytes exhausted (tried to allocate 32 bytes) in phar:///usr/local/bin/composer.phar/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52 Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 32 bytes) in phar:///usr/local/bin/composer.phar/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52 </code></pre>
0
Using erase-remove_if idiom
<p>Let's say I have <code>std::vector&lt;std::pair&lt;int,Direction&gt;&gt;</code>.</p> <p>I am trying to use erase-remove_if idiom to remove pairs from the vector. </p> <pre><code>stopPoints.erase(std::remove_if(stopPoints.begin(), stopPoints.end(), [&amp;](const stopPointPair stopPoint)-&gt; bool { return stopPoint.first == 4; })); </code></pre> <p>I want to delete all pairs that have .first value set to 4.</p> <p>In my example I have pairs:</p> <pre><code>- 4, Up - 4, Down - 2, Up - 6, Up </code></pre> <p>However, after I execute erase-remove_if, I am left with:</p> <pre><code>- 2, Up - 6, Up - 6, Up </code></pre> <p>What am I doing wrong here?</p>
0
Submitting a PHP form with onClick
<p>So I currently have a download link and an input field for an email address on my website.</p> <p>In order to download the file you first need to put in your email.</p> <p>I use a form to do this, with the email field being an input field and the download button being a submit button.</p> <p>I like HTML5's form validation (the required fields, field types etc, it all looks very nice).</p> <p>The problem is that if I use onClick in my submit button then none of the nice form validation works.</p> <pre><code>&lt;form&gt; &lt;input type="email" id="email" placeholder="Please enter email" required&gt; &lt;input type="submit" class="btn" onclick="downloadWin()" value="Windows"&gt; &lt;input type="submit" class="btn" onclick="downloadOsx()" value="Osx"&gt; &lt;/form&gt; &lt;script&gt; function downloadWin(){ event.preventDefault(); var email = $("#email").val(); if(email != ''){ if(validateEmail(email)){ location.href='http://s/index.php?page=downloadWin&amp;email='+email; } } } function downloadOsx(){ event.preventDefault(); var email = $("#email").val(); if(email != ''){ if(validateEmail(email)){ location.href='http://s/index.php?page=downloadOsx&amp;email='+email; } } } &lt;/script&gt; </code></pre> <p>This might not be the cleanest way to do it, so please if you think you know a better way tell me :)</p>
0
difference between setTimeout in javascript and $timeout service in angularjs
<p>Iam new to angular framework.Here is my scenario where, I want to change my $scope.variable after a period of time so i used javascript <code>setTimeout</code> method.</p> <pre><code>$scope.variable = 'Previous'; setTimeout(function(){ $scope.variable='NEXT'; },3000); </code></pre> <p>This code doesn't work for me. I used <code>$apply()</code> to make this code work.</p> <p>Later I came to know that angular itself has a $timeout service which does the same work.</p> <pre><code>$scope.variable = 'Previous'; $timeout(function () { $scope.variable = 'NEXT'; }, 2000); </code></pre> <p>How can i compare performance of <code>$timeout</code> service with javascript <code>setTimeout</code>??</p> <p>Why we should use <code>$timeout</code> instead of <code>setTimeout</code>??</p> <p>Please give me some examples and reasons to use it, which shows the performance.</p> <p>Thanks :) </p>
0
Drag and reorder - UICollectionview with sections
<p>Is that possible to do drag and reorder from one section to another section from collectionview - iOS 9.</p> <p>Every time am dragging from 1st section to drop at 4th section am getting below crash,</p> <p>Assertion failure in -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:</p> <pre><code> func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath,toIndexPath destinationIndexPath: NSIndexPath) { let sequence = ArrayrelatedSequence[sourceIndexPath.section] as! SEQ_Sequence relIndexCards = sequence.rel_indexCard if relIndexCards.count &gt; 0 { ArrayIndexcard = [] let arr1: NSMutableArray = [] for item in relIndexCards { arr1.addObject(item) } let descriptor: NSSortDescriptor = NSSortDescriptor(key: "keyP_IndexCard_ID", ascending: false) let arrNew:NSArray = arr1.sortedArrayUsingDescriptors([descriptor]) let i = 0 for item in arrNew { ArrayIndexcard.insert(item as! NSManagedObject, atIndex: i) i+1 } } let temp = self.ArrayIndexcard.removeAtIndex(sourceIndexPath.item) self.ArrayIndexcard.insert(temp, atIndex: destinationIndexPath.item) if islongPressed_Indexcard == true { islongPressed_Indexcard = false let managedContext = appDelegate.managedObjectContext var i = 0 for update in ArrayIndexcard { i = i+1 update.setValue(i, forKey: "keyP_IndexCard_ID") } do { try managedContext.save() collectionview_in_outline.reloadData() } catch let nserror as NSError { print("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } </code></pre> <p>My flow layout code below,</p> <pre><code> class CustomFlowLayout: UICollectionViewFlowLayout { var longPress: UILongPressGestureRecognizer! var originalIndexPath: NSIndexPath? var draggingIndexPath: NSIndexPath? var draggingView: UIView? var dragOffset = CGPointZero override func prepareLayout() { super.prepareLayout() installGestureRecognizer() } func applyDraggingAttributes(attributes: UICollectionViewLayoutAttributes) { attributes.alpha = 0 } override func layoutAttributesForElementsInRect(rect: CGRect) -&gt; [UICollectionViewLayoutAttributes]? { let attributes = super.layoutAttributesForElementsInRect(rect) attributes?.forEach { a in if a.indexPath == draggingIndexPath { if a.representedElementCategory == .Cell { self.applyDraggingAttributes(a) } } } return attributes } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -&gt; UICollectionViewLayoutAttributes? { let attributes = super.layoutAttributesForItemAtIndexPath(indexPath) if let attributes = attributes where indexPath == draggingIndexPath { if attributes.representedElementCategory == .Cell { applyDraggingAttributes(attributes) } } return attributes } func installGestureRecognizer() { if longPress == nil { longPress = UILongPressGestureRecognizer(target: self, action: #selector(CustomFlowLayout.handleLongPress(_:))) longPress.minimumPressDuration = 0.2 collectionView?.addGestureRecognizer(longPress) } } func handleLongPress(longPress: UILongPressGestureRecognizer) { let location = longPress.locationInView(collectionView!) switch longPress.state { case .Began: startDragAtLocation(location) case .Changed: updateDragAtLocation(location) case .Ended: endDragAtLocation(location) default: break } } func startDragAtLocation(location: CGPoint) { guard let cv = collectionView else { return } guard let indexPath = cv.indexPathForItemAtPoint(location) else { return } guard cv.dataSource?.collectionView?(cv, canMoveItemAtIndexPath: indexPath) == true else { return } guard let cell = cv.cellForItemAtIndexPath(indexPath) else { return } originalIndexPath = indexPath draggingIndexPath = indexPath draggingView = cell.snapshotViewAfterScreenUpdates(true) draggingView!.frame = cell.frame cv.addSubview(draggingView!) dragOffset = CGPointMake(draggingView!.center.x - location.x, draggingView!.center.y - location.y) draggingView?.layer.shadowPath = UIBezierPath(rect: draggingView!.bounds).CGPath draggingView?.layer.shadowColor = UIColor.blackColor().CGColor draggingView?.layer.shadowOpacity = 0.8 draggingView?.layer.shadowRadius = 10 invalidateLayout() UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { self.draggingView?.alpha = 0.95 self.draggingView?.transform = CGAffineTransformMakeScale(1.2, 1.2) }, completion: nil) } func updateDragAtLocation(location: CGPoint) { guard let view = draggingView else { return } guard let cv = collectionView else { return } view.center = CGPointMake(location.x + dragOffset.x, location.y + dragOffset.y) if let newIndexPath = cv.indexPathForItemAtPoint(location) { **cv.moveItemAtIndexPath(draggingIndexPath!, toIndexPath: newIndexPath)** draggingIndexPath = newIndexPath } } func endDragAtLocation(location: CGPoint) { guard let dragView = draggingView else { return } guard let indexPath = draggingIndexPath else { return } guard let cv = collectionView else { return } guard let datasource = cv.dataSource else { return } let targetCenter = datasource.collectionView(cv, cellForItemAtIndexPath: indexPath).center let shadowFade = CABasicAnimation(keyPath: "shadowOpacity") shadowFade.fromValue = 0.8 shadowFade.toValue = 0 shadowFade.duration = 0.4 dragView.layer.addAnimation(shadowFade, forKey: "shadowFade") UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { dragView.center = targetCenter dragView.transform = CGAffineTransformIdentity }) { (completed) in if !indexPath.isEqual(self.originalIndexPath!) { datasource.collectionView?(cv, moveItemAtIndexPath: self.originalIndexPath!, toIndexPath: indexPath) } dragView.removeFromSuperview() self.draggingIndexPath = nil self.draggingView = nil self.invalidateLayout() } NSNotificationCenter.defaultCenter().postNotificationName("Needtorefresh", object: nil) collectionView?.reloadData() } </code></pre> <p>}</p>
0
moment-timezone: unix timestamps with timezones
<p>i am using momentjs.com with nodejs and im trying to get unix timestamps for multiple timezones, but sadly the the output is not correct.</p> <p>code:</p> <pre><code>var moment = require('moment-timezone'); var berlin = moment.tz('Europe/Berlin').unix(); var angeles = moment.tz('America/Los_Angeles').unix(); var london = moment.tz('Europe/London').unix(); console.log(berlin); console.log(angeles); console.log(london); </code></pre> <p>output:</p> <pre><code>1472241731 1472241731 1472241731 </code></pre>
0
Nginx client_max_body_size not working
<p>This should be a quick fix. So for some reason I still can't get a request that is greater than 1MB to succeed without returning 413 Request Entity Too Large. </p> <p>For example with the following configuration file and a request of size ~2MB, I get the following error message in my nginx error.log:</p> <pre><code>*1 client intended to send too large body: 2666685 bytes, </code></pre> <p>I have tried setting the configuration that is set below and then restarting my nginx server but I still get the 413 error. Is there anything I am doing wrong?</p> <pre><code>server { listen 8080; server_name *****/api; (*omitted*) client_body_in_file_only clean; client_body_buffer_size 32K; charset utf-8; client_max_body_size 500M; sendfile on; send_timeout 300s; listen 443 ssl; location / { try_files $uri @(*omitted*); } location @parachute_server { include uwsgi_params; uwsgi_pass unix:/var/www/(*omitted*)/(*omitted*).sock; } } </code></pre> <p>Thank you in advance for the help!</p>
0
What does the tsconfig option "lib" do?
<p>I have an existing project that has this line in tsconfig.json:</p> <pre><code>lib:["2016", "DOM"] </code></pre> <p>What is the purpose of this?</p> <p>The only info I could find is this:</p> <blockquote> <p>Specify library file to be included in the compilation. Requires TypeScript version 2.0 or later.</p> </blockquote> <p>What does that mean?</p>
0
How to check if two [String: Any] are identical?
<p>Is there any way to check if two [String: Any] are identical ?</p> <pre><code>let actual: [[String: Any]] = [ ["id": 12345, "name": "Rahul Katariya"], ["id": 12346, "name": "Aar Kay"] ] var expected: [[String: Any]]! if actual == expected { print("Equal") } </code></pre> <p>Basically i want Dictionary to conform to Equatable protocol in Swift 3.</p>
0
Parsing SQL queries in python
<p>I need to built a mini-sql engine in python.So I require a sql-parser for it and I found out about python-sqlparse but am unable to understand how to extract column names or name of the table e.t.c from the SQL query.Can someone help me regarding this matter.</p>
0
Angular2 nested template driven form
<p>This is just madness , looks like there is no way to have a form which one of it's inputs is in a child component .</p> <p>I have read all the blogs and tutorials and everything , no way to work this out .</p> <p>The problem is when a child component is going to have any kind of form directives ( ngModel , ngModelGroup or whatever ..) , it wont work.</p> <p><strong><em>This is only a problem in template driven forms</em></strong></p> <p>This is the <a href="https://plnkr.co/edit/m0u1On?p=preview" rel="noreferrer">plunker</a> :</p> <pre class="lang-ts prettyprint-override"><code>import { Component } from '@angular/core'; @Component({ selector: 'child-form-component', template: ` &lt;fieldset ngModelGroup="address"&gt; &lt;div&gt; &lt;label&gt;Street:&lt;/label&gt; &lt;input type="text" name="street" ngModel&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Zip:&lt;/label&gt; &lt;input type="text" name="zip" ngModel&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;City:&lt;/label&gt; &lt;input type="text" name="city" ngModel&gt; &lt;/div&gt; &lt;/fieldset&gt;` }) export class childFormComponent{ } @Component({ selector: 'form-component', directives:[childFormComponent], template: ` &lt;form #form="ngForm" (ngSubmit)="submit(form.value)"&gt; &lt;fieldset ngModelGroup="name"&gt; &lt;div&gt; &lt;label&gt;Firstname:&lt;/label&gt; &lt;input type="text" name="firstname" ngModel&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Lastname:&lt;/label&gt; &lt;input type="text" name="lastname" ngModel&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;child-form-component&gt;&lt;/child-form-component&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;pre&gt; {{form.value | json}} &lt;/pre&gt; &lt;h4&gt;Submitted&lt;/h4&gt; &lt;pre&gt; {{value | json }} &lt;/pre&gt; ` }) export class FormComponent { value: any; submit(form) { this.value = form; } } </code></pre>
0
Escaping a string with quotes in Laravel
<p>I would like to insert the content of an excel file into my database.<br><br> I simply use a raw query to achieve this.<br><br><hr> <strong>The controller function</strong></p> <pre><code>public function uploadExcel() { $filename = Input::file('import_file')-&gt;getRealPath(); $file = fopen($filename, "r"); $count = 0; while (($emapData = fgetcsv($file, 10000, "\t")) !== FALSE) { $count++; if($count&gt;1) { DB::statement("INSERT INTO `members` ( member_title, member_first_name, member_name_affix, member_last_name, member_private_address, member_private_zip_code, member_private_location, member_private_phone, member_private_mobile, member_private_fax, member_private_mail, member_business_position, member_business_name, member_business_address, member_business_zip_code, member_business_location, member_business_area_code, member_business_phone, member_business_fax, member_business_mobile, member_business_mail, member_join_date, extra ) VALUES ( '$emapData[0]', '$emapData[1]', '$emapData[2]', '$emapData[3]', '$emapData[4]', '$emapData[5]', '$emapData[6]', '$emapData[7]', '$emapData[8]', '$emapData[9]', '$emapData[10]', '$emapData[11]', '$emapData[12]', '$emapData[13]', '$emapData[14]', '$emapData[15]', '$emapData[16]', '$emapData[17]', '$emapData[18]', '$emapData[19]', '$emapData[20]', '$emapData[21]', '$emapData[22]' )"); } } return redirect('index.index'); } </code></pre> <p><hr> <br><strong>My Problem:</strong> There are names in the excel file like Mc'Neal, so I get an error message. <br><strong>How can I escape the apostrophe in laravel??</strong> <br><br> I am really new to laravel and would be happy for any kind of help!</p>
0
How to reset the user/password of Jenkins on Windows?
<p>Maybe a fool question, I installed jenkins on windows by default, have set no user/password, it worked at first, no need to login. But when launch the 8080 webpage now, it hangs the login page, I've tried some normal user/password combinations, none could pass. Also searched the resolution on website, only find some about linux, no about windows, so need help. <a href="https://i.stack.imgur.com/Y1MUM.png" rel="noreferrer">jenkins login page</a></p>
0
How do I trust a self signed certificate from an electron app?
<p>I have an electron app that syncs with a server I own at a <a href="https://XXX.XX.XX.XXX:port" rel="noreferrer">https://XXX.XX.XX.XXX:port</a> that has a self signed certificate. How can I trust that certificate from my electron app? </p> <p>Right now I get: </p> <pre><code>Failed to load resource: net::ERR_INSECURE_RESPONSE </code></pre>
0
How to send and Receive messages using Facebook Messenger API
<p>i am using C# library for FB Messenger API here - <a href="https://www.nuget.org/packages/facebook-messenger-net-lib/" rel="nofollow">https://www.nuget.org/packages/facebook-messenger-net-lib/</a> </p> <p>But i think there is lack of some documentation . i am trying below code to send message but message is not delivering . Token I am using is Page Access Token generated from Graph api explorer tools. </p> <p>Code I am trying ( Console Application Code )</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FacebookMessengerLib; namespace FmAPI { class Program { static void Main(string[] args) { MessengerAPI obj = new MessengerAPI("EAACEdEose0cBAOSSBMZAZCd2OTZBT95ZBQbdd69B4eRbWcrWFdZAvUOrnk57DrnaHZARh3lIgZBGxzolZAMjQry9fiZCFjFzQEJJElZATgzTIQB3HsTZCyaimLzeetd37LhTG3yhwfGlxE7ojtdnupopsN3s1ZAzSgQPuxSsgf56MqpJPwZDZD"); obj.SendTextMessageAsync(660746514005471, "Hello"); } } } </code></pre>
0
How can I provide parameters for webpack html-loader interpolation?
<p>In the <a href="https://github.com/webpack/html-loader" rel="noreferrer">html-loader</a> documentation there is this example </p> <pre><code>require("html?interpolate=require!./file.ftl"); &lt;#list list as list&gt; &lt;a href="${list.href!}" /&gt;${list.name}&lt;/a&gt; &lt;/#list&gt; &lt;img src="${require(`./images/gallery.png`)}"&gt; &lt;div&gt;${require('./components/gallery.html')}&lt;/div&gt; </code></pre> <p>Where does "list" come from? How can I provide parameters to the interpolation scope?</p> <p>I would like to do something like <a href="https://www.npmjs.com/package/template-string-loader" rel="noreferrer">template-string-loader</a> does:</p> <pre><code>var template = require("html?interpolate!./file.html")({data: '123'}); </code></pre> <p>and then in file.html</p> <pre><code>&lt;div&gt;${scope.data}&lt;/div&gt; </code></pre> <p>But it doesn't work. I have try to mix the template-string-loader with the html-loader but it doesn't works. I could only use the template-string-loader but then the images in the HTML are not transformed by webpack.</p> <p>Any ideas? Thank you</p>
0
Java-8 parallelStream(...) -> fill ArrayList
<p>I have tried this code:</p> <pre><code> final List&lt;ScheduleContainer&gt; scheduleContainers = new ArrayList&lt;&gt;(); scheduleResponseContent.getSchedules().parallelStream().forEach(s -&gt; scheduleContainers.addAll(s)); </code></pre> <p>With parallelStream I get either an ArrayIndexOutOfBoundException or a NullpointerException because some entries in <strong>scheduleContainers</strong> are null.</p> <p>With ... .stream()... everything works fine. My question now would be if there is a possibiliy to fix this or did I misuse parallelStream? </p>
0
Django: How to rollback (@transaction.atomic) without raising exception?
<p>I'm using Django's command to perform some tasks involving database manipulation:</p> <pre><code>class SomeCommand(BaseCommand): @transaction.atomic def handle(self, *args, **options): # Some stuff on the database </code></pre> <p>If an exception is thrown during execution of my program, <code>@transaction.atomic</code> guarantees rollback. Can I force this behavior without throwing exception? Something like:</p> <pre><code># Doing some stuff, changing objects if some_condition: # ABANDON ALL CHANGES AND RETURN </code></pre>
0
Module not found: Error: Cannot resolve module 'semantic-ui-css'
<p>I'm trying to use <a href="https://webpack.github.io" rel="noreferrer">Webpack</a> + <a href="http://semantic-ui.com/" rel="noreferrer">Semantic UI</a> but without success. I tried...</p> <ol> <li><code>npm i semantic-ui-css</code></li> <li>In my <code>index.js</code>.. <code>import semantic from 'semantic-ui-css'</code></li> <li><p>I add configuration into my <code>webpack.config.js</code></p> <pre><code>resolve: { alias: {'semantic-ui': path.join(__dirname, "node_modules", "semantic-ui-css", semantic.min.js") } </code></pre></li> </ol> <p>But when I try to buid... error..</p> <blockquote> <p>ERROR in ./src/index.js Module not found: Error: Cannot resolve module 'sematic-ui-css' in /Users/ridermansb/Projects/boilerplate-projects/vue/src @ ./src/index.js 15:20-45</p> </blockquote> <p>Full <a href="https://gitlab.com/boilerplate-projects/vue/tree/webpack_semantic" rel="noreferrer">source here</a></p>
0
Binning time series with pandas
<p>I'm having a time series in form of a <code>DataFrame</code> that I can <code>groupby</code> to a series </p> <pre><code>pan.groupby(pan.Time).mean() </code></pre> <p>which has just two columns <code>Time</code> and <code>Value</code>: </p> <pre><code>Time Value 2015-04-24 06:38:49 0.023844 2015-04-24 06:39:19 0.019075 2015-04-24 06:43:49 0.023844 2015-04-24 06:44:18 0.019075 2015-04-24 06:44:48 0.023844 2015-04-24 06:45:18 0.019075 2015-04-24 06:47:48 0.023844 2015-04-24 06:48:18 0.019075 2015-04-24 06:50:48 0.023844 2015-04-24 06:51:18 0.019075 2015-04-24 06:51:48 0.023844 2015-04-24 06:52:18 0.019075 2015-04-24 06:52:48 0.023844 2015-04-24 06:53:48 0.019075 2015-04-24 06:55:18 0.023844 2015-04-24 07:00:47 0.019075 2015-04-24 07:01:17 0.023844 2015-04-24 07:01:47 0.019075 </code></pre> <p>What I'm trying to do is figuring out how I can bin those values into a sampling rate of e.g. 30 seconds and average those bins with more than one observations.</p> <p>In a last step I'd need to interpolate those values but I'm sure that there's something out there I can use. </p> <p>However, I just can't figure out how to do the binning and averaging of those values. <code>Time</code> is a <code>datetime.datetime</code> object, not a <code>str</code>.</p> <p>I've tried different things but nothing works. Exceptions flying around. </p> <p>Somebody out there who got this?</p>
0
Why cant I do blob detection on this binary image
<p>First, now i am doing the blob detection by Python2.7 with Opencv. What i want to do is to finish the blob detection after the color detection. i want to detect the red circles(marks), and to avoid other blob interference, i want to do color detection first, and then do the blob detection.</p> <p>and the image after color detection is <a href="http://i.stack.imgur.com/eRCe1.png" rel="nofollow">binary mask</a></p> <p>now i want to do blob detection on this image, but it doesn't work. This is my code.</p> <pre><code>import cv2 import numpy as np; # Read image im = cv2.imread("myblob.jpg", cv2.IMREAD_GRAYSCALE) # Set up the detector with default parameters. params = cv2.SimpleBlobDetector_Params() # Change thresholds params.minThreshold = 10; # the graylevel of images params.maxThreshold = 200; params.filterByColor = True params.blobColor = 255 # Filter by Area params.filterByArea = False params.minArea = 10000 detector = cv2.SimpleBlobDetector(params) # Detect blobs. keypoints = detector.detect(im) # Draw detected blobs as red circles. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Show keypoints cv2.imshow("Keypoints", im_with_keypoints) cv2.waitKey(0)` </code></pre> <p>I am really confused by this code, because it work on this image <a href="http://i.stack.imgur.com/c0AXO.jpg" rel="nofollow">white dots</a> I think the white dots image is quiet similar with the binary mask,but why cant i do blob detection on the binary image?could anyone tell me the difference or the right code?</p> <p>Thanks!!</p> <p>Regards, Nan</p>
0
nodejs : TypeError: callback is not a function
<p>I have written below code to read a xml and return a hashmap:</p> <pre><code>this.xmlObjectRepositoryLoader = function (xmlPath, callback){ var map = {} var innerMap = {}; var el; fs.readFile(xmlPath, "utf-8",function(err, data) { if(err){ console.log('File not found!!') } else{ console.log(data) var doc = domparser.parseFromString(data,"text/xml"); var els = doc.getElementsByTagName("Child"); for(var i =0 ; i&lt; els .length;i++){ var e = elements[i]; eName = e.getAttribute("a"); var params = elm.getElementsByTagName("abc"); innerMap = {}; for(var j =0 ; j&lt; params.length;j++){ var param = params[j]; var b = param.getAttribute("b"); var c= param.getAttribute("c"); innerMap[b] = c; } map[el] = innerMap; innerMap={}; }; } console.log(map); return callback(map); }); }; </code></pre> <p>And I am calling <code>xmlObjectRepositoryLoader</code> from below method but it returns error as <code>TypeError: callback is not a function</code>:</p> <pre><code>this.objectLoader = function(filePath){ if (filePath.includes(".xml")) { console.log(this.xmlObjectRepositoryLoader(filePath)); } </code></pre> <p>Can you please let me know where I am wrong and how can I resolve this</p>
0
A transport-level error has occurred when receiving results from the server. SQL Server
<p>I have a Products table.</p> <p>The number of records in the table is : 44990</p> <p>In this Table I have three columns, </p> <p>Column 1 - Attributes NVARCHAR(MAX)</p> <p>Column 2 - Detailed-description NVARCHAR(MAX)</p> <p>Column 3 - Promotion NVARCHAR(MAX)</p> <p>Column 1 has Json Data,</p> <p>Column 2 Has Xml Data, </p> <p>Column 3 has normal text</p> <p>When I try to select these three columns </p> <p>select p.Promotion, P.Attributes, P.DetailedDescriptionASXml from products</p> <p><strong>I get the following error</strong> : </p> <blockquote> <p>A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.)</p> </blockquote>
0
sparkSession/sparkContext can not get hadoop configuration
<p>I am running spark 2, hive, hadoop at local machine, and I want to use spark sql to read data from hive table. </p> <p>It works all fine when I have hadoop running at default <code>hdfs://localhost:9000</code>, but if I change to a different port in core-site.xml:</p> <pre><code>&lt;name&gt;fs.defaultFS&lt;/name&gt; &lt;value&gt;hdfs://localhost:9099&lt;/value&gt; </code></pre> <p>Running a simple sql <code>spark.sql("select * from archive.tcsv3 limit 100").show();</code> in spark-shell will give me the error:</p> <pre><code>ERROR metastore.RetryingHMSHandler: AlreadyExistsException(message:Database default already exists) ..... From local/147.214.109.160 to localhost:9000 failed on connection exception: java.net.ConnectException: Connection refused; ..... </code></pre> <p>I get the AlreadyExistsException before, which doesn't seem to influence the result.</p> <p>I can make it work by creating a new sparkContext:</p> <pre><code>import org.apache.spark.SparkContext import org.apache.spark.sql.SparkSession sc.stop() var sc = new SparkContext() val session = SparkSession.builder().master("local").appName("test").enableHiveSupport().getOrCreate() session.sql("show tables").show() </code></pre> <p>My question is, why the initial sparkSession/sparkContext did not get the correct configuration? How can I fix it? Thanks!</p>
0
How to search if a username exist in the given firebase database?
<pre><code>{ users: { apple: { username : apple email : [email protected] uid : tyutyutyu } mango: { username : mango email : [email protected] uid : erererer } } } </code></pre> <p>This is what I am doing CREATING USER if checkUsername method returns 0</p> <pre><code> if(checkFirebaseForUsername(username)==0) { mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener&lt;AuthResult&gt;() { @Override public void onComplete(@NonNull Task&lt;AuthResult&gt; task) { if (task.isSuccessful()) { Toast.makeText(getBaseContext(),"inside",Toast.LENGTH_LONG).show(); User newUser = new User(); newUser.setUserId(mAuth.getCurrentUser().getUid()); newUser.setUsername(username); newUser.setEmailId(email); try{ mRef.child("users").child(username).setValue(newUser); } catch(Exception e){ Toast.makeText(SignUpActivity.this,"error while inserting",Toast.LENGTH_LONG).show(); } AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this); builder.setTitle(R.string.signup_success) .setPositiveButton(R.string.login_button_label, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(SignUpActivity.this, LoginActivity.class); startActivity(intent); finish(); } }); AlertDialog dialog = builder.create(); dialog.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this); builder.setTitle(R.string.signup_error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } </code></pre> <p>My checkUsername method - </p> <pre><code>public int checkFirebaseForUsername(String passedUsername){ final int[] flag = {0}; final String myPassedUsername = passedUsername; Log.e("tag","working now"); //flag[0]=1; DatabaseReference mTest = FirebaseDatabase.getInstance().getReference(); mTest.child("users").child(passedUsername).addChildEventListener(new ChildEventListener() { @Override public void onDataChanged(DataSnapshot dataSnapshot) { Log.e("tag","checking"); if(dataSnapshot.exists()){ Log.e("tag","exists"); flag[0]=1; } } @Override public void onCancelled(DataSnapshot datasnapshot){ } }); if(flag[0]==1) return 1; else return 0; } </code></pre> <p>This is how I am inserting users in my <strong>firebase-database</strong> and I want to check if a username is available for a new user or not.</p> <p>Therefore I need to check is there any user already registered with that username....Please help I have already tried whatever I could understand after reffering to documentation provided on the official firebase blog but all in vain!!</p>
0
CSS Fixed - alternative way to keep an HTML Element in place
<p>I want to create a web page that has a section at the top that contains the headings, then a section below that contains the data. I then want the headings to stay visible and the data to be able to scroll in the same way you can lock a row in Excel.</p> <pre><code>&lt;div id="heading"&gt;This is my Heading&lt;/div&gt; &lt;div id="data"&gt; &lt;a&gt;1st line of Data&lt;/a&gt; &lt;a&gt;2nd line of Data&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Now I know if in my css I set <code>#heading { position: fixed; top: 0px; left: 0px }</code> then my heading will stay where it is and my data can scroll underneath it. But is there another way of doing this?</p> <p>The reason I want to find a different way is I have a legacy app that uses Frames (yes I know all the reasons not to - but if any of you have had a conversation with your boss where you explain that the fix for a tiny bug is a complete re-write and he/she say's yeah go for it, then I want to come work with you!) and we have Fixed elements in the frames, but if the Frame is set to zero size (closed) then reopened again they just can't be seen in Safari on a mac. The elements are still in the DOM, they should be visible, even their tooltips can be seen and their click events work too.</p> <p>So after many hours of trying to get them to display I figure it's worth looking at an alternative to the <code>css fixed</code>.</p>
0
React js change child component's state from parent component
<p>I have two components: <strong>Parent Component</strong> from which I want to change child component's state:</p> <pre><code>class ParentComponent extends Component { toggleChildMenu() { ????????? } render() { return ( &lt;div&gt; &lt;button onClick={toggleChildMenu.bind(this)}&gt; Toggle Menu from Parent &lt;/button&gt; &lt;ChildComponent /&gt; &lt;/div&gt; ); } } </code></pre> <p>And <strong>Child Component</strong>:</p> <pre><code>class ChildComponent extends Component { constructor(props) { super(props); this.state = { open: false; } } toggleMenu() { this.setState({ open: !this.state.open }); } render() { return ( &lt;Drawer open={this.state.open}/&gt; ); } } </code></pre> <p>I need to either change Child Component's <strong>open</strong> state from Parent Component, or call Child Component's <strong>toggleMenu()</strong> from Parent Component when Button in Parent Component is clicked?</p>
0
How to group by all but one columns?
<p>How do I tell <code>group_by</code> to group the data by all columns except a given one?</p> <p>With <code>aggregate</code>, it would be <code>aggregate(x ~ ., ...)</code>.</p> <p>I tried <code>group_by(data, -x)</code>, but that groups by the negative-of-x (i.e. the same as grouping by x).</p>
0
How to pass parameters in SOAP web service having a Method?
<p>I have never used SOAP based services and I am unsure of using the follwing SOAP Service.</p> <p><a href="http://workforce.wifisocial.in/WebServicesMethods/EmployeesWebService.asmx?op=EmployeesLoginMethod" rel="nofollow noreferrer">http://workforce.wifisocial.in/WebServicesMethods/EmployeesWebService.asmx?op=EmployeesLoginMethod</a></p> <p>In this service I need to pass 4 values with the parameters: username, password, ipaddress and devicename. And the output is in JSON format.</p> <p>Kindly help to achieve the desired result.</p>
0
Firebase Storage - Upload multiple image files in Android
<p>I want to upload and download images from Firebase Storage and show it in a <code>RecyclerView</code>. I can upload and download one image at a time, but I can't with multiple images.</p> <p>How can I do this? </p>
0
plot Latitude longitude points from dataframe on folium map - iPython
<p>I have a dataframe with lat/lon coordinates </p> <pre><code>latlon (51.249443914705175, -0.13878830247011467) (51.249443914705175, -0.13878830247011467) (51.249768239976866, -2.8610415615063034) ... </code></pre> <p>I would like to plot these on to a Folium map but I'm not sure of how to iterate through each of the rows.</p> <p>any help would be appreciated, Thanks in advance!</p>
0
Bootstrap select picker automatically sorting based on key
<p>I am using Bootstrap <a href="https://silviomoreto.github.io/bootstrap-select/" rel="nofollow">selectpicker</a> for populating the select box.</p> <p>I have the data in the DB table like this,</p> <pre><code>*cId* *CountryName* 1 Australia 2 Belgium 3 Canada 4 India 5 Zimbabwe 6 Brazil </code></pre> <p>What I am doing is ordering the data based on <code>countryName</code> and populating cId as <code>option</code> element's key and <code>countryName</code> as <code>option</code> element's value</p> <pre><code>function loadJSONtoSelectBox(selector, options) { $(selector).selectpicker(); $.each(options, function(key, value) { $('&lt;option data-tokens="'+value+'" value="' + key + '"&gt;' + value + '&lt;/option&gt;').appendTo(selector); $(selector).focus(); }); $(selector).selectpicker('refresh'); } </code></pre> <p>But internally it is sorting based on <code>option's</code> value attribute i.e it is showing Brazil(cid is 6) at the end instead of after Belgium, what is the hack to solve this issue? how can I turn off that internal sorting?</p> <p>Fiddle link <a href="https://jsfiddle.net/14a3h2bt/" rel="nofollow">https://jsfiddle.net/14a3h2bt/</a></p> <p>For more reference check my comment here: <a href="https://github.com/silviomoreto/bootstrap-select/issues/1476" rel="nofollow">https://github.com/silviomoreto/bootstrap-select/issues/1476</a></p>
0
Validation on textbox using jquery for pan Number format
<p>I have to add Pan no in my website Application but i have to use jquery for validation so that first 5 no. should be alphabet then 4 no. should be numeric and the last Questions should be alphabet. </p> <pre><code>$('#txtPANNumber').keypress(function (event) { var key = event.which; var esc = (key == 127 || key == 8 || key == 0 || key == 46); //alert(key); //var nor = $("#txtPANNumber").mask("aaaaa9999a"); var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/; var txtpan = $(this).val(); if (txtpan.length &lt; 10 ) { if( txtpan.match( regExp) ){ //event.preventDefault(); } } else { event.preventDefault(); } }); </code></pre> <p>Please provide some solutions</p>
0
regex to match any character or none?
<p>I have the two following peices of strings;</p> <pre><code>line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore </code></pre> <p>I'm trying to grab these two parts;</p> <pre><code>"GET /file/ HTTP/1.1" 302 "" 400 </code></pre> <p>Basically any character in between the two "" or nothing in between "". So far I've tried this;</p> <pre><code>regex_example = re.search("\".+?\" [0-9]{3}", line1) print regex_example.group() </code></pre> <p>This will work with line1, but give an error for line2. This is due to the '.' matching any character, but giving an error if no character exists. </p> <p>Is there any way for it to match any character or nothing in between the two ""?</p>
0
codeigniter database cache configuration
<p>I'm unable to configure database cache to my system. I've tried every configuration that available in internet . please help me out.</p> <pre><code>$db['default'] = array( 'dsn' =&gt; '', 'hostname' =&gt; 'localhost', 'username' =&gt; 'root', 'password' =&gt; '123', 'database' =&gt; 'test', 'dbdriver' =&gt; 'mysqli', 'dbprefix' =&gt; '', 'pconnect' =&gt; FALSE, 'db_debug' =&gt; TRUE, 'cache_on' =&gt; TRUE, 'cachedir' =&gt; 'application/cache', 'char_set' =&gt; 'utf8', 'dbcollat' =&gt; 'utf8_general_ci', 'swap_pre' =&gt; '', 'encrypt' =&gt; FALSE, 'compress' =&gt; FALSE, 'stricton' =&gt; FALSE, 'failover' =&gt; array(), 'save_queries' =&gt; TRUE ); </code></pre> <p>Below is the error message that i'm getting</p> <p>An uncaught Exception was encountered</p> <p>Type: Exception</p> <p>Message: Configured database connection has cache enabled. Aborting.</p> <p>Filename: C:\wamp\www\test\system\libraries\Session\drivers\Session_database_driver.php</p>
0
How to shutdown raspberry pi over ssh
<p>I am accessing my raspberry pi 3 from ssh. Can you tell me how to shut it down from ssh. Whenever I use <code>sudo shutdown -h now</code> the terminal just freezes without any output. If I kill the terminal I can ssh into raspberry again showing it did not shut down.</p>
0
Can I get an image digest without downloading the image?
<p>Similar to the question "<a href="https://stackoverflow.com/questions/32046334/what&#39;s-the-sha256-code-of-a-docker-image">What´s the sha256 code of a docker image?</a>", I would like to find the digest of a Docker image. I can see the digest when I download an image:</p> <pre><code>$ docker pull waisbrot/wait:latest latest: Pulling from waisbrot/wait Digest: sha256:6f2185daa4ab1711181c30d03f565508e8e978ebd0f263030e7de98deee5f330 Status: Image is up to date for waisbrot/wait:latest $ </code></pre> <p>Another question, <a href="https://stackoverflow.com/questions/35186693/what-is-the-docker-registry-v2-api-endpoint-to-get-the-digest-for-an-image">What is the Docker registry v2 API endpoint to get the digest for an image</a> has an answer suggesting the <code>Docker-Content-Digest</code> header.</p> <p>I can see that there is a <code>Docker-Content-Digest</code> header when I fetch the manifest for the image:</p> <pre><code>$ curl 'https://auth.docker.io/token?service=registry.docker.io&amp;scope=repository:waisbrot/wait:pull' -H "Authorization: Basic ${username_password_base64}" # store the resulting token in DT $ curl -v https://registry-1.docker.io/v2/waisbrot/wait/manifests/latest -H "Authorization: Bearer $DT" -XHEAD * Trying 52.7.141.30... * Connected to registry-1.docker.io (52.7.141.30) port 443 (#0) * TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * Server certificate: *.docker.io * Server certificate: RapidSSL SHA256 CA - G3 * Server certificate: GeoTrust Global CA &gt; GET /v2/waisbrot/wait/manifests/latest HTTP/1.1 &gt; Host: registry-1.docker.io &gt; User-Agent: curl/7.43.0 &gt; Accept: */* &gt; Authorization: Bearer LtVRw-etc-etc-etc &gt; &lt; HTTP/1.1 200 OK &lt; Content-Length: 4974 &lt; Content-Type: application/vnd.docker.distribution.manifest.v1+prettyjws &lt; Docker-Content-Digest: sha256:128c6e3534b842a2eec139999b8ce8aa9a2af9907e2b9269550809d18cd832a3 &lt; Docker-Distribution-Api-Version: registry/2.0 &lt; Etag: "sha256:128c6e3534b842a2eec139999b8ce8aa9a2af9907e2b9269550809d18cd832a3" &lt; Date: Wed, 07 Sep 2016 16:37:15 GMT &lt; Strict-Transport-Security: max-age=31536000 </code></pre> <p>However, this header isn't the same. The <code>pull</code> command got me <code>6f21</code> and the header shows <code>128c</code>. Further, the pull command doesn't work for that digest:</p> <pre><code>$ docker pull waisbrot/wait@sha256:128c6e3534b842a2eec139999b8ce8aa9a2af9907e2b9269550809d18cd832a3 Error response from daemon: manifest unknown: manifest unknown </code></pre> <p>whereas things work as I want when I have the correct digest:</p> <pre><code>$ docker pull waisbrot/wait@sha256:6f2185daa4ab1711181c30d03f565508e8e978ebd0f263030e7de98deee5f330 12:46 waisbrot@influenza sha256:6f2185daa4ab1711181c30d03f565508e8e978ebd0f263030e7de98deee5f330: Pulling from waisbrot/wait Digest: sha256:6f2185daa4ab1711181c30d03f565508e8e978ebd0f263030e7de98deee5f330 Status: Image is up to date for waisbrot/wait@sha256:6f2185daa4ab1711181c30d03f565508e8e978ebd0f263030e7de98deee5f330 </code></pre> <p>What I'm looking for is a way to translate the <code>latest</code> tag (which changes all the time) into a fixed digest that I can reliably pull. But I don't want to actually pull it down in order to do this translation.</p>
0
Unable to use FirebaseRecyclerAdapter
<p>I am getting cannot resolve FirebaseRecyclerAdapter when trying to use it even after adding firebase ui in gradle dependency.Thanks in advance</p>
0
Why use as.factor() instead of just factor()
<p>I recently saw Matt Dowle write some code with <code>as.factor()</code>, specifically</p> <pre><code>for (col in names_factors) set(dt, j=col, value=as.factor(dt[[col]])) </code></pre> <p>in <a href="https://stackoverflow.com/questions/7813578/convert-column-classes-in-data-table#comment31200110_20808945">a comment to this answer</a>.</p> <p>I used this snippet, but I needed to explicitly set the factor levels to make sure the levels appear in my desired order, so I had to change</p> <pre><code>as.factor(dt[[col]]) </code></pre> <p>to</p> <pre><code>factor(dt[[col]], levels = my_levels) </code></pre> <p>This got me thinking: what (if any) is the benefit to using <code>as.factor()</code> versus just <code>factor()</code>?</p>
0
get Font Size in Python with Tesseract and Pyocr
<p>Is it possible to get font size from an image using <code>pyocr</code> or <code>Tesseract</code>? Below is my code.</p> <pre><code>tools = pyocr.get_available_tools() tool = tools[0] txt = tool.image_to_string( Imagee.open(io.BytesIO(req_image)), lang=lang, builder=pyocr.builders.TextBuilder() ) </code></pre> <p>Here i get text from image using function <code>image_to_string</code> . And now, my question is, if i can get <code>font-size</code>(number) too of my text.</p>
0
Python importing modules in CMD
<p>Hello thanks for looking. </p> <p>i am trying to import third party modules but having a hard time. </p> <p>I have already done the edit to the environment variable and i get python to show up in cmd but I can not find the correct syntax to do the install. </p> <p>based on the python org site i should use python -m pip install SomePackage</p> <p>i have also read that i should use pip install SomePackage</p> <p>I have tried both and have not had success. I am in windows 10 below is the command prompt of my attempts. </p> <pre><code>C:\Users\T****J&gt;python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; -m pip install send2trash File "&lt;stdin&gt;", line 1 -m pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; pip install send2trash File "&lt;stdin&gt;", line 1 pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; python pip install send2trash File "&lt;stdin&gt;", line 1 python pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; python -m pip install requests File "&lt;stdin&gt;", line 1 python -m pip install requests ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre> <p>thanks again. searched the best i could and maybe i am missing something easy. I am new at this . </p>
0
How to dynamically create component instance with input/output from a service and inject it to DOM separately?
<p>In creating dynamic components in Angular 2, I <a href="https://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468">found</a> <a href="https://www.lucidchart.com/techblog/2016/07/19/building-angular-2-components-on-the-fly-a-dialog-box-example/" rel="nofollow noreferrer">out</a> that this process requires <code>ViewContainerRef</code> in order to add newly created component to DOM.</p> <p>And in passing <code>@Input</code> and <code>@Output</code>to those dynamically created components, I found the answer in the second link above and <a href="https://codedump.io/share/kQakwDKNu0iG/1/passing-input-while-creating-angular-2-component-dynamically-using-componentresolver" rel="nofollow noreferrer">here</a>.</p> <p>However, if I were to create a service named <code>shape.service</code> that contains functions returning different shape components with some <code>@Input</code> like <code>bgColor</code>, I don't know how this service will create a component without specifying DOM location, and how the container-component receives this returned component (probably its type will be <code>ComponentRef</code>) from the service and injects it to the DOM container-component specifies.</p> <p>For example, a service contains a method:</p> <pre><code>getCircle(bgColor:string): ComponentRef&lt;Circle&gt; { let circleFactory = componentFactoryResolver.resolveComponentFactory(CircleComponent); let circleCompRef = this.viewContainerRef.createComponent(circleFactory); circleCompRef.instance.bgColor = bgColor; return circleCompRef; } </code></pre> <p>First question rises here, how do I make <code>this.viewContainerRef</code> point to no where for the meantime? The reason why I'm importing <code>ViewContainerRef</code> is to create component dynamically.</p> <p>Second question is after container-component receives input-specific<code>componentRef</code> from the service, how will it inject to its DOM?</p> <p><strong>UPDATE:</strong> I think my question above wasn't specific enough. I'm in a situation where:</p> <ol> <li>A parent component calls the service and gets the componentRef/s,</li> <li>Creates an object including componentRef/s together with some other data and stores those created object/s into array</li> <li>Passes it to its children as <code>@Input</code>,</li> <li>And let each child inject componentRef to its DOM and use rest of the data in the object in other way.</li> </ol> <p>That means the service calling component has no idea where those componentRef will get injected. In short, I need independent component objects that can be injected to anywhere, anytime I want.</p> <p>I'm reading the rumTimeCompiler solution several times already but I don't really get how that really works. It seems like there's too much work compared to component creation using viewContainerRef. I'll dig into that more if I find no other solution...</p>
0
RxJava onError Can't create handler inside thread that has not called Looper.prepare()
<p>first i will try to explain what im trying to do, next you will see what im doing(code). Since im new at RxJava, and still learning fell free to give me your opinion.</p> <p>So, im calling a network API from server and when start request i call loader(spinner), when finish i hide it and same when i get an error. I would like this generic for all my requests so i get Observable and Observer from parameter. On this method, i just care about hide and show loader.</p> <p>OnError(and here is the trick part), im trying to show a dialog too, but i got the error that you can see on title. <em>Can't create handler inside thread that has not called Looper.prepare()</em></p> <p>Here is the code..</p> <pre><code>protected void makeMyrequest(MyBaseActivity myBaseActivity, Observable observable, Observer observer) { mSubscription = observable .doOnRequest(new Action1&lt;Long&gt;() { @Override public void call(Long aLong) { Log.d(TAG, "On request"); myBaseActivity.showLoader(); } }) .doOnCompleted(new Action0() { @Override public void call() { Log.d(TAG, "onCompleted: Hide spinner"); myBaseActivity.hideLoader(); mSubscription.unsubscribe(); } }) .doOnError(new Action1&lt;Throwable&gt;() { @Override public void call(Throwable throwable) { Log.d(TAG, "onError: Hide spinner"); myBaseActivity.showAlertDialog("error"); myBaseActivity.hideLoader(); } }) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); } </code></pre> <p>On my base activity i have a method to show dialog</p> <pre><code>public void showAlertDialog(String message) { mDialog = new AlertDialog.Builder(this) .setMessage(message) .show(); } </code></pre> <p>The part that matters from stacktracer</p> <pre><code>java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.&lt;init&gt;(Handler.java:200) at android.os.Handler.&lt;init&gt;(Handler.java:114) at android.app.Dialog.&lt;init&gt;(Dialog.java:119) at android.app.Dialog.&lt;init&gt;(Dialog.java:168) at android.support.v7.app.AppCompatDialog.&lt;init&gt;(AppCompatDialog.java:43) at android.support.v7.app.AlertDialog.&lt;init&gt;(AlertDialog.java:95) at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:927) at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:952) at xx.myapp.MyBaseActivity.showAlertDialog </code></pre>
0
How to use "Like" operator in sqlAlchemy
<p>Hi I am a new member in stackoverflow. I am currently using sqlAlchemy in flask. Trying to get the matched categories of string provided with the search url. The code of search url is given below:</p> <pre><code>@productapi.route("/search/category", methods=["GET"]) def search_category(): category_param_value = request.args.get('querystr', None) print(category_param_value) if category_param_value is None: return jsonify(message='Which category you want to search????'), 400 try: category = Category.query.filter_by( title=Category.title.like("category_param_value %")) except SQLAlchemyError as err: return jsonify(message='Category not found.'), 400 category_list = category_schema.dumps(category) return category_list.data, 200 </code></pre> <p>I tried with httpie with following url: http get <a href="http://192.168.1.98:5000/api/v1/search/category?querystr=" rel="noreferrer">http://192.168.1.98:5000/api/v1/search/category?querystr=</a>"test"</p> <p>Error: </p> <pre><code>sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) operator does not exist: character varying = boolean </code></pre> <p>Hoping for a positive response. Thank You.</p>
0
What's the difference between findOneAndUpdate and findOneAndReplace?
<p>I've recently installed the Java MongoDB Driver 3.1.1 version and I'm wondering what's the difference between <code>findOneAndUpdate</code> and <code>findOneAndReplace</code>?</p> <p>In what situation should i use each one?</p>
0
Convert Promise to Observable
<p>I am trying to wrap my head around observables. I love the way observables solve development and readability issues. As I read, benefits are immense. </p> <p>Observables on HTTP and collections seem to be straight forward. How can I convert something like this to observable pattern.</p> <p>This is from my service component, to provide authentication. I'd prefer this to work like other HTTP services in Angular2 - with support for data, error and completion handlers.</p> <pre class="lang-js prettyprint-override"><code>firebase.auth().createUserWithEmailAndPassword(email, password) .then(function(firebaseUser) { // do something to update your UI component // pass user object to UI component }) .catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // ... }); </code></pre> <p>Any help here would be much appreciated. The only alternative solution I had was to create <code>EventEmitter</code>s. But I guess that's a terrible way to do things in services section</p>
0
How to print an object as JSON to console in Angular2?
<p>I'm using a service to load my form data into an array in my angular2 app. The data is stored like this:</p> <pre><code>arr = [] arr.push({title:name}) </code></pre> <p>When I do a <code>console.log(arr)</code>, it is shown as Object. What I need is to see it as <code>[ { 'title':name } ]</code>. How can I achieve that?</p>
0
Swift 3 UnsafePointer($0) no longer compile in Xcode 8 beta 6
<p>My code snipet as follows …:</p> <pre><code> let defaultRouteReachability = withUnsafePointer(to: &amp;zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } </code></pre> <p>… does no longer compile with the following error which I don't understand:</p> <pre><code>"'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type." </code></pre> <p>What to do to fix it?</p>
0
Updating Python using 'PIP'
<p>just like we install packages like Matplotlib, using pip command in the cmd (pip install matplotlib) can we also update to newer version of python by some pip command?</p> <p><img src="https://i.stack.imgur.com/r108C.png" alt="screenshot"></p>
0
Job for docker.service failed because the control process exited with error code
<p>So I installed docker engine on RHEL 7 </p> <p>Now when I do a </p> <pre><code>service docker start </code></pre> <p>I get the following error:</p> <pre><code>Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details. </code></pre> <p>and when I go to "systemctl status docker.service" and "journalctl -xe" I get:</p> <pre><code>docker.service - Docker Application Container Engine Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled) Drop-In: /etc/systemd/system/docker.service.d └─docker.conf Active: failed (Result: exit-code) since Thu 2016-09-08 22:15:53 EDT; 10s ago Docs: https://docs.docker.com Process: 13504 ExecStart=/usr/bin/docker daemon -H fd:// --mtu 1400 --exec-opt native.cgroupdriver=systemd (code=exited, status=1/FAILURE) Main PID: 13504 (code=exited, status=1/FAILURE) Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine... Sep 08 22:15:53 app-linux2.app-netapp.lab.com docker[13504]: time="2016-09-08T22:15:53.227074798-04:00" level=fatal msg="no sockets found via socket activation: make sure the service ...by systemd" Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine. Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state. Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed. </code></pre> <p>And </p> <p>--</p> <pre><code>-- The start-up result is done. Sep 08 22:10:01 app-linux2.app-netapp.lab.com CROND[12753]: (root) CMD (/usr/lib64/sa/sa1 1 1) Sep 08 22:10:01 app-linux2.app-netapp.lab.com systemd[1]: Starting Session 58 of user root. -- Subject: Unit session-58.scope has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit session-58.scope has begun starting up. Sep 08 22:10:53 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:12878:2674931 (system bus name :1.173 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine... -- Subject: Unit docker.service has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit docker.service has begun starting up. Sep 08 22:10:53 app-linux2.app-netapp.lab.com docker[12895]: time="2016-09-08T22:10:53.413304246-04:00" level=fatal msg="no sockets found via socket activation: make sure the service was started by Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine. -- Subject: Unit docker.service has failed -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit docker.service has failed. -- -- The result is failed. Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state. Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed. Sep 08 22:10:53 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:12878:2674931 (system bus name :1.173, object path /org/freedesktop/PolicyKit1/Authent Sep 08 22:13:36 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:13214:2691210 (system bus name :1.174 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob Sep 08 22:13:36 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:13214:2691210 (system bus name :1.174, object path /org/freedesktop/PolicyKit1/Authent Sep 08 22:15:53 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:13489:2704913 (system bus name :1.175 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine... -- Subject: Unit docker.service has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit docker.service has begun starting up. Sep 08 22:15:53 app-linux2.app-netapp.lab.com docker[13504]: time="2016-09-08T22:15:53.227074798-04:00" level=fatal msg="no sockets found via socket activation: make sure the service was started by Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine. -- Subject: Unit docker.service has failed -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit docker.service has failed. -- -- The result is failed. Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state. Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed. Sep 08 22:15:53 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:13489:2704913 (system bus name :1.175, object path /org/freedesktop/PolicyKit1/Authent lines 3473-3523/3523 (END) </code></pre> <p>I tried to search solution for this but could not find any.</p>
0
When to use TouchableNativeFeedback, TouchableHighlight or TouchableOpacity?
<p>In React Native, there are at least three ways to make a button: <code>TouchableNativeFeedback</code>, <code>TouchableHighlight</code> and <code>TouchableOpacity</code>. There is also <code>TouchableWithoutFeedback</code>, which the documentation clearly states you should not use because "all the elements that respond to press should have a visual feedback when touched".</p> <ul> <li><a href="http://facebook.github.io/react-native/releases/0.31/docs/touchablenativefeedback.html#touchablenativefeedback">TouchableNativeFeedback</a> is Android only and "replaces the View with another instance of RCTView"</li> <li><a href="https://facebook.github.io/react-native/docs/touchablehighlight.html#touchablehighlight">TouchableHighlight</a> "adds a view to the view hierarchy"</li> <li><a href="https://facebook.github.io/react-native/docs/touchableopacity.html#touchableopacity">TouchableOpacity</a> works "without changing the view hierarchy"</li> </ul> <p>Are there any other significant differences between the three? Is one of them the goto component? In what case should you use <code>TouchableHighlight</code> over <code>TouchableOpacity</code>? Are there any performance implications?</p> <p>I am writing an application right now, and find that all three have a significant delay between tap and the action (in this case a navigation change). Is there any way to make it snappier?</p>
0
Laravel Passport Key path oauth-public.key does not exist or is not readable
<p>Laravel passport showing this while trying to access resource</p> <pre><code>Key path "file://C:\xampp\htdocs\rental_5.0\storage\oauth-public.key" does not exist or is not readable </code></pre>
0
Detect if the application in background or foreground in swift
<p>is there any way to know the state of my application if it is in background mode or in foreground . Thanks </p>
0
Handling the screen orientation change in ReactJS
<p>I am trying to create a Component whose content changes when the screen orientation(portrait/landscape) changes. This is what I am doing:</p> <pre><code> var Greeting = React.createClass({ getInitialState: function() { return {orientation: true} }, handleChange: function() { if ('onorientationchange' in window) { window.addEventListener("orientationchange", function() { this.setState({ orientation: !this.state.orientation }) console.log("onorientationchange"); }, false); } else if ('onresize' in window) { window.addEventListener("resize", function() { this.setState({ orientation: !this.state.orientation }) console.log("resize"); }, false); } }, render: function() { var message = this.state.orientation ? "Hello" : "Good bye" return &lt;p&gt;{message}&lt;/p&gt;; } }); ReactDOM.render( &lt;Greeting/&gt;, document.getElementById('container')); </code></pre> <p>How to make sure the state is mutated when the orientation change event is fired . </p>
0
How do I remove all stale branches from Github?
<p>We have a lot of branches that are inactive (the newest is 7 months old, the oldest is two years ago).<br> I'd like to remove all of those branches in bulk from the remote if no PR is still open for them.</p> <p>Should I be using Github's API? Should I be using git using snippets like those provided in <a href="https://stackoverflow.com/questions/10325599/delete-all-branches-that-are-more-than-x-days-weeks-old">this StackOverflow question</a>?<br> Is there some Github functionality I'm not familiar with that can help organize our repository?</p>
0
Gravity in LinearLayout - android?
<p>I created bellow Layout :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeStart" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/back" tools:context=".SongsActivity"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/header" android:orientation="vertical"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal"&gt; &lt;ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/felesh_m" /&gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_horizontal|center_vertical" android:gravity="center_horizontal|center_vertical" android:orientation="vertical"&gt; &lt;ImageButton android:id="@+id/imbCenter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|center_vertical" android:background="@null" android:src="@drawable/hosein_hlarge" /&gt; &lt;/LinearLayout&gt; &lt;ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/felesh_m" /&gt; &lt;/LinearLayout&gt; &lt;android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="4" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>See bellow Image :</p> <p><a href="https://i.stack.imgur.com/b2kYF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b2kYF.png" alt="enter image description here"></a></p>
0
Multiple indexes vs single index on multiple columns in postgresql
<p>I could not reach any conclusive answers reading some of the existing posts on this topic.</p> <p>I have certain data at 100 locations the for past 10 years. The table has about 800 million rows. I need to primarily generate yearly statistics for each location. Some times I need to generate monthly variation statistics and hourly variation statistics as well. I'm wondering if I should generate two indexes - one for location and another for year or generate one index on both location and year. My primary key currently is a serial number (Probably I could use location and timestamp as the primary key). </p> <p>Thanks.</p>
0
How do I uninstall Visual Studio 2013?
<p>I installed a VS 2013 trial on my Windows 10 PC. Now the trial period has expired and I want to remove it. However I can not find it listed under Control Panel->Programs->Programs and Features!? </p>
0
Specifying dtypes for read_sql in pandas
<p>I would like to specify the dtypes returned when doing pandas.read_sql. In particular I am interested in saving memory and having float values returned as np.float32 instead of np.float64. I know that I can convert afterwards with astype(np.float32) but that doesn't solve the problem of the large memory requirements in the initial query. In my actual code, I will be pulling 84 million rows, not the 5 shown here. pandas.read_csv allows for specifying dtypes as a dict, but I see no way to do that with read_sql. </p> <p>I am using MySQLdb and Python 2.7.</p> <p>As an aside, read_sql seems to use far more memory while running (about 2x) than it needs for the final DataFrame storage.</p> <pre><code>In [70]: df=pd.read_sql('select ARP, ACP from train where seq &lt; 5', connection) In [71]: df Out[71]: ARP ACP 0 1.17915 1.42595 1 1.10578 1.21369 2 1.35629 1.12693 3 1.56740 1.61847 4 1.28060 1.05935 In [72]: df.dtypes Out[72]: ARP float64 ACP float64 dtype: object </code></pre>
0
NGINX and Angular 2
<p>My current app users routes like this /myapp/, /myapp//, /myaapp/dept/</p> <p>My app is currently deployed in an internal http server with NGINX. The other server that accepts external traffic, also runs NGINX and forwards it to the internal server.</p> <p>I have add baseref=/myapp to the index.html as per documentation</p> <p>If the user goes to <a href="http://www.myexternalserver.com/myapp" rel="noreferrer">http://www.myexternalserver.com/myapp</a>, the app works perfectly. If the user is inside the page and clicks on an internal link like <a href="http://www.myexternalserver.com/myapp/myparameter" rel="noreferrer">http://www.myexternalserver.com/myapp/myparameter</a>, it works. The url in the browser changes, the page is displayed as intended. I am guessing it's processed by Angular 2.</p> <p>Unfortunately when a user types in the url directly: <a href="http://www.myexternalserver.com/myapp/myparameter" rel="noreferrer">http://www.myexternalserver.com/myapp/myparameter</a>, I get a 404 error made by NGINX.</p> <p>I think I have to configure NGINX settings but I don't know how should modify NGINX's config or what to put in the sites-available/default file/</p>
0
How to write OR condition inside which in R
<p>I am unable to figure out how can i write <strong>or condition</strong> inside <strong>which</strong> in R. This statemnet does not work.</p> <pre><code> which(value&gt;100 | value&lt;=200) </code></pre> <p>I know it very basic thing but i am unable to find the right solution.</p>
0
The 'photo' attribute has no file associated with it
<pre><code>Template error: </code></pre> <p>In template D:\virtualEnv\alumni\member\templates\member\index.html, error at line 15</p> <pre><code>The 'photo' attribute has no file associated with it. 5 : &lt;!-- Albums --&gt; 6 : &lt;div class="row"&gt; 7 : &lt;div class="col-sm-12"&gt; 8 : &lt;h3&gt;{{ user.username }}'s Albums&lt;/h3&gt; 9 : &lt;/div&gt; 10 : {% if all_persons %} 11 : {% for person in all_persons %} 12 : &lt;div class="col-sm-4 col-lg-2"&gt; 13 : &lt;div class="thumbnail"&gt; 14 : &lt;a href="{% url 'member:detail' person.id %}"&gt; 15 : &lt;img src=" {{ person.photo.url }} " class="img-responsive"&gt; 16 : &lt;/a&gt; 17 : &lt;div class="caption"&gt; 18 : &lt;h2&gt;{{ person.name }}&lt;/h2&gt; 19 : &lt;h4&gt;{{ person.category }}&lt;/h4&gt; 20 : 21 : &lt;!-- View Details --&gt; 22 : &lt;a href="{% url 'member:detail' person.id %}" class="btn btn-primary btn-sm" role="button"&gt;View Details&lt;/a&gt; 23 : 24 : 25 : </code></pre> <p>Traceback:</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _resolve_lookup 885. current = current[bit]</p> <p>During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:</p> <p>File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request)</p> <p>File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request)</p> <p>File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render()</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\response.py" in render 109. self.content = self.rendered_content</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\response.py" in rendered_content 86. content = template.render(context, self._request)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 208. return self._render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\loader_tags.py" in render 61. result = self.nodelist.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\defaulttags.py" in render 323. return nodelist.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render_annotated(context))</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 1044. output = self.filter_expression.resolve(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in resolve 711. obj = self.var.resolve(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in resolve 852. value = self._resolve_lookup(context)</p> <p>File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _resolve_lookup 893. current = getattr(current, bit)</p> <p>File "D:\virtualEnv\lib\site-packages\django\db\models\fields\files.py" in _get_url 68. self._require_file()</p> <p>File "D:\virtualEnv\lib\site-packages\django\db\models\fields\files.py" in _require_file 46. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)</p> <p>Exception Type: ValueError at / Exception Value: The 'photo' attribute has no file associated with it.</p> <p>my views:</p> <pre><code>class IndexView(generic.ListView): template_name = 'member/index.html' context_object_name = 'all_persons' def get_queryset(self): return Person.objects.all() class DetailView(generic.DetailView): model = Person template_name = 'member/detail.html' class AlbumCreate(CreateView): model = Person fields = '__all__' </code></pre> <p>My models are:</p> <pre><code>class Person(models.Model): name = models.CharField(max_length=128) present_position=models.CharField(max_length=100) organization= models.CharField(max_length=150,blank=True) address = models.CharField(max_length=150, blank=True) tele_land = models.CharField(max_length=15,blank=True) tele_cell = models.CharField(max_length=15, blank=True) email = models.EmailField(max_length=70, blank=True, null=True, unique=True) photo= models.ImageField(upload_to='persons/%Y/%m/%d/',max_length=70, blank=True ) category = models.ForeignKey('Membership', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('member:detail', kwargs={'pk': self.pk}) class Membership(models.Model): category = models.CharField(max_length=50, blank=False) </code></pre> <p>Ursl:</p> <pre><code>from . import views app_name = 'member' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P&lt;pk&gt;[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'member/add/$', views.AlbumCreate.as_view(), name='member-add'), ] </code></pre> <p>detail template:</p> <pre><code>&lt;div class="col-sm-4 col-md-3"&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-body"&gt; &lt;a href="{% url 'member:detail' person.id %}"&gt; {% if member.photo %} &lt;img src="{{ member.photo.url }}" class="img-responsive"&gt; {% else %} &lt;h3&gt;No image to display&lt;/h3&gt; {% endif %} &lt;/a&gt; &lt;p&gt;{{member.name}}&lt;/p&gt; &lt;p&gt;{{member.present_position}}&lt;/p&gt; &lt;p&gt;{{member.organization}}&lt;/p&gt; &lt;p&gt;{{member.address}}&lt;/p&gt; &lt;p&gt;{{member.tele_land}}&lt;/p&gt; &lt;p&gt;{{member.tele_cell}}&lt;/p&gt; &lt;p&gt;{{member.email}}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Project urls:</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from member import urls as member_urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(member_urls, namespace="member")), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <p>Why photo field gives these errors?</p>
0
Shortest way to get last element by class name in javascript
<p>I know that by using <code>jQuery</code> you can easily use <code>:last</code> selector to get the last element.</p> <pre><code>$(&quot;.some-element:last&quot;) </code></pre> <p>Although, this does <strong>not</strong> work with javascript.</p> <pre><code>document.querySelectorAll(&quot;.some-element:last&quot;) </code></pre> <p>What would be the best and shortest way to do the same thing in <code>javascript</code>?</p>
0
How to fix background red color TextInputLayout when isEmpty in Android
<p>I want <strong><code>setError</code></strong> when <code>TextInputLayout</code> <strong><code>isEmpty</code></strong>, I write this code but when show error message, set red background for <code>TextInputLayout</code>! <br></p> <p>I do <strong>not want</strong> set background! <strong>I want</strong> just show the error message.</p> <p><a href="https://i.stack.imgur.com/4FEoY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4FEoY.png" alt="enter image description here"></a></p> <p><strong>My code:</strong> </p> <pre><code>if (TextUtils.isEmpty(userName)) { register_UserName_layout.setError("Insert Username"); } </code></pre> <p><strong>XML code :</strong> </p> <pre><code>&lt;android.support.design.widget.TextInputLayout android:id="@+id/register_userUsernameTextLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/register_headerLayout" android:layout_margin="10dp" android:textColorHint="#c5c5c5"&gt; &lt;EditText android:id="@+id/register_userUserNameText" android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/selector_bg_edit" android:hint="نام کاربری" android:paddingBottom="2dp" android:textColor="@color/colorAccent" android:textCursorDrawable="@drawable/bg_input_cursor" android:textSize="16sp" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; </code></pre> <p>How can I fix this? Thanks all &lt;3</p>
0
Build OpenVPN with specific OpenSSL version
<p>Similar questions have been asked before, but the answers no longer seem to apply as the flags have changed for the configure script. I am trying to compile OpenVPN from the git source on Ubuntu 14.04.5 on both x86 and x64. I have OpenSSL 1.0.1t built and installed to /usr/local/ssl. I've tried various combinations of the configure options and the compiler seems to recognize since</p> <pre><code>./configure OPENSSL_LIBS="-L/usr/local/ssl/ -lssl -lcrypto" OPENSSL_CFLAGS="-I/usr/local/ssl/include/" </code></pre> <p>finishes with no errors, but <code>./configure OPENSSL_LIBS="-L/usr/local/ssl/" OPENSSL_CFLAGS="-I/usr/local/ssl/include/"</code> results in <code>configure: error: openssl check failed</code>. Once you do make and make install, it still reports the system version of OpenSSL: </p> <pre><code>root@anonymous:/usr/local/src/openvpn# openvpn --version OpenVPN 2.3_git [git:master/d1bd37fd508ee046] x86_64-unknown-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [MH] [IPv6] built on Aug 16 2016 library versions: OpenSSL 1.0.1f 6 Jan 2014, LZO 2.06 Originally developed by James Yonan Copyright (C) 2002-2010 OpenVPN Technologies, Inc. &lt;[email protected]&gt; Compile time defines: enable_async_push=no enable_comp_stub=no enable_crypto=yes enable_crypto_ofb_cfb=yes enable_debug=yes enable_def_auth=yes enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown enable_fast_install=yes enable_fragment=yes enable_iproute2=no enable_libtool_lock=yes enable_lz4=yes enable_lzo=yes enable_management=yes enable_multi=yes enable_multihome=yes enable_pam_dlopen=no enable_pedantic=no enable_pf=yes enable_pkcs11=no enable_plugin_auth_pam=yes enable_plugin_down_root=yes enable_plugins=yes enable_port_share=yes enable_selinux=no enable_server=yes enable_shared=yes enable_shared_with_static_runtimes=no enable_small=no enable_static=yes enable_strict=no enable_strict_options=no enable_systemd=no enable_werror=no enable_win32_dll=yes enable_x509_alt_username=no with_crypto_library=openssl with_gnu_ld=yes with_mem_check=no with_plugindir='$(libdir)/openvpn/plugins' with_sysroot=no </code></pre> <p>System OpenSSL:</p> <pre><code>root@anonymous:/usr/local/src/openvpn# openssl version OpenSSL 1.0.1f 6 Jan 2014 </code></pre> <p>Compiled OpenSSL:</p> <pre><code>root@anonymous:/usr/local/ssl/bin# ./openssl version OpenSSL 1.0.1t 3 May 2016 </code></pre> <p>I know it has to be something simple, but I saw other users asking about this on the OpenVPN Forums with no responses as of yet.</p>
0
Extracting a string between other two strings in R
<p>I am trying to find a simple way to extract an unknown substring (could be anything) that appear between two known substrings. For example, I have a string:</p> <p><code>a&lt;-" anything goes here, STR1 GET_ME STR2, anything goes here"</code></p> <p>I need to extract the string <code>GET_ME</code> which is between STR1 and STR2 (without the white spaces).</p> <p>I am trying <code>str_extract(a, "STR1 (.+) STR2")</code>, but I am getting the entire match </p> <pre><code>[1] "STR1 GET_ME STR2" </code></pre> <p>I can of course strip the known strings, to isolate the substring I need, but I think there should be a cleaner way to do it by using a correct regular expression. </p>
0
Validation failed Class must exist
<p>I have been (hours) trouble with associations in Rails. I found a lot of similar problems, but I couldn't apply for my case:</p> <p>City's class:</p> <pre><code>class City &lt; ApplicationRecord has_many :users end </code></pre> <p>User's class:</p> <pre><code>class User &lt; ApplicationRecord belongs_to :city validates :name, presence: true, length: { maximum: 80 } validates :city_id, presence: true end </code></pre> <p>Users Controller:</p> <pre><code>def create Rails.logger.debug user_params.inspect @user = User.new(user_params) if @user.save! flash[:success] = "Works!" redirect_to '/index' else render 'new' end end def user_params params.require(:user).permit(:name, :citys_id) end </code></pre> <p>Users View:</p> <pre><code>&lt;%= form_for(:user, url: '/user/new') do |f| %&gt; &lt;%= render 'shared/error_messages' %&gt; &lt;%= f.label :name %&gt; &lt;%= f.text_field :name %&gt; &lt;%= f.label :citys_id, "City" %&gt; &lt;select name="city"&gt; &lt;% @city.all.each do |t| %&gt; &lt;option value="&lt;%= t.id %&gt;"&gt;&lt;%= t.city %&gt;&lt;/option&gt; &lt;% end %&gt; &lt;/select&gt; end </code></pre> <p>Migrate:</p> <pre><code>class CreateUser &lt; ActiveRecord::Migration[5.0] def change create_table :user do |t| t.string :name, limit: 80, null: false t.belongs_to :citys, null: false t.timestamps end end </code></pre> <p>Message from console and browser:</p> <pre><code>ActiveRecord::RecordInvalid (Validation failed: City must exist): </code></pre> <p>Well, the problem is, the attributes from User's model that aren't FK they are accept by User.save method, and the FK attributes like citys_id are not. Then it gives me error message in browser saying that "Validation failed City must exist".</p> <p>Thanks</p>
0
How to download a PDF to a new tab/window without popup blocker?
<p>I have the following service call to download files from the server. I currently have it so that PDFs will open up in a new tab/window, and any other document types will be downloaded.</p> <p>The problem I'm having right now is that the PDF is being prevented by a pop up blocker. Is there any way around this?</p> <pre><code> return formService.getForm(params) .$promise .then(response =&gt; { var blob = new Blob([response.data], { type: response.responseType }); var fileUrl = (window.URL || window.webkitURL).createObjectURL(blob); if (response.responseType === 'application/pdf') { window.open(fileUrl); } else { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none" a.href = fileUrl; a.download = formName; a.target = "_blank"; a.click(); window.URL.revokeObjectURL(fileUrl); } }) .catch(error =&gt; { console.error(`Error downloading form '${formName}' `, error); }); </code></pre>
0
Get timestamp in seconds from python's datetime
<p>How to get timestamp from the structure datetime? What is right alternative for non-existing <code>datetime.utcnow().timestamp()</code>?</p>
0
meaning of wildchar **/.* in package.json
<p>what is the meaning of the wild char path <code>**/.*</code>. I see these paths are used in <code>package.json</code>. Can anyone point to the wild char path syntax used in <code>package.json</code>?</p>
0
Making Google Chart Responsive
<p>I am relatively new to HTML, CSS and Javascript. I'm writing a JSP application (I am a Java programmer) and have been learning about responsive web design. I'm running into trouble getting some google charts to work with responsive design. I have two charts side by side on the page.</p> <p>I Have even used an example of how to get responsive google charts on codepen. When I use it on codepen's website, the example works. But when I save it on my computer and open the file, the charts are no longer responsive. It makes me think it's not the code itself that's wrong but something with my browser. Any help will be greatly appreciated. </p> <p>Here's the code I have for my JSP application. The HTML:</p> <pre><code>&lt;div class="charts"&gt; &lt;div class="pieChartDiv"&gt; &lt;div id="piechart"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="lineChartDiv"&gt; &lt;div id="chart_div"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The CSS:</p> <pre><code>.charts { width: 80%; height: 35%; border: 1px solid blue; overflow: hidden; margin: auto; margin-top: 50px; background: #CFC3F8; box-shadow: 10px 10px 5px #888888; } .pieChartDiv { padding: 0; float: right; width: 50%; height: 100%; border-left: 1px solid white; } .lineChartDiv { float: left; width: 50%; height: 100%; } #piechart { width: 100%; height: 100%; } #chart_div { width: 100%; height: 100%; } @media only screen and (max-width: 460px) { .charts { width: 80%; height: 70%; } .pieChartDiv { width: 100%; height: 50%; border: none; border-bottom: 1px solid white; } .lineChartDiv { width: 100%; height: 50%; } } </code></pre> <p>The Javascript for the charts:</p> <pre><code>&lt;script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; google.charts.load('43', {packages: ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Cakes', 11], ['Cupcakes', 2], ['Cookies', 2], ['Other', 2], ]); var options = { title: 'Product Sales', 'legend':'left', 'is3D':true, 'width':550, 'height':320, backgroundColor: '#CFC3F8', }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } &lt;/script&gt; &lt;script&gt; google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data = new google.visualization.DataTable(); data.addColumn('number', 'X'); data.addColumn('number', 'Sales'); data.addRows([ [0, 0], [1, 10], [2, 23], [3, 17], [4, 18], [5, 9], [6, 11], [7, 27], [8, 33], [9, 40], [10, 32], [11, 35], [12, 30], [13, 40], [14, 42], [15, 47], [16, 44], [17, 48], [18, 52], [19, 54], [20, 42], [21, 55], [22, 56], [23, 57], [24, 60], [25, 50], [26, 52], [27, 51], [28, 49], [29, 53], [30, 55], [31, 60], [32, 61], [33, 59], [34, 62], [35, 65], [36, 62], [37, 58], [38, 55], [39, 61], [40, 64], [41, 65], [42, 63], [43, 66], [44, 67], [45, 69], [46, 69], [47, 70], [48, 72], [49, 68], [50, 66], [51, 65], [52, 67], [53, 70], [54, 71], [55, 72], [56, 73], [57, 75], [58, 70], [59, 68], [60, 64], [61, 60], [62, 65], [63, 67], [64, 68], [65, 69], [66, 70], [67, 72], [68, 75], [69, 80] ]); var options = { hAxis: { title: 'Time' }, vAxis: { title: 'Popularity' }, hAxis: {gridlines: {color: '#1E4D6B'}}, vAxis: {gridlines: {color: '#1E4D6B'}}, legend: { position: 'top' }, backgroundColor: '#CFC3F8' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } &lt;/script&gt; </code></pre> <p>Screenshots of the page and the page sized small:</p> <p><a href="https://i.stack.imgur.com/CBvMZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CBvMZ.png" alt="Google Charts"></a></p> <p><a href="https://i.stack.imgur.com/nCZ8G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nCZ8G.png" alt="Non-responsive Charts"></a></p> <p>It seems like the first chart will not resize. The example from codepen acts the same way.</p> <p>Codepen example: </p> <p><a href="https://codepen.io/flopreynat/pen/BfLkA" rel="nofollow noreferrer">https://codepen.io/flopreynat/pen/BfLkA</a></p> <p>I might be way off, so please bear with me. Any advice would be very helpful. </p>
0
How to use merge in pandas
<p>Sorry guys, I know it is a very basic question, I'm just a beginner</p> <pre><code>In [55]: df1 Out[55]: x y a 1 3 b 2 4 c 3 5 d 4 6 e 5 7 In [56]: df2 Out[56]: y z b 1 9 c 3 8 d 5 7 e 7 6 f 9 5 </code></pre> <p>pd.merge(df1, df2) gives:</p> <pre><code>In [56]: df2 Out[56]: x y z 0 1 3 8 1 3 5 7 2 5 7 6 </code></pre> <p>I'm confused the use of merge, what does '0','1','2' mean? For example,when the index is 0, why x is 1, y is 3 and z is 8?</p>
0
How to play sounds on python with tkinter
<p>I have been working on a sort of 'Piano' on python. I have used tkinter as the ui, and this is how it goes:</p> <pre><code>from tkinter import* tk =Tk() btn = Button(tk, text="c note", command = play) </code></pre> <p>How do I define the function <code>play</code> to play a sound when I press it? <br> Please Help.</p>
0
How to stop an Observable interval manually?
<p>I am currently trying to make a 20 second timer like this:</p> <pre><code>this.timer = Observable.interval(1000).take(20).map((tick) =&gt; tick+1).subscribe((tick) =&gt; { this.reverseTimer = 20-tick; }) </code></pre> <p>This is fine if I let the Observable reach 20 every time, but sometimes, I want to end the timer early. Right now, I can't stop the timer until it stops itself after 20 seconds. </p> <p>Right now, I am hiding the timer in the display when I want it to stop, but I need it to be able to restart. If I try to restart the timer before 20 seconds, <code>reverseTimer</code> flickers between the new timer and old timer values because I haven't stopped the old timer. </p> <p>I have tried <code>this.timer.unsubscribe()</code> but I get the error that <code>unsubscribe</code> does not exist for timer. </p>
0
Open a ViewController from remote notification
<p>I try to open a particular ViewController when my app catch a remote notification.</p> <p>Let me show my project's architecture. Here my storyboard : <a href="https://i.stack.imgur.com/MgSVG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MgSVG.png" alt="enter image description here"></a> </p> <p>When I receive a notification I want open a "SimplePostViewController", so this is my appDelegate :</p> <pre><code>var window: UIWindow? var navigationVC: UINavigationController? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -&gt; Bool { let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound] let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil) let storyboard = UIStoryboard(name: "Main", bundle: nil) self.navigationVC = storyboard.instantiateViewControllerWithIdentifier("LastestPostsNavigationController") as? UINavigationController application.registerUserNotificationSettings(pushNotificationSettings) application.registerForRemoteNotifications() return true } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { if let postId = userInfo["postId"] as? String { print(postId) let api = EVWordPressAPI(wordpressOauth2Settings: Wordpress.wordpressOauth2Settings, site: Wordpress.siteName) api.postById(postId) { post in if (post != nil) { self.navigationVC!.pushViewController(SimplePostViewController(), animated: true) } else { print("An error occurred") } } } } </code></pre> <p>I save my UINavigationViewController when the app is launch and simply try to push a new SimplePostViewController when I receive a notification. But nothing happen. I placed breakpoints and seen that my pushViewController method was reached, but not the ViewWillAppear of my SimplePostViewController.</p> <p>I also used the "whats new" view add perform my segue but nothing happen too. </p> <p><strong>Solution :</strong></p> <pre><code>for child in (self.rootViewController?.childViewControllers)! { if child.restorationIdentifier == "LastestPostsNavigationController" { let lastestPostsTableViewController = (child.childViewControllers[0]) as! LastestPostsTableViewController let simplePostVC = (self.storyboard?.instantiateViewControllerWithIdentifier("PostViewController"))! as! PostViewController simplePostVC.post = post lastestPostsTableViewController.navigationController?.pushViewController(simplePostVC, animated: true) } } </code></pre> <p>I use :</p> <pre><code>child.childViewControllers[0] </code></pre> <p>because I've only one child in my example.</p>
0
float does not work in a flex container
<p>I want to position text (foo link) in right of the footer element.</p> <p>I need footer display to remain <code>flex</code>.</p> <p>But when I set it to <code>flex</code>, <code>float:right</code> for span doesn't work anymore. </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;footer style="display: flex;"&gt; &lt;span style="text-align: right;float: right;"&gt; &lt;a&gt;foo link&lt;/a&gt; &lt;/span&gt; &lt;/footer&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/dhsgvxdx/" rel="noreferrer">https://jsfiddle.net/dhsgvxdx/</a></p>
0
What does it mean to add a directory to your PATH?
<p>I'm following the Python tutorial for Google App Engine, and this is the step:</p> <blockquote> <p>Add the google_appengine directory to your PATH: export PATH=$PATH:/path/to/google_appengine/</p> </blockquote> <p>source: <a href="https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python" rel="nofollow">https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python</a></p>
0
getting "No qualifying bean of type is defined."
<p>I am getting exception - </p> <pre><code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.muztaba.service.VerdictServiceImpl] is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1066) at com.muztaba.service.App.task(App.java:35) at com.muztaba.service.App.main(App.java:28) </code></pre> <p>This is the class from where I am getting there exception. </p> <pre><code>@Component public class App { QueueService&lt;Submission&gt; queue; Compiler compiler; VerdictService verdictService; public static void main( String[] args ) { new App().task(); } private void task() { AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); queue = context.getBean(QueueImpl.class); compiler = context.getBean(CompilerImpl.class); verdictService = context.getBean(VerdictServiceImpl.class); //here the exception thrown. while (true) { if (!queue.isEmpty()) { Submission submission = queue.get(); compiler.submit(submission); } } } } </code></pre> <p>First two variable injected properly but the verdictService is not. this is my <code>VerdictService</code> and <code>VerdictServiceImpl</code> interface and class. </p> <pre><code>public interface VerdictService { void post(Verdict verdict); } </code></pre> <p>==</p> <pre><code>@Service @Transactional public class VerdictServiceImpl implements VerdictService { @Autowired SessionFactory sessionFactory; @Override public void post(Verdict verdict) { sessionFactory.getCurrentSession() .save(verdict); } } </code></pre> <p>and this is my configuration class </p> <pre><code>@Configuration @EnableScheduling @ComponentScan(basePackages = "com.muztaba") public class AppConfig { } </code></pre> <p>I have also give my project directory structure. </p> <p><a href="https://i.stack.imgur.com/OX9aa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OX9aa.png" alt="enter image description here"></a></p> <p>What I am missing here ? thank you.</p>
0
Managing contents of requirements.txt for a Python virtual environment
<p>So I am creating a brand new Flask app from scratch. As all good developers do, my first step was to create a virtual environment.</p> <p>The first thing I install in the virtual environment is <code>Flask==0.11.1</code>. Flask installs its following dependencies:</p> <blockquote> <ul> <li>click==6.6</li> <li>itsdangerous==0.24</li> <li>Jinja2==2.8</li> <li>MarkupSafe==0.23</li> <li>Werkzeug==0.11.11</li> <li>wheel==0.24.0</li> </ul> </blockquote> <p>Now, I create a <strong>requirements.txt</strong> to ensure everyone cloning the repository has the same version of the libraries. However, my dilemma is this:</p> <ul> <li>Do I mention each of the Flask dependencies in the <strong>requirements.txt</strong> along with the version numbers OR</li> <li>Do I just mention the exact Flask version number in the <strong>requirements.txt</strong> and hope that when they do a <strong>pip install requirements.txt</strong>, Flask will take care of the dependency management and they will download the right versions of the dependent libraries</li> </ul>
0
Pandas expand rows from list data available in column
<p>I have a data frame like this in pandas:</p> <pre><code> column1 column2 [a,b,c] 1 [d,e,f] 2 [g,h,i] 3 </code></pre> <h1><strong>Expected output:</strong></h1> <pre><code>column1 column2 a 1 b 1 c 1 d 2 e 2 f 2 g 3 h 3 i 3 </code></pre> <p>How to process this data ? </p>
0
How to serve media files on Django production environment?
<p>In me settings.py file :-</p> <pre><code>DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' LOGIN_URL = '/login/' MEDIA_URL = '/media/' </code></pre> <p>In my urls.py file:-</p> <pre><code>urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) </code></pre> <p>When I am uploading the profile image then it is uploading to specified folder. but when i am visiting the user profile url then i am getting error like this in terminal</p> <pre><code>"GET /media/profile_images/a_34.jpg HTTP/1.1" 404 103 </code></pre> <p>a_34.png is present in /media/profile_images/</p> <p>then why it is not showing on browser and i am getting 404 error?</p>
0
grpc and zeromq comparsion
<p>I'd like to compare somehow capabilities of grpc vs. zeromq &amp; its patterns: and I'd like to create some comparsion (feature set) - somehow - 0mq is "better" sockets - but anyways - if I apply 0mq patterns - I get comparable 'frameworks' I think - and here 0mq seems to be much more flexible ...</p> <p>The main requirements are:</p> <ul> <li>async req / res communication (inproc or remote) between nodes</li> <li>flexible messages routing </li> <li>loadbalancing support</li> <li>well documented</li> </ul> <p>any ideas? </p> <p>thanks!</p>
0
Error:SSL peer shut down incorrectly
<p>I'm coding in Android studio. I cloned a project from gitHub </p> <p><a href="https://github.com/QuadFlask/colorpicker" rel="nofollow noreferrer">https://github.com/QuadFlask/colorpicker</a></p> <p>but I have this problem,</p> <p><a href="https://i.stack.imgur.com/WixEx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WixEx.png" alt="enter image description here"></a></p> <p>I don't know how to solve it because I'm new in android studio.</p>
0
TCP IP Listener in windows Service
<p>I'm trying to create a windows service that needs to run in the background and listen for incoming traffic (a normal and regular TCP listener) </p> <p>my code is:</p> <pre><code>private TcpListener server; public void startServer() { // EventLog.WriteEntry(source, "connected on: " + ipAddress.ToString() + " port: " + Service1.Port.ToString()); server = new TcpListener(IPAddress.Parse("127.0.0.1"), Service1.Port); server.Start(); while (true) { var client = server.AcceptTcpClient(); new Thread(work).Start(client); } public void work(object client) { string msg = null; var clientLocal = (TcpClient)client; using (NetworkStream ns = clientLocal.GetStream()) using (StreamReader sr = new StreamReader(ns)) { byte[] msgFullArray = new UTF8Encoding(true).GetBytes(msg); fs.Write(msgFullArray, 0, msg.Length); } </code></pre> <p>now if you don't look at the work method at all as whenever i start my service it freezes whenever i try to start it at my :</p> <pre><code> var client = server.AcceptTcpClient(); </code></pre> <p>meaning my service never gets to use the Thread or my Work method.. i can see from previous logging that it enters my while loop and then just times out the service</p>
0
Using instanceof to test for base class of a React component
<p>To support nested navigation menu's, we're using React.cloneElement to add properties to child menu components (the menu components are custom components, based on react-bootstrap). To prevent that we're cloning all elements even though they are not child menu components, but regular content components, I want make the cloning conditional.</p> <p>All menu components are sub classes of 'MenuBase' (which itself is a sub class of React.Component). In my code, I tried to test whether a child of a react component (reading this.props.children by use of the React.Children utility functions) is an instance of MenuBase.</p> <p>Simplified code:</p> <pre><code>interface IMenuBaseProps { // menu related properties } abstract class MenuBase&lt;P extends IMenuBaseProps, S&gt; extends React.Component&lt;P, S&gt; { // constructor etc. } interface IGeneralMenuProps extends IMenuBaseProps { // additional properties } class GeneralMenu extends MenuBase&lt;IGeneralMenuProps, {}&gt; { public render(): JSX.Element { // do some magic } } </code></pre> <p>Somewhere in the menu logic I want to do something like the following</p> <pre><code>React.Children.map(this.props.children, (child: React.ReactElement&lt;any&gt;): React.ReactElement&lt;any&gt; ==&gt; { if (child instanceof MenuBase) { // return clone of child with additional properties } else { // return child } } </code></pre> <p>However, this test never results in true and as a result a clone is never made.</p> <p>In the Chrome developer tools I can see that:</p> <ol> <li>child.type = function GeneralMenu(props)</li> <li>child.type.prototype = MenuBase</li> </ol> <p><a href="https://i.stack.imgur.com/C85Cy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C85Cy.png" alt="typescript child watch"></a></p> <p>Can somebody help me to clarify the following:</p> <ol> <li>Why is instanceof not working</li> <li>If I'm not able to use instance of the test for something in the inheritance chain of react components, what are my alternatives (I know I can test for the existence of one of the properties of IMenuBaseProps, but I don't really like that solution).</li> </ol>
0
How to make flexbox responsive?
<p>I have a div with two elements that I want to stack horizontally. Div#C has fixed width, and div#B will fill up the rest of the space. However the contents of div#B might be fixed width (which is dynamic) or 100% width (of div#B). </p> <p>The effect I want is, if the screen width is small enough such that, right before div#B and div#C start to overlap or if the width of div#B is small enough, I want div#B and div#C to stack vertically, and each have width 100% of div#A. The problem is if I use a media query, I have to give a fixed min width for it to stack horizontally. With a fixed width, it doesn't account for any fixed width content in div#B. Does anyone know how to fix this preferably only in CSS?</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>#A { display:flex; } #B { flex:1; } #C { width:300px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="A"&gt; &lt;div id="B"&gt;b&lt;/div&gt; &lt;div id="C"&gt;c&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
0
Detect previous path in react router?
<p>I am using react router. I want to detect the previous page (within the same app) from where I am coming from. I have the router in my context. But, I don't see any properties like "previous path" or history on the router object. How do I do it?</p>
0