title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Define a form option allowed values depending on another option value in a FormType
<p>In Symfony 2.8, in a custom form type, is it possible to make setAllowedValues return a result that depends on the value of another option? There isn't an obvious way to access an <code>Options</code> object in the closure as far as I can see.</p> <pre><code>public function configureOptions(OptionsResolver $resolver) { $resolver-&gt;setRequired('option1'); $resolver-&gt;setRequired('option2'); $resolver-&gt;setAllowedValues('option2', function ($value) { return $based_on_set_restricted_by_option1; // &lt;-- option2 values are allowed or denied depending on what option1 says } } </code></pre> <p>The closest idea to a solution that I have is to have an option that is a dictionary that encapsulates both option1 and option2 and do setAllowedValues on it instead, but it's not easy to restructure the options right now.</p>
1
Golang Converting Image magick object to []byte
<p>I am using the following code which fetch the object from Amazon s3 and after performing resizing and cropping. I want to store it on s3. But the problem is i am not able convert the <code>mw (Image maigck object)</code> to byte array. Which will be used for storing it on s3. Moreover in current method it uses jpeg.Encode. What if the image in .png or .gif format. How will we convert it to []byte? </p> <p>Could you please also tell me how to evenly crop an image just passing the aspect ratio not cropping coordinates. <code>imgStream.Crop((int)originalWidth, ((int)(originalWidth / masterAspectRatio)), Gravity.Center)</code> like we do it in .net. Reason i am asking is there is no method in library which provides this flexibility. </p> <pre><code>s3Client := s3.New(session.New(), &amp;aws.Config{Region: aws.String(region)}) params := &amp;s3.GetObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(keyName), } out, err := s3Client.GetObject(params) if err != nil { log.Fatal(err) } img, err := ioutil.ReadAll(out.Body) if err != nil { log.Fatal(err) } mw := imagick.NewMagickWand() err = mw.ReadImageBlob(img) if err != nil { log.Fatal(err) } //Perform resizing and cropping on mw object buf := new(bytes.Buffer) err = jpeg.Encode(buf, mw, nil) sendmw_s3 := buf.Bytes() paramsPut := &amp;s3.PutObjectInput{ Bucket: aws.String(masterBucketName), Key: aws.String(keyName), Body: bytes.NewReader(sendmw_s3), } resp, err := s3Client.PutObject(paramsPut) if err != nil { log.Fatal(err) } </code></pre> <p>Error : </p> <pre><code> cannot use mw (type *imagick.MagickWand) as type image.Image in argument to jpeg.Encode: *imagick.MagickWand does not implement image.Image (missing At method) </code></pre>
1
Inheritance & BASE Classes in ASP.NET MVC
<p>I’m trying to understand inheritance within an MVC application and I have a couple of things I would like clear up if someone can please help.</p> <p><strong>Question 1</strong></p> <p>If I have the following three classes which inherit off each other as follows</p> <pre><code>Public class StandardPage Public class ArticlePage : StandardPage Public class NewsPage : ArticlePage </code></pre> <p>Is the StandardPage class the only BASE class here or is the ArticlePage class also referred to as a BASE class because the NewsPage class derives from it? </p> <p>In a nut shell are classes that derive from other classes also referred to as BASE classes (for the class that inherits it)?</p> <p><strong>Question 2</strong></p> <p>If I have the above classes defined when working in the strongly typed view file (with Razor), if I write the following code</p> <pre><code>@foreach (var article in Model.Articles) { if (article is StandardPage) { var articlePage = article as StandardPage; </code></pre> <p>If the object inside the article var is of type StandardPage, ArticlePage or news page then the articlePage var will be populated without any issues because StandardPage is the BASE class which ArticlePage &amp; NewsPage both inherit from, however if I change the code to the following </p> <pre><code>@foreach (var article in Model.Articles) { if (article is StandardPage) { var articlePage = article as ArticlePage; </code></pre> <p>When the object inside the article var is of type StandardPage I will receive an ‘Object reference not set to an instance of an object’ when trying to populate the articlePage var because StandardPage does not inherit from an ArticlePage (it’s the other way around) and therefore I can’t cast something of type StandardPage into and ArticlePage.</p> <p>Fingers crossed im nearly there with understanding this but if im way off the mark could someone please point me in the right direction</p> <p>Thanks in advance</p>
1
Dynamic Header Titles with React
<p>I was wondering how I would go about being able to have different header titles using only 1 header file with React? I don't want to have to have a header for each component but want to have a title for each view that is changed. Any thoughts?</p>
1
Display when key is pressed in opencv
<p>There is a program which takes live feed from camera: I want to perform some operations when a key from keyboard is pressed without disturbing the on going process. I tried </p> <pre><code>if(waitKey(30) == '27') cout &lt;&lt; "ESC pressed"; </code></pre> <p>But this one doesn't work.</p>
1
Compressing image in android is loosing the quality when image is taken from phone camera
<p>I am using this method for compressing the image <a href="https://gist.github.com/ManzzBaria/c3af85b708fee49d55f7" rel="nofollow">https://gist.github.com/ManzzBaria/c3af85b708fee49d55f7</a></p> <p>but my images are loosing quality after compression. it is worse when an image is take from phone and compressed.</p> <p>Please let me know where I am doing wrong. </p>
1
Scaling and fitting to a log-normal distribution using a logarithmic axis in python
<p>I have a log-normal distributed set of samples. I can visualize the samples using a histrogram with either linear or logarithmic x-axis. I can perform a fit to the histogram to get the PDF and then scale it to the histrogram in the plot with the linear x-axis, see also <a href="https://stackoverflow.com/questions/34893615/scaling-the-fitted-pdf-of-a-log-normal-distribution-to-the-histrogram-in-python/">this previously posted question</a>.</p> <p>I am, however, not able to properly plot the PDF into the plot with the logarithmic x-axis. </p> <p>Unfortunately, it is not only a problem with the scaling of the area of the PDF to the histogram but the PDF is also shifted to the left, as you can see from the following plot.</p> <p><a href="https://i.stack.imgur.com/gizkR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gizkR.png" alt="Histogram and fitted and scaled PDF with a linear x-axis (left) and a logarithmic x-axis (right)"></a></p> <p>My question now is, what am I doing wrong here? Using the CDF to plot the expected histogram, <a href="https://stackoverflow.com/a/34896229/838992">as suggested in this answer</a>, works. I would just like to know what I am doing wrong in this code as in my understanding it should work too.</p> <p>This is the python code (I am sorry that it is rather long but I wanted to post a "full stand-alone version"):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import scipy.stats # generate log-normal distributed set of samples np.random.seed(42) samples = np.random.lognormal( mean=1, sigma=.4, size=10000 ) # make a fit to the samples shape, loc, scale = scipy.stats.lognorm.fit( samples, floc=0 ) x_fit = np.linspace( samples.min(), samples.max(), 100 ) samples_fit = scipy.stats.lognorm.pdf( x_fit, shape, loc=loc, scale=scale ) # plot a histrogram with linear x-axis plt.subplot( 1, 2, 1 ) N_bins = 50 counts, bin_edges, ignored = plt.hist( samples, N_bins, histtype='stepfilled', label='histogram' ) # calculate area of histogram (area under PDF should be 1) area_hist = .0 for ii in range( counts.size): area_hist += (bin_edges[ii+1]-bin_edges[ii]) * counts[ii] # oplot fit into histogram plt.plot( x_fit, samples_fit*area_hist, label='fitted and area-scaled PDF', linewidth=2) plt.legend() # make a histrogram with a log10 x-axis plt.subplot( 1, 2, 2 ) # equally sized bins (in log10-scale) bins_log10 = np.logspace( np.log10( samples.min() ), np.log10( samples.max() ), N_bins ) counts, bin_edges, ignored = plt.hist( samples, bins_log10, histtype='stepfilled', label='histogram' ) # calculate area of histogram area_hist_log = .0 for ii in range( counts.size): area_hist_log += (bin_edges[ii+1]-bin_edges[ii]) * counts[ii] # get pdf-values for log10 - spaced intervals x_fit_log = np.logspace( np.log10( samples.min()), np.log10( samples.max()), 100 ) samples_fit_log = scipy.stats.lognorm.pdf( x_fit_log, shape, loc=loc, scale=scale ) # oplot fit into histogram plt.plot( x_fit_log, samples_fit_log*area_hist_log, label='fitted and area-scaled PDF', linewidth=2 ) plt.xscale( 'log' ) plt.xlim( bin_edges.min(), bin_edges.max() ) plt.legend() plt.show() </code></pre> <p><strong>Update 1</strong>: </p> <p>I forgot to mention the versions I am using:</p> <pre><code>python 2.7.6 numpy 1.8.2 matplotlib 1.3.1 scipy 0.13.3 </code></pre> <p><strong>Update 2</strong>:</p> <p>As pointed out by @Christoph and @zaxliu (thanks to both), the problem lies in the scaling of the PDF. It works when I am using the same bins as for the histogram, as in @zaxliu's solution, but I still have some problems when using a higher resolution for the PDF (as in my example above). This is shown in the following figure:</p> <p><a href="https://i.stack.imgur.com/aD2gV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aD2gV.png" alt="Histogram and fitted and scaled PDF with a linear x-axis (left) and a logarithmic x-axis (right)"></a></p> <p>The code for the figure on the right hand side is (I left out the import and data-sample generation stuff, which you can find both in the above example):</p> <pre><code># equally sized bins in log10-scale bins_log10 = np.logspace( np.log10( samples.min() ), np.log10( samples.max() ), N_bins ) counts, bin_edges, ignored = plt.hist( samples, bins_log10, histtype='stepfilled', label='histogram' ) # calculate length of each bin (required for scaling PDF to histogram) bins_log_len = np.zeros( bins_log10.size ) for ii in range( counts.size): bins_log_len[ii] = bin_edges[ii+1]-bin_edges[ii] # get pdf-values for same intervals as histogram samples_fit_log = scipy.stats.lognorm.pdf( bins_log10, shape, loc=loc, scale=scale ) # oplot fitted and scaled PDF into histogram plt.plot( bins_log10, np.multiply(samples_fit_log,bins_log_len)*sum(counts), label='PDF using histogram bins', linewidth=2 ) # make another pdf with a finer resolution x_fit_log = np.logspace( np.log10( samples.min()), np.log10( samples.max()), 100 ) samples_fit_log = scipy.stats.lognorm.pdf( x_fit_log, shape, loc=loc, scale=scale ) # calculate length of each bin (required for scaling PDF to histogram) # in addition, estimate middle point for more accuracy (should in principle also be done for the other PDF) bins_log_len = np.diff( x_fit_log ) samples_log_center = np.zeros( x_fit_log.size-1 ) for ii in range( x_fit_log.size-1 ): samples_log_center[ii] = .5*(samples_fit_log[ii] + samples_fit_log[ii+1] ) # scale PDF to histogram # NOTE: THIS IS NOT WORKING PROPERLY (SEE FIGURE) pdf_scaled2hist = np.multiply(samples_log_center,bins_log_len)*sum(counts) # oplot fit into histogram plt.plot( .5*(x_fit_log[:-1]+x_fit_log[1:]), pdf_scaled2hist, label='PDF using own bins', linewidth=2 ) plt.xscale( 'log' ) plt.xlim( bin_edges.min(), bin_edges.max() ) plt.legend(loc=3) </code></pre>
1
Pure CSS scrolling tbody and static thead table w/ dynamic height & width
<p>I was tasked with creating a table that would be used as the major portion of a layout. The header of the table should be static while body should scroll if necessary. The issue is that if the scrollbar is needed, the columns of the table becomes misaligned because the width of the tbody changes. </p> <p>I used a bit of javascript to compensate by setting the right padding on the thead to be equal to the width of the scrollbar, and planned to use a listener to remove / add back the padding as the scrollbar disappeared / appeared.</p> <p>While this approach worked to keep the columns aligned, I was asked to come up with an HTML/CSS only solution if possible. Does anyone know of a way to achieve this without any js? Thanks.</p> <p>Some relevant CSS I currently have:</p> <pre><code>table { width: 100%; border-collapse: collapse; } table tbody { position: absolute; top: 24px; left: 0; right: 0; bottom: 0; overflow-y: auto; } table thead { position: absolute; top: 0; left: 0; right: 0; } </code></pre> <p>Here is a fiddle to see the whole example: <a href="http://jsfiddle.net/kirky93/qqv73kjo/5/" rel="nofollow">http://jsfiddle.net/kirky93/qqv73kjo/5/</a> <br> Drag the viewport up/down to make the scrollbar dis/appear to see the issue.</p>
1
Cloudinary - Upload preset must be in whitelist for unsigned uploads
<p>I want to upload image, to Cloudinary, taken directly from camera in Ionic using cordova camera plugin. I am getting an error of code 1, having message "upload preset must be in whitelist for unsigned uploads." How to solve this error.Please help.</p> <p>my edited js code is:</p> <pre><code> $scope.cameraopen = function(){ var options = { quality : 100, destinationType : Camera.DestinationType.FILE_URI,//FILE_URI sourceType : Camera.PictureSourceType.CAMERA, allowEdit : false, encodingType: Camera.EncodingType.JPEG, popoverOptions: CameraPopoverOptions, targetWidth: 500, targetHeight: 500, saveToPhotoAlbum: true }; $cordovaCamera.getPicture(options).then(function(imageData) { var Uploadoptions = { upload_preset: cloudinary.config().upload_preset, tags: 'mytag', context: 'photo=photo', file: imageData }; var onUploadSuccess = function(data){ console.log("success"+JSON.stringify(data)); } var onUploadFail = function(e){ console.log("error"+JSON.stringify(e)); } var ft = new FileTransfer(); ft.upload(imageData, "http://api.cloudinary.com/v1_1/" + cloudinary.config().cloud_name + "/upload", onUploadSuccess, onUploadFail, Uploadoptions, true); }, function(err) { // error }); } </code></pre>
1
NullPointerException in array.length Java
<p>I've been getting an NPE whenever I try to access my array. Even calling for the .length attribute gives me an NPE. Any help would be appreciated. Here is my constructor and the method that keeps failing.</p> <pre><code>public SkierList() { Skier[] skiers= new Skier[INITIAL_CAP]; for (int i = 0; i &lt; skiers.length; i++){ skiers[i] = new Skier(&quot;&quot;); } int count = 0; } public void add(Skier newSkier) { if (this.size() &lt; skiers.length) { skiers[count] = new Skier(newSkier.getName(), newSkier.getLevel()); count++; } } </code></pre> <p>The code compiles but throws the NPE at skiers.length</p>
1
Passing ng-model from view to controller angular js
<p>I am trying to pass value like this from view to controller in angular js of this form. I do not wish to hardcode it in this way. How could it be done in proper manner?</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('user').controller('UsersController', ['$scope', '$stateParams', 'Users', function($scope, $stateParams, Orders) { $scope.create = function() { var user = new Users({ child: [ { columnA: child[0].columnA, columnB: child[0].columnB, columnC: child[0].columnC }, { columnB: child[1].columnA, columnB: child[1].columnB, columnC: child[1].columnC }, ... { columnC: child[10].columnA, columnB: child[10].columnB, columnC: child[10].columnC } ] }); } } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form data-ng-submit="create()"&gt; &lt;input type="text" data-ng-model="child[0].columnA"&gt; &lt;input type="text" data-ng-model="child[0].columnB"&gt; &lt;input type="text" data-ng-model="child[0].columnC"&gt; &lt;input type="text" data-ng-model="child[1].columnA"&gt; &lt;input type="text" data-ng-model="child[1].columnB"&gt; &lt;input type="text" data-ng-model="child[1].columnC"&gt; ...... &lt;input type="text" data-ng-model="child[10].columnA"&gt; &lt;input type="text" data-ng-model="child[10].columnB"&gt; &lt;input type="text" data-ng-model="child[10].columnC"&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>It would be better if an reusable directive that may perform above function.</p> <pre><code>$scope.create = function() { child: toJSON(child); } function toJSON(var a) { //automatically search through the view for ng-model with child[index].columnName and change to the form above. } </code></pre>
1
div tag with style='display: none;' not working
<p>So, I am trying to have a full div hidden until user clicks a button. I tried setting <code>display:none</code>; but it is not working. i tried setting <code>display:none !important;</code> but that didn't work either. I tried using </p> <pre><code>$(document).ready(function(){ jQuery('#div').hide(); }); </code></pre> <p>but it is not working.. Below is my code. Any help would be appreciated.</p> <pre><code>&lt;div name="Head"&gt; &lt;div id="first_box" align=right&gt; &lt;input type="button" id="get_preview" onClick="bringPreview()" value="Generate Preview"/&gt; &lt;input type="button" id="get_code" onClick="bringCode()" value="Generate Code"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;script&gt; function bringPreview() { jQuery('#batchemail').toggle(); } function bringCode() { jQuery('#batchemail').hide(); jQuery('#batchemailcode').toggle(); } &lt;/script&gt; &lt;div id="batchemailcode" style="display: none;"&gt; &lt;xmp&gt; &lt;p&gt;Hello&lt;/p&gt; &lt;/xmp&gt; &lt;/div&gt; &lt;div id="batchemail" style="display:none;"&gt; &lt;body style="background:#f6f6f6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;"&gt; &lt;div style="background:#f6f6f6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;"&gt; &lt;table cellspacing="0" cellpadding="0" border="0" width="100%"&gt; &lt;tr&gt; &lt;td align="center" valign="top" style="padding:20px 0 20px 0"&gt; &lt;table bgcolor="#ffffff" cellspacing="0" cellpadding="20" border="0" width="650" style="border:1px solid #E0E0E0;"&gt; &lt;!-- [ header starts here] --&gt; &lt;tr&gt; &lt;td style="width:200px; height:70px; float:left;"&gt; &lt;a href="{{store url=""}}"&gt;&lt;img src="{{ logo }}" alt="{{var logo_alt}}" style="margin-bottom:10px; width:299px; height:62px" border="0"/&gt; &lt;/a&gt;&lt;/div&gt; &lt;div style="width:240px; float:right; font-size: 12px;text-align:right; color: #222222;"&gt;Subheader subject line&lt;br/&gt; &lt;a href="{{ url }}" style="color: #222222; margin-top: 10px;"&gt;&lt;span style="font-size: 12px;"&gt;View The Online Version&lt;/span&gt;&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;!-- [ middle starts here] --&gt; &lt;tr&gt; &lt;td valign="top"&gt; &lt;div style="text-align: center; font-size: 14px; text-decoration: none; color: #222222; padding: 10px 0 10px 0; margin-bottom: 5px; background-color: #cccccc;"&gt; &lt;a href="{{ url }}" style="color: #222222; text-decoration: none; padding: 0 5px 0 5px;"&gt;Appliances&lt;/a&gt; | &lt;a href="{{ url }}" style="color: #222222; text-decoration: none; padding: 0 5px 0 5px;"&gt;Furniture&lt;/a&gt; | &lt;a href="{{ url }}" style="color: #222222; text-decoration: none; padding: 0 5px 0 5px;"&gt;Bed &amp;amp; Bath&lt;/a&gt; | &lt;a href="{{ url }}" style="color: #222222; text-decoration: none; padding: 0 5px 0 5px;"&gt;Lighting&lt;/a&gt; | &lt;a href="{{ url }}" style="color: #222222; text-decoration: none; padding: 0 5px 0 5px;"&gt;Rebates&lt;/a&gt; | &lt;a href="{{ url }}" style="color: #222222; text-decoration: none; padding: 0 5px 0 5px;"&gt;Scratch &amp;amp; Dent&lt;/a&gt; &lt;/div&gt; &lt;hr style="border:1px; color:#cccccc; border-style:dotted;" /&gt; &lt;!--&lt;div class="email-large-banner" style="width: 640px; border: 1px solid #e0e0e0; margin-top: 5px; margin-bottom: 10px;"&gt;--&gt; &lt;!-- &lt;a href="&lt;?php echo $link ?&gt;"&gt;&lt;img src="&lt;?php echo $image?&gt;" alt="&lt;?php echo $brand?&gt;" /&gt;&lt;/a&gt; --&gt; &lt;!--&lt;/div&gt;--&gt; &lt;?php elseif($counter == 2): foreach ($imagesByRow as $row =&gt; $images): $count = 1; foreach($images as $image): $link = $model-&gt;getAllLinks($rowPositions[$row], $count); $sku = $model-&gt;getAllSkus($rowPositions[$row], $count); //Mage::log($link); ?&gt; &lt;div class="email-two-column" style="width: 295px;"&gt; &lt;a href="&lt;?php echo $link ?&gt;"&gt;&lt;img src="&lt;?php echo $image?&gt;" alt="&lt;?php echo $brand ?&gt;" /&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php endforeach ?&gt; &lt;?php endforeach?&gt; &lt;?php endif ?&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/div&gt; </code></pre>
1
Creating lists from another list's item in Linq
<p>I have a list of a custom car object <code>List&lt;Car&gt;</code>. The car class has two properties 'BrandName' and 'Models' as defined below. </p> <pre><code>public class Car { public string BrandName {get; set;} public List&lt;string&gt; Models {get; set;} } </code></pre> <p>The data for the 'List` object is populated from an API as below. It returns close to 200 rows. For illustration purposes, the object has been instantiated with two items as below. The object is returned from the API with this structure and I have no control over how the data is structured and sent. </p> <pre><code>List&lt;Car&gt; listCarObj = new List&lt;Car&gt;(){ new Car(){ BrandName = "Mercedes", Models = new List&lt;string&gt;(){"Class A", "Class E"}}, new Car(){ BrandName = "BMW", Models = new List&lt;string&gt;(){"X Series", "E Series"}} } </code></pre> <p>How do I convert this list to an IEnumerable or another List of an anonymous type having data in the below format using Linq?</p> <pre><code>var obj = new[] {new {brand = "Mercedes", model = "Class A"}, new {brand = "Mercedes", model = "Class E"}, new {brand = "BMW", model = "X Series"}, new {brand = "BMW", model = "E Series"}}; </code></pre> <p>Thanks in advance..</p>
1
Assassin Program Java
<p>I have to create a program where I have a list of peoples names and have to assign them by random who will be stalking who and who will be killing who.</p> <p>I have my program here but I am having some errors. The list of who killed who will and everything after that will not appear in the output and I am wondering if I could get some help</p> <p>Here is my program so far:</p> <p>AssassinMain.java:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>package Assassin; import java.io.*; import java.util.*; public class AssassinMain { public static final String INPUT_FILENAME = "names.txt"; public static final boolean RANDOM = false; /** * If not random, use this value to guide the sequence of numbers * that will be generated by the Random object. */ public static final int SEED = 42; public static void main(String[] args) throws FileNotFoundException { File inputFile = new File(INPUT_FILENAME); if (!inputFile.canRead()) { System.out.println("Required input file not found; exiting.\n" + inputFile.getAbsolutePath()); System.exit(1); } Scanner input = new Scanner(inputFile); Set&lt;String&gt; names = new TreeSet&lt;String&gt;(String.CASE_INSENSITIVE_ORDER); while (input.hasNextLine()) { String name = input.nextLine().trim().intern(); if (name.length() &gt; 0) { names.add(name); } } ArrayList&lt;String&gt; nameList = new ArrayList&lt;String&gt;(names); Random rand = (RANDOM) ? new Random() : new Random(SEED); Collections.shuffle(nameList, rand); AssassinManager manager = new AssassinManager(nameList); Scanner console = new Scanner(System.in); while (!manager.isGameOver()) { oneKill(console, manager); } // report who won System.out.println("Game was won by " + manager.winner()); System.out.println("Final graveyard is as follows:"); manager.printGraveyard(); } public static void oneKill(Scanner console, AssassinManager manager) { System.out.println("Current kill ring:"); manager.printKillRing(); System.out.println("Current graveyard:"); manager.printGraveyard(); System.out.println(); System.out.print("next victim? "); String name = console.nextLine().trim(); if (manager.graveyardContains(name)) { System.out.println(name + " is already dead."); } else if (!manager.killRingContains(name)) { System.out.println("Unknown person."); } else { manager.kill(name); } System.out.println(); } }</code></pre> </div> </div> </p> <p>AssassinNode.java:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>package Assassin; //CSE 143, Homework 4: Assassin // //Instructor-provided support class. You should not modify this code! /** * Each AssassinNode object represents a single node in a linked list * for a game of Assassin. */ public class AssassinNode { public String name; // this person's name public String killer; // name of who killed this person (null if alive) public AssassinNode next; // next node in the list (null if none) /** * Constructs a new node to store the given name and no next node. */ public AssassinNode(String name) { this(name, null); } /** * Constructs a new node to store the given name and a reference * to the given next node. */ public AssassinNode(String name, AssassinNode next) { this.name = name; this.killer = null; this.next = next; } }</code></pre> </div> </div> </p> <p>AssassinManager.java:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>package Assassin; import java.util.ArrayList; /** * AssassinManager that keeps track of who is stalking whom and the history * of who killed whom by maintaining two linked lists, a list of players who * are currently alive in the "kill ring" and a list of players who are * currently dead in the "graveyard". * */ public class AssassinManager { /** * killRingFront field: reference to the front node of the kill ring */ private AssassinNode killRingFront; /** * graveyardFront field: reference to the front node of the graveyard (null if empty) */ private AssassinNode graveyardFront; /** * Initialize a new assassin manager over the given list of people. * @param names * @throws IllegalArgumentException if the list is null or has a size of 0 */ public AssassinManager(ArrayList&lt;String&gt; names) { // You receive a list of names (as a parameter). // Take the names and build up the kill ring of linked nodes that // contains the names in the same order as you received them in // the ArrayList. You may assume that the names are non-empty, non-null // strings and that there are no duplicates. // Note: you receive a list of names as strings. You need to create a new // AssassinNode object for each player and put their name into the node // and connect the nodes together into a list that killRingFront references. // your code goes here int temp = 0; while( temp &lt; names.size()) { if( killRingFront == null) { killRingFront = new AssassinNode(names.get(temp)); } else { AssassinNode current = killRingFront; while( current.next != null) { current = current.next; } current.next = new AssassinNode( names.get(temp)); } temp++; } } /** * Prints the names of the people in the kill ring, one per line, indented * by two spaces, as "name is stalking name". The behavior is unspecified if * the game is over. */ public void printKillRing() { // your code goes here AssassinNode current = killRingFront; while( current.next != null) { System.out.println(" " + current.name + " is stalking " + current.next.name ); current = current.next; } } /** * Prints the names of the people in the graveyard, one per line, with each * line indented by two spaces, with output of the form "name was killed by * name". It should print the names in the opposite of the order in which * they were killed (most recently killed first, then next more recently * killed, and so on). It should produce no output if the graveyard is empty. */ public void printGraveyard() { // your code goes here AssassinNode current = graveyardFront; if (graveyardFront == null) { return; } for(current = graveyardFront ; current.next != null; current = current.next) { System.out.println(" " + current.name + " was killed by " + current.killer ); } System.out.println(current.name); } /** * Checks to see if &lt;code&gt;name&lt;/code&gt; is in the current kill ring. * @param name name to check * @return true if the &lt;code&gt;name&lt;/code&gt; is in the kill ring and false otherwise */ public boolean killRingContains(String name) { AssassinNode current; for(current = killRingFront ; current.next != null; current = current.next) { if( current.name.equals(name)) { return true; } } return false; } /** * Checks to see if &lt;code&gt;name&lt;/code&gt; is in the current graveyard. * @param name name to check * @return true if the &lt;code&gt;name&lt;/code&gt; is in the graveyard and false otherwise */ public boolean graveyardContains(String name) { AssassinNode current = graveyardFront; if( graveyardFront == null) { return false; } for(current = graveyardFront ; current.next != null ; current = current.next) { if( current.name.equals(name)) { return true; } } return false; } /** * Checks to see if the game is over (if the kill ring has only one player * remaining). * @return true if the game is over and false otherwise */ public boolean isGameOver() { if(killRingFront.next == null) { return true; } else { return false; } } /** * Obtains the name of the winner of the game. * @return name of the winner of the game or &lt;code&gt;null&lt;/code&gt; if the game * is not over */ public String winner() { String winner; AssassinNode current; if( isGameOver()) { for(current = killRingFront ; current.next != null; current = current.next) { winner = current.name; return winner; } } return null; // delete this line and replace it with your code for this method } /** * Transfers a player from the kill ring to the front of the graveyard. This * operation does not change the relative order of the kill ring. Case is * ignored in comparing names. * @param name the name of the player to be transferred from the kill ring * to the graveyard * @throws IllegalStateException if the game is over * @throws IllegalArgumentException if the given name is not part of the kill ring */ public void kill(String name) { // your code goes here AssassinNode current, previous; for( current = killRingFront, previous= null; current != null &amp;&amp; !current.name.equals(name); current = current.next) { previous = current; } if( previous == null) { AssassinNode temp = killRingFront; killRingFront = killRingFront.next; while( previous.next != null) { previous= previous.next; } // previous.next = current.next; // current.killer = previous.name; // current.next = graveyardFront; addtoGraveyard(temp); } else { AssassinNode temp = killRingFront; previous.next = current.next; current.killer = previous.name; current.next = graveyardFront; addtoGraveyard(temp); } } private void addtoGraveyard(AssassinNode dead) { } }</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>Don Knuth Alan Turing Ada Lovelace Charles Babbage John von Neumann Grace Hopper Bill Gates Tim Berners-Lee Alan Kay Linus Torvalds Alonzo Church</code></pre> </div> </div> </p> <p>Now I know this is alot of programming But My problem is I cant get my list of people who were killed to come up in the output, the list is suppose to grow and grow as each person choosen as the next victim is suppose to die. My professor instruct me to create a private void addtograveyard to help. I am not 100% sure what to put here exactly to make it work? Do I right the same thing as from the printgraveyard method? Also when I go over the list I need to have the very last person in the list to stalk the first person on the list and to kill the first person on the list . Can you guys help me on how to make that work in my program and where will I have it typed at.I really do need some help here guys this is all I need to complete my program. Thanks guys!</p>
1
Materialized view refresh terrible performance degradation
<p>I have materialized view (it uses joins, WITH, partition by; query returns about <strong>42 mln</strong> rows) with 2 simple indexes on it. Only full refresh is used.</p> <p>The first refresh works fine (it takes ~100 minutes) but second refresh works several days and failed to complete.</p> <p>Also I dropped indexes and re-run test. It works fine. Here is all results (time and redo entries from session statistics):</p> <p>1) Without indexes, first run time: 72 min redo: <strong>42 mln</strong> (it is close to row number)</p> <p>2) Without indexes, second run time: 106 min redo: <strong>84 mln</strong> (42 mln to delete all and 42 mln to insert new)</p> <p>3) With 2 indexes, first run time: 99 min redo: <strong>126 mln</strong> (42 mln for rows and 42 mln for each index)</p> <p>4) With 2 indexes, second run time: failed after 48 hours redo: <strong>453 mln</strong> when failed (I have no idea why it's so huge)</p> <p>Oracle version: 11g Enterprise Edition Release 11.2.0.3.0</p> <p>The issue was reproduced on different instances&amp;servers. I have no server where it works correctly. I think that it is some kind of bug but can't find anything similar</p>
1
shadows not appearing in the scene in three.js?
<p>camera : </p> <pre><code> Camera = new THREE.PerspectiveCamera(45, Width / Height, 0.1, 10000); Camera.position.set( 150, 400, 400); Scene.add(Camera); </code></pre> <p>Light </p> <pre><code> Light = new THREE.SpotLight(0xffccff,.5, 0, Math.PI/2, 1); Light.position.set(0, 2000, 0); Light.castShadow = true; Light.shadowBias = -0.0002; Light.shadowCameraNear = 850; Light.shadowCameraFar = 8000; Light.shadowCameraFov = 600; Light.shadowDarkness = .7; Light.shadowMapWidth = 2048; Light.shadowMapHeight = 2048; Scene.add(Light); </code></pre> <p>Renderer</p> <pre><code> Renderer = new THREE.WebGLRenderer({ antialias: true, sortObjects: false, preserveDrawingBuffer: true, shadowMapEnabled: true }); document.body.appendChild(Renderer.domElement); Renderer.shadowMap.type = THREE.PCFSoftShadowMap; Renderer.shadowMap.cullFace = THREE.CullFaceBack; Renderer.gammaInput = true; Renderer.gammaOutput = true; Renderer.setSize(window.innerWidth, window.innerHeight); </code></pre> <p>i use this function to add 3d model</p> <pre><code> function getModel(path,texture) { var Material = new THREE.MeshPhongMaterial({shading: THREE.SmoothShading, specular: 0xff9900, shininess: 0, side: THREE.DoubleSide, shading: THREE.SmoothShading }); Loader = new THREE.JSONLoader(); Loader.load(path,function(geometry){ geometry.mergeVertices(); geometry.computeFaceNormals(); geometry.computeVertexNormals(); TextureLoader.load(texture,function(texture){ Mesh = new THREE.Mesh(geometry, Material); Mesh.material.map =texture; Mesh.material.map.wrapS = THREE.RepeatWrapping; Mesh.material.map.wrapT = THREE.RepeatWrapping; Mesh.material.map.repeat.set(38,38); //Mesh.position.y -= 1; Mesh.position.y = 160; Mesh.position.x = 0; Mesh.position.z = 0; Mesh.scale.set(40,40,40); Mesh.castShadow = true; Mesh.receiveShadow = true; Scene.add(Mesh); }); }); } </code></pre> <p>and the plane to recive shadow is </p> <pre><code>var planeGeometry = new THREE.PlaneBufferGeometry(100,100); var planematerial = new THREE.MeshLambertMaterial( { shininess: 80, color: 0xffaaff, specular: 0xffffff }); var plane = new THREE.Mesh(planeGeometry,planematerial); plane.rotation.x = - Math.PI / 2; plane.position.set(0,100,0); plane.scale.set( 10, 10, 10 ); plane.receiveShadow = true; plane.castShadow = true; Scene.add(plane); </code></pre> <p>I just tried adjusting the position of the lights and adjusted the values of shadowCameraNear,Light.shadowCameraFar and Light.shadowCameraFov .but not no changes are seen</p>
1
Should data go in a redux state tree?
<p>I am a bit lost on what to keep in the state tree of Redux.</p> <p>I saw two conflicting statements on what to store in the state tree(s).</p> <ul> <li><a href="https://facebook.github.io/react/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state">React doc</a> tell us that only <strong>user input</strong> should be stored in state trees.</li> </ul> <blockquote> <p>The <strong>original list</strong> of products is passed in as props, so <strong>that's not state</strong>. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the <strong>filtered list of products isn't state</strong> because it can be computed by combining the original list of products with the search text and value of the checkbox. </p> </blockquote> <ul> <li><a href="http://rackt.org/redux/docs/basics/Reducers.html">Redux doc</a> tells us that we often should store UI state <strong>and data</strong> in the single state tree:</li> </ul> <blockquote> <p>For our todo app, we want to store two different things:</p> <ul> <li>The currently selected visibility filter;</li> <li><strong>The actual list of todos.</strong></li> </ul> <p>You’ll often find that you need to store some data, as well as some UI state**, in the state tree. This is fine, but try to keep the data separate from the UI state.</p> </blockquote> <p>So React tells that we should not store data (I am talking about data of the todos) and, for me, Redux tells the opposite.</p> <p>In my understand I would tend on the React side because both React and Redux aims to predict a UI state by storing:</p> <ol> <li><p>all what can't be computed (eg: all human inputs) and are part of the UI:</p> <ul> <li>checkbox value</li> <li>input value</li> <li>radio value</li> <li>...</li> </ul></li> <li><p>All <strong>minimal</strong> data that could be use to build a query and send it to the API/database that will return the complete user profil, friends lists, whatever...:</p> <ul> <li>user Id</li> <li>creation dates range</li> <li>items Ids</li> <li>...</li> </ul></li> </ol> <p>For me <strong>that excludes all database/API results</strong> because:</p> <ul> <li>that stands on data level</li> <li>could be computed by sending the right (and computed by pure reducers) query.</li> </ul> <p>So what is your opinion here?</p>
1
Error in file(file, "rt") : invalid 'description' argument
<p>In the code below, I am trying to cycle through csv files and calculate the correlation between two columns for each file. The results are being stored in an empty vector.</p> <p>For example: the first file has name "001.csv". The for loop will calculate the correlation between the 2nd and 3rd column and store it in the 1st position of the results vector. This will continue to iterate until to the end of the loop.</p> <p>For some reason the following error keep occuring:<br> <code>Error in file(file, "rt") : invalid 'description' argument</code></p> <p>The code I am trying to execute is:</p> <pre><code>corr &lt;- function(directory, threshold = 0) { ## defining the directory path = paste("C:/Users/name/Desktop/R/R Working Directory/",directory,"/", sep="", collapse="") directory1 &lt;- dir(path, pattern=".csv") data.set &lt;- complete(directory,) ##calling in the dataset to find correlation on data.setDIM &lt;- dim(data.set) ##using the dim to filter data in for loop filter.data &lt;- data.frame(matrix(,,2)) result &lt;- vector() for(i in i:data.setDIM[1]) { if( data.set[i,2] &gt;= threshold) { filter.data[i,1]&lt;-data.set[i,1] filter.data[i,2]&lt;-data.set[i,2] } } filter.data &lt;- na.omit(filter.data) ##removing the NA values ## Performing corr() function. I will use the 1st column of filter.data to identify the files to read and perform calc on. for(j in c(filter.data[1])) { file &lt;- na.omit(read.csv(paste(path,directory1[j],sep="",colapse=""))) result[j] &lt;- cor(file[2],file[3]) } result } </code></pre> <p>The <code>c(filter.data[1])</code> gives me a vector of integers that I want to index through. I've printed out an example below.</p> <pre><code>[1] 21 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 [19] 41 44 45 47 49 50 51 52 53 54 55 56 57 58 59 60 61 62 [37] 63 64 66 67 68 71 72 74 75 76 77 78 80 83 84 86 87 88 [55] 89 91 93 94 96 97 98 99 103 104 105 108 109 110 111 112 113 114 [73] 115 116 117 119 120 121 122 123 124 125 127 128 131 132 133 136 138 139 [91] 140 141 142 143 144 145 147 148 149 150 151 152 153 154 156 158 160 164 [109] 165 166 167 168 170 171 172 173 174 176 177 178 179 180 181 182 183 184 [127] 185 186 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 [145] 205 209 210 213 214 215 216 217 218 219 220 221 222 223 225 227 228 229 [163] 230 231 232 234 239 240 241 242 243 244 245 246 247 248 249 250 252 253 [181] 254 255 257 258 260 262 263 265 266 267 268 269 270 271 272 273 277 279 [199] 287 299 300 301 302 303 305 306 307 309 310 312 313 314 315 318 320 321 [217] 322 325 326 327 328 329 330 331 </code></pre>
1
google analytics api with python
<p><a href="http://www.marinamele.com/use-google-analytics-api-with-python" rel="nofollow">http://www.marinamele.com/use-google-analytics-api-with-python</a></p> <p>Hi, I followed this tutorial to try access the google analytics api with python.</p> <p>the code is like this:</p> <pre><code>import httplib2 from apiclient.discovery import build from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client import tools import argparse CLIENT_SECRETS = 'client_secrets.json' # The Flow object to be used if we need to authenticate. FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/analytics.readonly', message='%s is missing' % CLIENT_SECRETS ) # A file to store the access token TOKEN_FILE_NAME = 'credentials.dat' def prepare_credentials(): parser = argparse.ArgumentParser(parents=[tools.argparser]) flags = parser.parse_args() # Retrieve existing credendials storage = Storage(TOKEN_FILE_NAME) credentials = storage.get() # If no credentials exist, we create new ones if credentials is None or credentials.invalid: credentials = tools.run_flow(FLOW, storage, flags) return credentials def initialize_service(): # Creates an http object and authorize it using # the function prepare_creadentials() http = httplib2.Http() credentials = prepare_credentials() http = credentials.authorize(http) # Build the Analytics Service Object with the authorized http object return build('analytics', 'v3', http=http) if __name__ == '__main__': service = initialize_service() </code></pre> <p>After I run the python code, it gave me a new browser window and ask me the permission to access google analytics data, after I click allow, it shows: no data received. </p> <p>What wrong did I do?</p> <p>Thanks </p>
1
AttributeError: 'function' object has no attribute 'lower'
<p>I am trying to use sentiwordnet text file "SentiWordNet_3.0.0_20130122.txt". When I am importing the sentiwordnet.py file and attempting to run it I am getting the error as follows:</p> <p>The error occured as:</p> <pre><code>-------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-13-6e4eb476b4b2&gt; in &lt;module&gt;() ----&gt; 1 happy = cv.senti_synsets('happy', 'a') C:\Users\Desktop\fp\sentiwordnet.pyc in senti_synsets(self, string, pos) 65 synset_list = wn.synsets(string, pos) 66 for synset in synset_list: ---&gt; 67 sentis.append(self.senti_synset(synset.name)) 68 sentis = filter(lambda x : x, sentis) 69 return sentis C:\Users\Desktop\fp\sentiwordnet.pyc in senti_synset(self, *vals) 52 return SentiSynset(pos_score, neg_score, synset) 53 else: ---&gt; 54 synset = wn.synset(vals[0]) 55 pos = synset.pos 56 offset = synset.offset C:\Users\Anaconda2\lib\site-packages\nltk\corpus\reader\wordnet.pyc in synset(self, name) 1227 def synset(self, name): 1228 # split name into lemma, part of speech and synset number ---&gt; 1229 lemma, pos, synset_index_str = name.lower().rsplit('.', 2) 1230 synset_index = int(synset_index_str) - 1 1231 AttributeError: 'function' object has no attribute 'lower' </code></pre> <p>My code:</p> <pre><code>import sentiwordnet as snw SWN_FILENAME = "SentiWordNet_3.0.0_20130122.txt" cv = snw.SentiWordNetCorpusReader(SWN_FILENAME) happy = cv.senti_synsets('happy', 'a') print happy </code></pre>
1
Issue with "rake" and won't connect to database
<p>I have a rails app i've been working on for a while and it was always working and testing fine. Then for some reason today when I tried rake db:migrate I get the message below. I have started using git recently. Whether that has anything to do with it I don't know.</p> <p>Gem::LoadError: You have already activated rake 10.5.0, but your Gemfile requires rake 10.4.2. Prepending <code>bundle exec</code> to your command may solve this.</p> <p>If i type bundle exec rake db:migrate it seems to complete the migration the issue now is that in the new view when the user hits the submit button the create action isn't called. So the data isn't entered into the database.</p> <p>Any ideas would be great. Thanks.</p>
1
How to persist data using a postgres database, Docker, and Kubernetes?
<p>I am trying to mount a persistent disk on my container which runs a Postgres custom image. I am using Kubernetes and following <a href="https://cloud.google.com/container-engine/docs/tutorials/persistent-disk/" rel="nofollow noreferrer">this</a> tutorial.</p> <p>This is my <code>db_pod.yaml</code> file:</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: lp-db labels: name: lp-db spec: containers: - image: my_username/my-db name: my-db ports: - containerPort: 5432 name: my-db volumeMounts: - name: pg-data mountPath: /var/lib/postgresql/data volumes: - name: pg-data gcePersistentDisk: pdName: my-db-disk fsType: ext4 </code></pre> <p>I create the disk using the command <code>gcloud compute disks create --size 200GB my-db-disk</code>.</p> <p>However, when I run the pod, delete it, and then run it again (like in the tutorial) my data is not persisted.</p> <p>I tried multiple versions of this file, including with PersistentVolumes and PersistentVolumeClaims, I tried changing the mountPath, but to no success.</p> <h2>Edit</h2> <p>Dockerfile for creating the Postgres image:</p> <pre><code>FROM ubuntu:trusty RUN rm /bin/sh &amp;&amp; \ ln -s /bin/bash /bin/sh # Get Postgres RUN echo &quot;deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main&quot; &gt;&gt; /etc/apt/sources.list.d/pgdg.list RUN apt-get update &amp;&amp; \ apt-get install -y wget RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - # Install virtualenv (will be needed later) RUN apt-get update &amp;&amp; \ apt-get install -y \ libjpeg-dev \ libpq-dev \ postgresql-9.4 \ python-dev \ python-pip \ python-virtualenv \ strace \ supervisor # Grab gosu for easy step-down from root RUN gpg --keyserver pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends ca-certificates wget &amp;&amp; rm -rf /var/lib/apt/lists/* \ &amp;&amp; wget -O /usr/local/bin/gosu &quot;https://github.com/tianon/gosu/releases/download/1.2/gosu-$(dpkg --print-architecture)&quot; \ &amp;&amp; wget -O /usr/local/bin/gosu.asc &quot;https://github.com/tianon/gosu/releases/download/1.2/gosu-$(dpkg --print-architecture).asc&quot; \ &amp;&amp; gpg --verify /usr/local/bin/gosu.asc \ &amp;&amp; rm /usr/local/bin/gosu.asc \ &amp;&amp; chmod +x /usr/local/bin/gosu \ &amp;&amp; apt-get purge -y --auto-remove ca-certificates wget # make the &quot;en_US.UTF-8&quot; locale so postgres will be utf-8 enabled by default RUN apt-get update &amp;&amp; apt-get install -y locales &amp;&amp; rm -rf /var/lib/apt/lists/* \ &amp;&amp; localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 ENV LANG en_US.utf8 # Adjust PostgreSQL configuration so that remote connections to the database are possible. RUN echo &quot;host all all 0.0.0.0/0 md5&quot; &gt;&gt; /etc/postgresql/9.4/main/pg_hba.conf # And add ``listen_addresses`` to ``/etc/postgresql/9.4/main/postgresql.conf`` RUN echo &quot;listen_addresses='*'&quot; &gt;&gt; /etc/postgresql/9.4/main/postgresql.conf RUN echo &quot;log_directory='/var/log/postgresql'&quot; &gt;&gt; /etc/postgresql/9.4/main/postgresql.conf # Add all code from the project and all config files WORKDIR /home/projects/my-project COPY . . # Add VOLUMEs to allow backup of config, logs and databases ENV PGDATA /var/lib/postgresql/data VOLUME /var/lib/postgresql/data # Expose an entrypoint and a port RUN chmod +x scripts/sh/* EXPOSE 5432 ENTRYPOINT [&quot;scripts/sh/entrypoint-postgres.sh&quot;] </code></pre> <p>And entrypoint script:</p> <pre><code>echo &quot; I am &quot; &amp;&amp; gosu postgres whoami gosu postgres /etc/init.d/postgresql start &amp;&amp; echo 'Started postgres' gosu postgres psql --command &quot;CREATE USER myuser WITH SUPERUSER PASSWORD 'mypassword';&quot; &amp;&amp; echo 'Created user' gosu postgres createdb -O myuser mydb &amp;&amp; echo 'Created db' # This just keeps the container alive. tail -F /var/log/postgresql/postgresql-9.4-main.log </code></pre>
1
Nested For loop in R
<p>This is just a simple question but really taking my time as I am new in R.</p> <p>I'm trying to write a code for the variance of a portfolio. </p> <p><a href="https://i.stack.imgur.com/Uvat6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uvat6.png" alt="enter image description here"></a></p> <p>For example, I have the following :-</p> <pre><code>weight=c(0.3,0.2,0.5) cov = matrix( c(0.2, 0.4, 0.3, 0.4, 0.5, 0.3,0.3,0.3,0.4),nrow=3, ncol=3, byrow = TRUE) for (i in 1:3){ for (j in 1:3) { port = sum((weight[i]^2) * (cov[i,i]^2)) + sum(weight[i] *weight[j]* cov[i,j]) }} </code></pre> <p>The answer if I calculate manually should be <code>0.336</code>. But R gave me <code>port=0.12</code> which is wrong. Where is my mistake?</p>
1
Jquery get length of json array
<p>I've an issue with a json array row length...</p> <p>I want to extract the correct length of data-row json (in this case "2")... If I try to count the length I get the value "1". Why ? How can I get the correct length ?</p> <pre><code>{ "data-row": { "data1": [{ "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" }], "data2": [{ "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }] } } </code></pre>
1
VB.NET: CheckBoxList - programmatically setting Items as Checked
<p>I pass in comma separated values to this function, and check items in a checkboxlist according to the values. But there are no items checked after the function call.</p> <p>For example, I pass in a string "1,5,8", hoping the 3 items with value of 1,5,8 in the checkboxlist will get "checked = true" status. But they don't.</p> <pre><code>Private Sub GetListValuesFromCommaSeparatedValueString(ByRef lst As CheckBoxList, s As String) If IsNothing(s) Or s = "" Then Exit Sub End If Dim array = s.Split(",") For Each value As String In array lst.Items.FindByValue(value).Selected = True Next End Sub </code></pre>
1
When and Why ViewHolder should use in baseadapter
<p>When <code>ViewHolder</code> should use? I found this with most code for <code>ListView</code> and <code>GridView</code>. If anyone can explain. Thanks.</p>
1
C++ segfault when accessing std::vector.size() of an objects pointer's vector
<p>I've a segfault when executing my code: according to GDB the segfault is thrown by </p> <pre><code>Program received signal SIGSEGV, Segmentation fault. 0x00000000004090a6 in std::vector&lt;GeometricObject*, std::allocator&lt;GeometricObject*&gt; &gt;::size (this=0x30) at /usr/include/c++/4.9/bits/stl_vector.h:655 655 { return size_type(this-&gt;_M_impl._M_finish - this-&gt;_M_impl._M_start); } </code></pre> <p>and that's the output of GDB where command</p> <pre><code>#0 0x000000000040923c in std::vector&lt;GeometricObject*, std::allocator&lt;GeometricObject*&gt; &gt;::size ( this=0x30) at /usr/include/c++/4.9/bits/stl_vector.h:655 #1 0x000000000040843c in World::hitObjects (this=0x0, r=...) at /mnt/7DEB96B84D6B013D/Universita/Programmazione ad oggetti e grafica/esercizi/Progetto - RTFGU/core/world/world.cpp:85 #2 0x000000000040a0d8 in MultipleObjects::traceRay (this=0x67ea70, r=...) at /mnt/7DEB96B84D6B013D/Universita/Programmazione ad oggetti e grafica/esercizi/Progetto - RTFGU/core/tracers/multipleObjects.cpp:13 #3 0x00000000004086f0 in World::renderScene (this=0x7fffffffdd60) at /mnt/7DEB96B84D6B013D/Universita/Programmazione ad oggetti e grafica/esercizi/Progetto - RTFGU/core/world/world.cpp:115 #4 0x0000000000407c05 in main (argc=1, argv=0x7fffffffdea8) at /mnt/7DEB96B84D6B013D/Universita/Programmazione ad oggetti e grafica/esercizi/Progetto - RTFGU/main.cpp:20 </code></pre> <p>Here is the main class</p> <pre><code>int main(int argc, char const *argv[]){ World w; w.build(); w.renderScene(); w.displayImage(); return 0; } </code></pre> <p>Here the World class with definitions</p> <pre><code>class World{ public: World(); ~World(); void addObject(GeometricObject *); void build(); ShadeRec hitObjects(const Ray &amp;); void renderScene() const; void displayImage() const; void displayPixel(const int, const int, const RGBColor &amp;) const; RGBColor backgroundColor; ViewPlane vp; Tracer * tracer_ptr; cv::Mat * rendering; std::vector&lt;GeometricObject*&gt; objects; }; // definitions World::World(): backgroundColor(), vp(), tracer_ptr(0), rendering(0), objects(){} World::~World(){} void World::addObject(GeometricObject * o){ objects.push_back(o); } void World::build(){ std::cout &lt;&lt; "Build begins" &lt;&lt; std::endl; int width = 1024, height = 768; vp.setHres(width); vp.setVres(height); vp.setPixelSize(1.f); vp.setGamma(1.f); rendering = new cv::Mat(height,width, CV_8UC3, cv::Scalar(0,0,0)); tracer_ptr = new MultipleObjects(this); backgroundColor = BLACK; Sphere * s1 = new Sphere(Point(0., -25., 0.), 80., CYAN); Sphere * s2 = new Sphere(Point(0.,30.,0.), 60., MAGENTA); Plane * p = new Plane(Point(0.), Normal(0., 1., 1.), YELLOW); std::cout &lt;&lt; objects.size() &lt;&lt; std::endl; // used for debug: size is 0 addObject(s1); addObject(s2); addObject(p); std::cout &lt;&lt; objects.size() &lt;&lt; std::endl; // used for debug: size is 3 for(uint i = 0; i &lt; objects.size(); i++) // in this scope objects.size() works std::cout &lt;&lt; objects[i]-&gt;toString() &lt;&lt; std::endl; // at this stage gdb give me these information: (gdb) p this $1 = (World * const) 0x7fffffffdd60 (gdb) p *this $2 = {backgroundColor = {r = 0, g = 0, b = 0}, vp = {hRes = 1024, vRes = 768, s = 1, gamma = 1, gammaInv = 1}, tracer_ptr = 0x67ea70, rendering = 0x67d870, objects = std::vector of length 3, capacity 4 = {0x67ea90, 0x67ead0, 0x67eb10}} (gdb) p &amp;objects $4 = (std::vector&lt;GeometricObject*, std::allocator&lt;GeometricObject*&gt; &gt; *) 0x7fffffffdd90 } ShadeRec World::hitObjects(const Ray &amp; r){ // at this stage , instead (gdb) p this $1 = (World * const) 0x0 (gdb) p *this Cannot access memory at address 0x0 (gdb) p objects Cannot access memory at address 0x30 (gdb) p &amp;objects $2 = (std::vector&lt;GeometricObject*, std::allocator&lt;GeometricObject*&gt; &gt; *) 0x30 std::cout &lt;&lt; "hitObjects begins" &lt;&lt; std::endl; ShadeRec sr(*this); int objNum = objects.size(); // in this scope objects.size() throw a segfault double t, tmin = viewLimit; for(int i = 0; i &lt; objNum ; i++){ if(objects.at(i)-&gt;hit(r, t, sr) &amp;&amp; t &lt; tmin){ sr.haveHit = true; sr.color = objects.at(i)-&gt;getColor(); tmin = t; } } return sr; } void World::renderScene() const{ std::cout &lt;&lt; "renderScene begins" &lt;&lt; std::endl; RGBColor col; Ray ray; double z = 10; double x, y; ray.d = Vect3(0.,0.,-1.); for(int r = 0; r &lt; vp.vRes; r++) for(int c = 0; c &lt; vp.hRes; c++){ x = vp.s*(c-(vp.hRes-1)*.5); y = vp.s*(r-(vp.vRes-1)*.5); ray.o = Point(x, y, z); std::cout &lt;&lt; "debug - " &lt;&lt; r &lt;&lt; " " &lt;&lt; c &lt;&lt; std::endl; col = tracer_ptr-&gt;traceRay(ray); std::cout &lt;&lt; "exit traceRay" &lt;&lt; std::endl; rendering-&gt;at&lt;cv::Vec3b&gt;(cv::Point(c,r)) = cv::Vec3b(col.b*255,col.g*255,col.r*255); } } void World::displayImage() const{ cv::imwrite("rendering.png", *rendering); cv::namedWindow("Rendering", cv::WINDOW_AUTOSIZE ); if(!rendering-&gt;empty()) cv::imshow("Rendering", *rendering); cv::waitKey(0); } </code></pre> <p>and at last the MultipleObject class that launch traceRay() in world::renderScene() and call world::hitObject() in itself</p> <pre><code>class MultipleObjects: public Tracer{ public: MultipleObjects(); MultipleObjects(World *); ~MultipleObjects(); RGBColor traceRay(const Ray &amp;) const; protected: World * world_ptr; }; // definitions MultipleObjects::MultipleObjects(): Tracer(){} MultipleObjects::MultipleObjects(World * w): Tracer(w){} MultipleObjects::~MultipleObjects(){} RGBColor MultipleObjects::traceRay(const Ray &amp; r) const{ ShadeRec sr(world_ptr-&gt;hitObjects(r)); if(sr.haveHit) return sr.color; else return world_ptr-&gt;backgroundColor; } </code></pre> <p>The question is: why in World::build() scope all works, whereas in World::hitObjects(), this point to NULL and &amp;objects point to 0x30? </p> <p>Thanks in advance for answers and sorry for my bad English and eventually for my first question. </p>
1
HQL Join with three tables
<p>I'm having some issues with HQL since I'm a newbie with it. Even though I don't have issues with &quot;simple queries&quot;, I am currently stuck with a query involving three tables.</p> <p>I have already gone through some tutorials, but I haven't been able to find a valid example for my needs. I have tried my best to explain my problem:</p> <p>I have three different tables, let's name them <code>HOUSES</code>, <code>OWNERS</code>, and <code>OWNERINFOS</code>.</p> <p>Given a <code>townId</code>, I need to <strong>list all houses</strong> from that town, <strong>including</strong> <code>name</code> and <code>surname</code> of that house-owner.</p> <p>I made a really simple graph to show the connections between tables:</p> <p><a href="https://i.stack.imgur.com/c6yZv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c6yZv.png" alt="enter image description here" /></a></p> <p>I'm also not sure which join-strategy I should use. Any kind of help would be highly appreciated, since solving this is a priority for me.</p> <p>Thanks in advance!</p>
1
How to make a scala library?
<p>I'm not a very experienced programmer and very new to scala. I am in a situation where I have to write a library for other people to use. I do not have access to the repo of the people I am doing this for, so I cannot simply write a class for them - it needs to be library-type thing that they can include when building their own code. How does one go about achieving this? Should I build a .jar from my source, and then they'll be able to include it somehow, or is there no other way than to directly provide the source code to them?</p>
1
Define make variable from $(shell) as a string in C
<p>I am compiling code using a makefile for an embedded application on the STM32f4 family of chips.</p> <p>When I do:</p> <p>Makefile:</p> <pre><code>DEFINES += -DGIT_HASH="test hash" </code></pre> <p>In my <code>main.c</code>:</p> <pre><code>const char * git_hash = GIT_HASH; </code></pre> <p>When I print out <code>git_hash</code>, I get <code>test hash</code>.</p> <p>What I would like to do is:</p> <p>Makefile:</p> <pre><code>COMMIT_HASH = $(shell git rev-parse HEAD) DEFINES += -DGIT_HASH=$(COMMIT_HASH) </code></pre> <p>In my <code>main.c</code>:</p> <pre><code>const char * git_hash = GIT_HASH; </code></pre> <p>I get an error:</p> <pre><code>&lt;command-line&gt;:0:10: error: 'c1920a032c487a55b1b109d8774faf05e2ba42d0' undeclared here (not in a function) src/run/main.c:173:25: note: in expansion of macro 'GIT_HASH' const char * git_hash = GIT_HASH; </code></pre> <p>I am wondering why the <code>COMMIT_HASH</code> is not treated the same way as a string. Any insight would be appreciated.</p>
1
Protocol Enumerable not implemented for - Elixir
<p>I am following this tutorial <a href="http://elixirdose.com/post/building-a-simple-stream-media-app" rel="nofollow">building-a-simple-stream-media-app</a></p> <p>When i go to change the list to Struct <em>Not quite sure what i am doing, really new to this.</em> it's not working, keep getting </p> <blockquote> <p>protocol Enumerable not implemented </p> </blockquote> <p>My controller</p> <pre><code>defmodule Blog.PageController do use Blog.Web, :controller def index(conn, _params) do media_dir = "./priv/static/media/" filetype = [".mp4", ".png"] {:ok, files} = File.ls(media_dir) filtered_files = Enum.filter(files, fn(file) -&gt; String.ends_with?(file, [".mp4", ".png"]) end) struct_files = Enum.map(filtered_files, fn(file) -&gt; %Blog.Media{filename: file} end ) render conn, "index.html", files: struct_files end def show(conn, %{"filename" =&gt; filename}) do render conn, "show.html", filename: filename end end </code></pre> <p>Model</p> <pre><code>defmodule Blog.Media do @derive {Phoenix.Param, key: :filename} defstruct [:filename] end </code></pre>
1
Updating the Height of a Self-Sizing Table View Cell with a Text View
<p>I have a table view similar to the Compose screen in Mail, where one of the cells is used for text input. I'd like the cell to resize automatically by constraining the <code>contentView</code> of the cell to its <code>UITextView</code> subview using Auto Layout. The table view's <code>rowHeight</code> and <code>estimatedRowHeight</code> are set to <code>UITableViewAutomaticDimension</code>. Additionally, the text view's <code>scrollEnabled</code> property is set to <code>false</code> so that it reports its <code>intrinsicContentSize</code>.</p> <p>However, the cell does not update its height as lines of text are entered by the user, even though the text view itself <em>does</em> update its intrinsic content size. As far as I know, the only way to request this manually is for the table view to call <code>beginUpdates()</code> and <code>endUpdates()</code>. The height of the cell is then correctly updated, but this also causes re-layout of the entire table view. Here's (someone else's) <a href="https://github.com/jurezove/self-sizing-uitextview-in-a-table" rel="nofollow noreferrer">sample code demonstrating the problem</a>.</p> <p>How can I reflect changes in the cell's text view without laying out the entire table view?</p>
1
Include a fragment from the same thymeleaf template using "this :: content" or ":: content" not working as expected
<p>I'm including a template fragment from the same template file. Section "<a href="http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#including-template-fragments" rel="noreferrer">8.1 Including template fragments - Defining and referencing fragments</a>" of the docs states that:</p> <blockquote> <p>"<strong>::domselector</strong>" or "<strong>this::domselector</strong>" Includes a fragment from the same template.</p> </blockquote> <p>If I haven't misunderstood, I should be able to reference the fragment as follows: <code>th:include="this :: contentB"</code> or <code>th:include=":: contentB"</code> but only making full reference <code>th:include="test-fragment :: contentB"</code> works for me.</p> <p>This is the sample code:</p> <p><em>HomeController.java</em></p> <pre><code>@Controller class HomeController { @RequestMapping({ "/", "index", "home" }) String index(Model model) { return "test"; } } </code></pre> <p><em>test.html</em></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;ul th:replace="test-fragment :: contentA" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><em>test-fragment.html</em></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;ul th:fragment="contentA"&gt; &lt;li th:each="idx : ${#numbers.sequence(1,4)}" th:switch="${idx}"&gt; &lt;th:block th:case="1" th:include="test-fragment :: contentB" th:with="strVar = 'One'"/&gt; &lt;th:block th:case="2" th:include="this :: contentB" th:with="strVar = 'Two'"/&gt; &lt;th:block th:case="3" th:include=" :: contentB" th:with="strVar = 'Three'"/&gt; &lt;th:block th:case="*" th:include="/test-fragment :: contentB" th:with="strVar = 'Other'"/&gt; &lt;/li&gt; &lt;/ul&gt; &lt;span th:fragment="contentB"&gt; &lt;span th:text="|value: ${strVar}|" /&gt; &lt;/span&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Output is:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;ul&gt; &lt;li&gt;&lt;span&gt;value: One&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;span&gt;value: Other&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Case 2 and 3 are missing. What am I doing wrong? </p> <p>I'm testing using <a href="http://projects.spring.io/spring-boot/" rel="noreferrer">Spring Boot</a> 1.3.2.RELEASE</p> <p>EDIT:</p> <p>I've made a small test project to reproduce the issue, it can be found here: <a href="https://github.com/t-cst/thymeleaf-springboot-test" rel="noreferrer">https://github.com/t-cst/thymeleaf-springboot-test</a></p> <p>EDIT:</p> <p>After some debug, I find out that when the fragment selector is <code>"this :: contentB"</code> or <code>" :: contentB"</code> then the template name is resolved as <code>test</code> instead of <code>test-framgent</code>. This is done at:</p> <p><code>StandardFragment#extractFragment:189</code> from thymeleaf-2.1.4.RELEASE:</p> <pre><code>/* 186 */ String targetTemplateName = getTemplateName(); if (targetTemplateName == null) { if (context != null &amp;&amp; context instanceof Arguments) { targetTemplateName = ((Arguments)context).getTemplateName(); /* 190 */ } else { throw new TemplateProcessingException( "In order to extract fragment from current template (templateName == null), processing context " + "must be a non-null instance of the Arguments class (but is: " + (context == null? null : context.getClass().getName()) + ")"); /* 195 */ } } </code></pre> <p>But I still don't know why this happens in my test.</p> <p>EDIT:</p> <p>I've also asked at <a href="http://forum.thymeleaf.org/Include-a-fragment-from-the-same-thymeleaf-template-using-quot-this-content-quot-or-quot-content-quod-td4029523.html" rel="noreferrer">thymeleaf forum</a>. Maybe it's a bug. I've opened an <a href="https://github.com/thymeleaf/thymeleaf/issues/466" rel="noreferrer">issue</a>.</p>
1
Update react component without parent outside of it
<p>How should I properly update component if it doesn't have a parent?</p> <p>I've found two ways to do it:</p> <h3><a href="https://jsfiddle.net/69z2wepo/28597/" rel="nofollow noreferrer">First method</a></h3> <p>Here I update component through changing component`s state:</p> <pre><code>var Hello = React.createClass({ render: function() { if (!this.state) return null; return ( &lt;div&gt;Hello {this.state.name}&lt;/div&gt; ); } }); var component = ReactDOM.render( &lt;Hello /&gt;, document.getElementById('container') ); component.setState({name: &quot;World&quot;}); setTimeout(function(){ component.setState({name: &quot;StackOverFlow&quot;}); }, 1000); </code></pre> <h3><a href="https://jsfiddle.net/69z2wepo/28596/" rel="nofollow noreferrer">Second method</a></h3> <p>Here I update component through <code>ReactDOM.render</code> method:</p> <pre><code>var Hello = React.createClass({ render: function() { return ( &lt;div&gt;Hello {this.props.name}&lt;/div&gt; ); } }); ReactDOM.render( &lt;Hello name=&quot;world&quot;/&gt;, document.getElementById('container') ); setTimeout(function(){ ReactDOM.render( &lt;Hello name=&quot;StackOverFlow&quot;/&gt;, document.getElementById('container') ); }, 1000); </code></pre> <p>So which method is correct? Or maybe here is a third, <em>correct</em> way?</p>
1
Yii 1: Could not find driver error when connecting to microsoft sql server
<p>I successfully tested that my PHP can connect to my MS SQL SERVER.</p> <pre><code>&lt;?php $server = 'SRV-MEXAL'; // Connect to MSSQL $link = mssql_connect($server, 'mexal_db_usr', 'password_changed'); if (!$link) { die('Something went wrong while connecting to MSSQL'); } else { echo "Works &lt;br&gt;"; $OK = mssql_select_db ("at6_rp"); echo $OK ? "ok" : "ko"; } ?&gt; </code></pre> <p>Using this script I got both <code>Works</code> and <code>ok</code>, so connection and db selection are both working. </p> <p>I tried to configure my db connection into Yii 1 <code>main.php</code></p> <pre><code>"mexal_db" =&gt; array ( 'class' =&gt; "CDbConnection", 'connectionString' =&gt; 'sqlsrv:Server=SRV-MEXAL; Database=at6_rp', 'enableParamLogging' =&gt; false, 'username' =&gt; 'mexal_db_usr', 'password' =&gt; 'password_changed', 'charset' =&gt; 'utf8', ), </code></pre> <p>But when trying to instantiate it, I got this exception </p> <blockquote> <p>CDbException' with message 'CDbConnection failed to open the DB connection: could not find driver' in /var/www/httpdocs/test1.phonix.it/yii/framework/db/CDbConnection.php:399</p> </blockquote> <p>What am I doing wrong?</p>
1
Error: "Qualifier must be an expression" - Android Studio
<p>Activity:</p> <pre><code>public class PreviewsFragment extends Fragment { private ViewPager mPager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.section_all_icons, container, false); ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (toolbar != null) toolbar.setTitle(R.string.section_two); mPager = (ViewPager) root.findViewById(R.id.pager); mPager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager())); TabLayout mTabs = (TabLayout) layout.findViewById(R.id.tabs); //layout: qualifier must be an expression. mTabs.setupWithViewPager(mPager); mTabs.setTabTextColors(getResources().getColor(R.color.semitransparent_white), getResources().getColor(android.R.color.white)); mTabs.setSelectedTabIndicatorColor(getResources().getColor(R.color.accent)); mTabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); return root; } @Override public void onResume() { super.onResume(); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) { Toolbar appbar = (Toolbar) getActivity().findViewById(R.id.toolbar); appbar.setElevation(0); } } @Override public void onPause() { super.onPause(); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) { Toolbar appbar = (Toolbar) getActivity().findViewById(R.id.toolbar); appbar.setElevation((int) getResources().getDimension(R.dimen.toolbar_elevation)); } } class MyPagerAdapter extends FragmentStatePagerAdapter { final String[] tabs; public MyPagerAdapter(android.support.v4.app.FragmentManager fm) { super(fm); tabs = getResources().getStringArray(R.array.tabs); } @Override public Fragment getItem(int position) { Fragment f = new Fragment(); switch (position) { case 0: f = IconsFragment.newInstance(R.array.latest); break; case 1: f = IconsFragment.newInstance(R.array.system); break; case 2: f = IconsFragment.newInstance(R.array.google); break; case 3: f = IconsFragment.newInstance(R.array.games); break; case 4: f = IconsFragment.newInstance(R.array.icon_pack); break; case 5: f = IconsFragment.newInstance(R.array.drawer); break; } return f; } @Override public CharSequence getPageTitle(int position) { return tabs[position]; } @Override public int getCount() { return tabs.length; } } </code></pre> <p>I've problems with <strong>TabLayout mTabs = (TabLayout) layout.findViewById(R.id.tabs);</strong> because <strong>layout</strong> is not considered a qualifier. I've tried to make something up but it still doesn't work. Thanks.</p>
1
Android studio: Segmentation fault while trying to deploy app on Android device
<p>I am getting <code>Segmentation fault</code> when I try to run my app from <code>Android Studio</code>. I have tried to restart the device, Android Studio and even my PC.</p> <p>This is what I get! How can I solve this</p> <pre><code>Installing APK: F:\......\app\build\outputs\apk\app-debug.apk Uploading file to: /data/local/tmp/com.astrolabe.mofa Installing com.astrolabe.mofa DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.astrolabe.mofa" Segmentation fault Launching application: com.astrolabe.mofa/com.astrolabe.mofa.FullscreenActivity. DEVICE SHELL COMMAND: am start -n "com.astrolabe.mofa/com.astrolabe.mofa.FullscreenActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Segmentation fault </code></pre> <p><strong>EDIT</strong></p> <p>This Question is not Duplicate of the one pointed out as the solution to that problem will not fix my issue!</p>
1
iOS task when application is closed
<p>I am building an app which uploads files to the server via ajax. The problem is that users most likely sometimes won't have the internet connection and client would like to have the ajax call scheduled to time when user have the connection back. This is possible that user will schedule the file upload when he's offline and close the app. Is it possible to do ajax call when the application is closed (not in background)? When app is in the background, we can use background-fetch but I have never faced a problem to do something when app is closed. </p>
1
vagrant is not a recognised internal/external command
<p>I have cloned a repository from Github following a course on Udacity. It contains a vagrant file and according to the tutorial I shoulld use <code>vagrant up</code> command to get the virtual machine started. But it says that <code>vagrant</code> is not a recognized internal/external command. How can I fix this?</p>
1
How to select only part of json, stored in Postgres, with ActiveRecord
<p>Say I have a model <code>User</code>, which has a field of type <code>json</code> called <code>settings</code>. Let's assume that this field looks roughly like this:</p> <pre><code>{ color: 'red', language: 'English', subitems: { item1: true, item2: 43, item3: ['foo', 'bar', 'baz'] } } </code></pre> <p>If I do <code>User.select(:settings)</code> I will get all the settings for each user. But I want to get only the languages for a user. I tried both:</p> <pre><code>User.select("settings -&gt; 'language'") </code></pre> <p>and</p> <pre><code>User.select("settings -&gt;&gt; 'language'") </code></pre> <p>but this just returns empty objects:</p> <pre><code>[#&lt;User:0x007f381fa92208 id: nil&gt;, ...] </code></pre> <p>Is this at all possible? If yes - can I do it using just <code>json</code> or do I need to switch to <code>jsonb</code>?</p>
1
How to find similarity between two nodes in graph (NetworkX/ Python)
<p>I've checked previous SO questions on NetworkX and most are about Graph-Graph similarity, but not Node-Node similarity. I wish to assess the similarity of two nodes in a graph, and I can't convert to vector space of attributes and do it that way because some attributes have no intrinsic order. An example should make it clear:</p> <p><a href="https://i.stack.imgur.com/5LdsL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5LdsL.png" alt="Donut Graph"></a></p> <p>Here it is clear to the human observer that ChocolateDonut is more similar to RingDonut than to PoundCake, but how does one extract that information from a graph? I roughly could guess at how one could do it in a brute force manner by comparing the in and out arcs for every node against every other node, but what would be the 'right' way to do this?</p> <p>Also I need to be able to set constraints (for example, "Get object in graph most similar to ChocolateDonut that DOES NOT have sprinkles", etc.). So if the method searches only within constraints that's a bonus so that I don't have to filter the results afterwards.</p> <p>The library used doesn't have to be NetworkX, anything that works in Python is fine.</p>
1
BULK INSERT 4866 and 7301
<p>Trying to BULK import data in SQL server with below lines but getting error:</p> <blockquote> <p>Msg 4866, Level 16, State 8, Line 3<br> The bulk load failed. The column is too long in the data file for row 1, column 96. Verify that the field terminator and row terminator are specified correctly. </p> <p>Msg 7301, Level 16, State 2, Line 3<br> Cannot obtain the required interface ("IID_IColumnsInfo") from OLE DB provider "BULK" for linked server "(null)".</p> </blockquote> <p>Is there anything wrong with my statements? As when I use import wizard it works fine.</p> <pre><code>BULK INSERT BICX.dbo.raw FROM 'D:\NEW_CDR\NEW.txt' WITH ( FIRSTROW = 5, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ); </code></pre>
1
JS function: Cannot read property 'dataset' of undefined
<p>I have a JS function that replaces a parent Node with a Youtube iFrame:</p> <pre><code>function labnolIframe() { var iframe = document.createElement("iframe"); iframe.setAttribute("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&amp;autohide=2&amp;border=0&amp;wmode=opaque&amp;enablejsapi=1&amp;controls=1&amp;showinfo=0"); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("id", "youtube-iframe"); iframe.setAttribute("width", "100%"); iframe.setAttribute("allowFullscreen", "1"); this.parentNode.replaceChild(iframe, this); } </code></pre> <p>I dynamically create divs on page load that have an onclick attribute that runs the above function:</p> <pre><code>(function() { var v = document.getElementsByClassName("youtube-player"); for (var n = 0; n &lt; v.length; n++) { var p = document.createElement("div"); p.innerHTML = labnolThumb(v[n].dataset.id); p.onclick = labnolIframe; v[n].appendChild(p); } })(); </code></pre> <p>So far, so good. But I am trying to add an additional icon that calls the function labnolIframe and having difficulty:</p> <pre><code>$('.play-icon').click(function(){ labnolIframe(); }); </code></pre> <p>When I click on .play-icon, I want to run the code that replaces the parent div with the youtube Iframe. But I've discovered that "this" in the above function is not referring to the "this" element in the DOM (unlike when I call it in the first example).</p> <p>How can I change my code so that it refers to "this" in the last example?</p>
1
start service multiple times with different intents
<p>lets say we have two buttons:</p> <p>First button: </p> <pre><code>Intent i = new Intent(this,MyService.class); i.putExtra("url","https://api.crowdscores.com/api/v1/matches/53102") startService(i); </code></pre> <p>second button :</p> <pre><code>Intent i = new Intent(this,MyService.class); i.putExtra("url","https://api.crowdscores.com/api/v1/matches/53113"); startService(i); </code></pre> <p>on MyService i have a timer which retrieve data every 30 seconds for about 2 hours long </p> <p>when i click button can't start the other one but first service is finished(Destroyed) </p> <p>how can i run the two services in parallel ? </p>
1
get second imei number through adb shell
<p>I was able to get one imei number through adb shell with command </p> <pre><code>adb shell service call iphonesubinfo 1 </code></pre> <p>But device has two imei numbers ,</p> <p>How to get second imei number through adb shell </p> <p>The output of adb shell service call iphonesubinfo 1 is as below (which is inbetween quotes) </p> <pre><code>Result: Parcel( 0x00000000: 00000000 0000000f 00320031 00340033 '........1.2.3.4.' 0x00000010: 00360035 00380037 00300039 00380039 '5.6.7.8.9.0.9.8.' 0x00000020: 00360037 00000035 '7.6.5... ') </code></pre> <p>imei=123456789098765 </p> <p>Help me to find second imei......</p>
1
Doctrine ordering toMany associations and matching Criteria
<p>I've an entity with a OneToMany association. In this association I've defined an orderby and It works fine when I retrieve it.</p> <pre><code>class client { ... /** * @ORM\OneToMany(targetEntity="Reservation", mappedBy="client") * @ORM\OrderBy({"reservation_date" = "DESC"}) */ protected $reservations; .... public function getReservations() { return $this-&gt;reservations; } .... } </code></pre> <p>The <code>getReservations</code> method works fine and It retrieve all <code>Reservations</code> ordered by the <code>reservation_date</code> field. But if I add this method:</p> <pre><code>public function getActiveReservations() { $activeCriteria = Criteria::create() -&gt;where(Criteria::expr()-&gt;eq("active", true)); return $this-&gt;getReservations()-&gt;matching($activeCriteria); } </code></pre> <p>The matching criteria <i>mess</i> all results and are not ordered by the <code>reservation_field</code>.</p> <p>How can I preserve the order after a matching criteria?</p>
1
Missing leading zeroes of date in Hive partition using Spark Dataframe
<p>I am adding a partition column to Spark Dataframe. New column(s) contains year month and day. I have a timestamp column in my dataframe.</p> <pre><code>DataFrame dfPartition = df.withColumn("year", df.col("date").substr(0, 4)); dfPartition = dfPartition.withColumn("month", dfPartition.col("date").substr(6, 2)); dfPartition = dfPartition.withColumn("day", dfPartition.col("date").substr(9, 2)); </code></pre> <p>I can see the correct values of columns when I output the dataframe eg : <code>2016 01 08</code> </p> <p>But When I export this dataframe to hive table like </p> <pre><code>dfPartition.write().partitionBy("year", "month","day").mode(SaveMode.Append).saveAsTable("testdb.testtable"); </code></pre> <p>I see that directory structure generated misses leading zeroes. I tried to cast column to String but did not work.</p> <p>Is there is a way to capture two digits date/month in hive partition</p> <p>Thanks</p>
1
Sorting a data stream before writing to file in nodejs
<p>I have an input file which may potentially contain upto 1M records and each record would look like this</p> <p><code>field 1 field 2 field3 \n</code></p> <p>I want to read this input file and sort it based on <code>field3</code> before writing it to another file. </p> <p>here is what I have so far</p> <pre><code>var fs = require('fs'), readline = require('readline'), stream = require('stream'); var start = Date.now(); var outstream = new stream; outstream.readable = true; outstream.writable = true; var rl = readline.createInterface({ input: fs.createReadStream('cross.txt'), output: outstream, terminal: false }); rl.on('line', function(line) { //var tmp = line.split("\t").reverse().join('\t') + '\n'; //fs.appendFileSync("op_rev.txt", tmp ); // this logic to reverse and then sort is too slow }); rl.on('close', function() { var closetime = Date.now(); console.log('Read entirefile. ', (closetime - start)/1000, ' secs'); }); </code></pre> <p>I am basically stuck at this point, all I have is the ability to read from one file and write to another, is there a way to efficiently sort this data before writing it</p>
1
Ruby on rails. Passing params from view to controller
<p>I'm having what I assume must be a simple problem but I just can't figure it out. I'm trying to update an attribute in one model when another is created.</p> <p>In my view:</p> <pre><code>&lt;%= link_to 'Click here to rate this user', new_user_review_path(:user_id =&gt; request.user.id, :gigid =&gt; request.gig.id), remote: true %&gt; </code></pre> <p>Which passes params <code>:gigid</code> and <code>:user_id</code></p> <p>Than my controller:</p> <pre><code>def new @review = Review.new @gig = Gig.find(params[:gigid]) end def create @review = @user.reviews.new review_params @review.reviewed_id = current_user.id if @review.save @gig.update(reviewed: true) respond_to do |format| format.html {redirect_to session.delete(:return_to), flash[:notice] = "Thankyou for your rating!"} format.js end else render 'new' end end </code></pre> <p>But I get <code>undefined method 'update'for nil:NilCLass:</code></p> <p>I know the params are passing and the 'Gig' can be updated as :</p> <pre><code>def new @review = Review.new Gig.find(params[:gigid]).update(reviewed: true) end </code></pre> <p>updates the attribute fine, but when I click 'New review' not when the review is actually created.</p> <p>Adding :</p> <pre><code>def create @review = @user.reviews.new review_params @review.reviewed_id = current_user.id if @review.save Gig.find(params[:gigid]).update(reviewed: true) etc etc etc </code></pre> <p>gives me the same <code>undefined method 'update'for nil:NilCLass:</code></p> <p>I have tried with <code>find_by_id</code> instead of <code>find</code> which makes no difference.</p> <p>EDIT:</p> <pre><code>def create @gig = Gig.find params[:gigid] @review = @user.reviews.new review_params @review.reviewed_id = current_user.id if @review.save @gig.update(reviewed: true) etc etc etc </code></pre> <p>Doesn't work either. I get no errors, but the gig ID is still 'nil'.</p> <p>The params are passing to the 'New' action but not the 'Create' action. I feel this should be very easy but I'm just not seeing it at the moment.</p>
1
SQL server Openquery equivalent to PostgresQL
<p>Is there query equivalent to sql server's openquery or openrowset to use in postgresql to query from excel or csv ? </p>
1
Remove duplicate values from comma separated string in Oracle
<p>I need your help with the regexp_replace function. I have a table which has a column for concatenated string values which contain duplicates. How do I eliminate them?</p> <p>Example:</p> <pre><code>Ian,Beatty,Larry,Neesha,Beatty,Neesha,Ian,Neesha </code></pre> <p>I need the output to be</p> <pre><code>Ian,Beatty,Larry,Neesha </code></pre> <p>The duplicates are random and not in any particular order.</p> <p>Update--</p> <p>Here's how my table looks</p> <pre><code>ID Name1 Name2 Name3 1 a b c 1 c d a 2 d e a 2 c d b </code></pre> <p>I need one row per ID having distinct name1,name2,name3 in one row as a comma separated string.</p> <pre><code>ID Name 1 a,c,b,d,c 2 d,c,e,a,b </code></pre> <p>I have tried using listagg with distinct but I'm not able to remove the duplicates. </p>
1
Connecting to Amazon Aurora with Laravel in production
<p>I've developed a Laravel app locally and connected locally to a database instance of Amazon Aurora. Had no problems connected to that DB locally but now that I've migrated to production, I get a SQLSTATE[HY000] [2003] Can't connect to MySQL server on '[AMAZON AURORA URL HERE]' (4)</p> <p>error. I'm hosting on MediaTemple. I've got the database access on Amazon set to public, so not sure why I wouldn't be able to connect using the same settings I'm connecting to locally.</p>
1
Get the json values in Http.get
<p>I was trying to create a small example in Angular2. What I am doing is when I click a button, this does a get to public api and show a quotes, but I can't, the value never shows and I got the error </p> <blockquote> <p>Cannot read property 'quotes' of undefined in [{{quote.contents.quotes.quote}} in App@4:20]</p> </blockquote> <p>My Component.ts</p> <pre><code>import {Component, OnInit, Injectable} from 'angular2/core'; import {Http, HTTP_PROVIDERS, URLSearchParams} from 'angular2/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app', template: `&lt;ul&gt; &lt;li (click)='myAlert()'&gt; Helow World&lt;/li&gt; &lt;/ul&gt; &lt;div&gt; &lt;spam&gt;{{quote.contents.quotes.quote}}&lt;/spam&gt; &lt;/div&gt;`, providers: [HTTP_PROVIDERS] }) export class App { public quote: Object; public logError: string; constructor(private http: Http){ this.quote = {}; } myAlert(){ this.http.get("http://quotes.rest/qod.json").map(res =&gt; { return res.json()}) .subscribe( data =&gt; this.quote = data, err =&gt; this.logError(err), () =&gt; console.log('Random Quote Complete') ); } } </code></pre> <p>My boot.ts</p> <pre><code>import {bootstrap} from 'angular2/platform/browser' import {App} from './component' import {HTTP_PROVIDERS} from 'angular2/http'; bootstrap(App, [HTTP_PROVIDERS]).catch(err =&gt; console.error(err)); </code></pre> <p>Index.html</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Angular 2 QuickStart&lt;/title&gt; &lt;!-- 1. Load libraries --&gt; &lt;script src="node_modules/angular2/bundles/angular2-polyfills.js"&gt;&lt;/script&gt; &lt;script src="node_modules/systemjs/dist/system.src.js"&gt;&lt;/script&gt; &lt;script src="node_modules/rxjs/bundles/Rx.js"&gt;&lt;/script&gt; &lt;script src="node_modules/angular2/bundles/angular2.dev.js"&gt;&lt;/script&gt; &lt;script src="https://code.angularjs.org/2.0.0-beta.1/http.js"&gt;&lt;/script&gt; &lt;!-- 2. Configure SystemJS --&gt; &lt;script&gt; System.config({ packages: { app: { format: 'register', defaultExtension: 'js' } } }); System.import('app/boot') .then(null, console.error.bind(console)); &lt;/script&gt; &lt;/head&gt; &lt;!-- 3. Display the application --&gt; &lt;body&gt; &lt;app&gt;Loading...&lt;/app&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>How Do I get the values from the service's subscribe and put into my template?</p>
1
XAMPP Connection for controluser as defined in your configuration failed phpmyadmin xampp
<p>I have a windows and I installed XAMPP for it, for a web app I am building as part of my class project. I installed it using recommended settings and didn't change anything, but when I try to access localhost/phpmyadmin, and even 127.0.0.1/phpmyadmin, I get the error:</p> <pre><code>Connection for controluser as defined in your configuration failed. </code></pre> <p>I looked at the other questions posted here on Stackoverflow about the same issue and tried some of the answers posted, but nothing seems to work. I am thoroughly confused and lost. Should I just find another service to use?</p>
1
Javascript how to override a constructor method?
<p>I have a <code>View</code> class that has a constructor method <code>initialize</code> I think this is a constructor method, correct me if wrong.</p> <pre><code>var View = function(obj) { this.initalize = obj.initalize; }; </code></pre> <p>What I would like to achieve is something gets called when the Class is instantiated. </p> <p>How can I pass in an object like so?</p> <pre><code>var chatView = new View({ initialize: function() { alert('Yay for initialization'); } }); </code></pre> <p>So that when I instantiate the <code>View</code> I can pass an object to the constructor and within a key <code>initialize</code> which value is a function and this key specifically gets called when instantiated.</p>
1
Using Scanner as a parameter of a method
<p>Basically I am trying to use a scanner as a method. This is what I have (I've used <code>int</code> in the meantime because I have not been able to figure out how to use Scanner as a parameter)</p> <pre><code>public class LoopPatterns { public static int sum(int number1, int number2){ int sum = number1 + number2; return sum; } public static void main(String[] args) { System.out.println(sum(3, 4)); } } </code></pre> <p>So this is what I have so far. However, the main point is that I need to get the sum of an unspecified amount of digits. I need to use a scanner but I haven't been able to figure out how to use it as a parameter of my method. Anyway, I hope that was concise enough. Thanks!</p>
1
Output SqlParameter Error: the Size property has an invalid size of 0
<p>I know there are a few other threads/questions about this error, but I wanted to get a bit more insight if possible. We've seen this error occur intermittently for a particular piece of code where we have an Integer type output parameter. </p> <p>This is how we're defining the parameter:</p> <pre><code>SqlParameter errorParam = new SqlParameter("@ErrorCode", errorCode); errorParam.Direction = ParameterDirection.Output; </code></pre> <p>You'll notice no size and no DBType is specified. It seems the error doesn't always occur, but sometimes this will be thrown:</p> <p><strong>the Size property has an invalid size of 0. at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc) at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)</strong></p> <p>I'm assuming I need to add the DBType and Size settings, but what might be underlying reason be that this is occurring, and only in some occasions?</p> <p>Note, the parameter in SQL is defined as:</p> <pre><code>@ErrorCode INT OUT , </code></pre>
1
How to make part of a string italics in java?
<p>say I have a string "How are you?" How would I convert just the word "you" into italics.</p> <p>PS, I am a beginner so please don't incorporate advanced programming.</p>
1
Get the pid of a running playbook for use within the playbook
<p>When we run a playbook, with verbose output enabled, in the ansible logs we can see something like this:</p> <p><code>2016-02-03 12:51:58,235 p=4105 u=root | PLAY RECAP</code></p> <p>I guess that the <code>p=4105</code> is the pid of the playbook when it ran.</p> <p>Is there a way to get this pid inside the playbook during its runtime (as a variable for example)?</p>
1
revealViewController() always returns nil
<p>I'm having some troubles with <code>revealViewController</code> in Xcode 7.2 and iOS 9.2.</p> <p>My app starts with a view controller embedded in a navigation controller to perform a login. After login, or if the login token is present, I jump to another view controller embedded in a navigation controller with the following code:</p> <pre><code>let homePage = self.storyboard?.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController let homePageNav = UINavigationController(rootViewController: homePage) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.window?.rootViewController = homePageNav </code></pre> <p>In this home view controller I would like to have a left navigation menu with <code>SWRealViewController</code>.</p> <p>I had the <code>SWRealViewController</code> view linked with <code>sw_front</code> to my home navigation controller, and the following code:</p> <pre><code>if (self.revealViewController() != nil) { self.menuButton.target = self.revealViewController() self.menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) </code></pre> <p>But <code>self.revealViewController()</code> always returns nil, so it does not work.</p> <p>I think I lost the <code>revealViewController</code> somewhere (maybe when I jump from the first navigation controller to the second) but I do not know what to do.</p>
1
how can you open a URL with a specified web browser in python 3
<p>I am creating a program in python 3 and i would like the user to open a URL with a specified web browser application.I have tried using the <code>subprocess.Popen([application, URL])</code> but it raises a <code>FileNotFoundError</code>. Any help is greatly appreciated.</p> <p>EDIT: I forgot to mention that I am using Windows 10, and here is a copy of the Error message I am getting:</p> <pre><code>Traceback (most recent call last): File "C:\Users\[Name]\Desktop\AI.py", line 221, in &lt;module&gt; subprocess.Popen(["google-chrome", "www.google.co.uk/"]) File "C:\Python34\lib\subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified </code></pre> <p>EDIT2: This is my result if i try running <code>subprocess.Popen(["start", "chrome", "www.example.com/"])</code> (and i get the same error if i leave out the <code>"start",</code> part of the array):</p> <pre><code>`Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; subprocess.Popen(["start", "chrome", "http://www.google.co.uk/"]) File "C:\Python34\lib\subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified` </code></pre>
1
Access VBA to Close a Chrome window opened via Shell
<p>I am attempting to close a <code>shell</code> <code>Chrome</code> window via a VBA function. My function runs a URL query that returns a <code>.csv</code> file. The thing is I would like to close the window so that it is not always showing (This process runs every 3 minutes). I haven't been able to find a solution that I can get to work as of yet. I tried adding <code>SendKeys "%{F4}"</code> after as one site suggested. This merely minimizes the window, not close it. I also attempted to try adding <code>DoCmd.Close Shell, "Untitled"</code> after, yet this also did not work. I have spent several hours attempting to do, what I imagine is a simple task, and felt another set of eyes could point me in the right direction. Below is my code that opens <code>Chrome</code>. Any assistance is greatly appreciated.</p> <pre><code>Public Function RunYahooAPI() Dim chromePath As String chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe""" Shell (chromePath &amp; " -url http://download.finance.yahoo.com/d/quotes.csv?s=CVX%2CXOM%2CHP%2CSLB%2CPBA%2CATR%2CECL%2CNVZMY%2CMON&amp;f=nsl1op&amp;e=.csv") End Function </code></pre>
1
How to add packages to populate SDK as a host tool?
<p>I have created my own recipe for building my SW, which requires native perl during building (e.g. invoking perl script for generating code). There is no problem if I add my recipe to an image and use bitbake to build my recipe with the image.</p> <p>Now I also want to build SW with a populate SDK, but I found that when I generate the populate SDK, the native perl only contains a few modules without what is necessary to build my SW. I have found two ways to generate the populate SDK with additional perl modules:</p> <ol> <li>Add TOOLCHAIN_HOST_TASK += "nativesdk-perl-modules" to my image .bb file before I generate the populate SDK</li> <li>Add a bbappend file for nativesdk-packagegroup-sdk-host which includes "nativesdk-perl-modules" in RDEPENDS</li> </ol> <p>For 1, it is an image-specific solution. For 2, it is a global solution.</p> <p>Now I am looking for a recipe-specific solution. Is there a solution where I could add some configuration in my recipe .bb file, and then I build populate SDK for any image which include my recipe will contains these additional native perl modules?</p>
1
Saving all values in "multiple select"
<p>im having a metabox in wordpress with a mutliple select form. </p> <pre><code>&lt;select name="my_meta_box_select" id="my_meta_box_select" multiple="" style="width:300px; height:400px;"&gt; &lt;option value="red"&gt;Red &lt;/option&gt; &lt;option value="blue"&gt;Blue &lt;/option&gt; &lt;/select&gt; </code></pre> <p>So far so good, the selected value gets saved and I am able to retrieve it, however I wish for both values to be saved.</p> <p>For example I wish to save both red AND blue and be able to retrieve it from the frontend. Is there any way to achieve this? Are there better forms than a select?</p> <p>The purpose is for a user to select pages from one select field to another and then save the second select field.</p> <p>select 1: </p> <p>red</p> <p>blue</p> <p>green</p> <p>Select 2:</p> <p>orange</p> <p>-button-</p> <p>Now if a user where to select <code>red</code> and <code>blue</code> from <code>select 1</code> and then press <code>-button-</code> the values will be added to select 2. When I now press update page I wish to save all the values in select 2.</p> <p>This is how i save from my current select field (but it only saves ONE selected value)</p> <pre><code>if( isset( $_POST['my_meta_box_select'] ) ) update_post_meta( $post_id, 'my_meta_box_select', esc_attr( $_POST['my_meta_box_select'] ) ); </code></pre>
1
Generate YAML manifest from Kubernetes types
<p>I'm looking into writing a tool that generates Kubernetes definitions programatically for our project.</p> <p>I've found that the API types in Kubernetes can be found in <code>k8s.io/kubernetes/pkg/api</code>. I would like to output YAML based on these types.</p> <p>Given an object like this:</p> <pre><code>ns := &amp;api.Namespace{ ObjectMeta: api.ObjectMeta{ Name: "test", }, } </code></pre> <p>What's the best way to generate the YAML output expected by <code>kubectl create</code>?</p>
1
Wordpress add search to custom post type archive
<p>I have a website with many custom post type for example <code>players</code> <code>teams</code> ... </p> <p>for each one of them I have archive pages like : <code>player-archive.php</code></p> <p><strong>in custom post type archive pages I want to add to the top a search ( and filter if possible ).</strong></p> <p><em>PS : I see other Questions with so code about the search but it don't work and there is no answer to the question and others with plugins but they are general to improve all the search in the site .</em></p> <p>so first of all is it possible if there is any suggestions for plugin also will be great . </p>
1
Exception HRESULT: 0x800A03EC when inserting an Excel formula
<p>This is the exception I'm getting:</p> <blockquote> <p>System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC</p> <p>at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&amp; msgData)<br /> at Microsoft.Office.Interop.Excel.Range.set_Formula(Object value)</p> </blockquote> <p>My code looks like this:</p> <pre><code>Range rng = activeWorksheet.get_Range(&quot;A1&quot;); rng.Formula = &quot;=SUM(A4*C4;A5*C5;A6*C6;A7*C7)/SUM(A4:A7)&quot;; </code></pre> <p>Whenever I run this code I get the previously mentioned exception. However, when I run this code:</p> <pre><code>Range rng = activeWorksheet.get_Range(&quot;A1&quot;); rng.Formula = &quot;=SUM(A4:A7)/4&quot; </code></pre> <p>This works perfectly. No exception.</p> <p>I've checked both formulas, they work perfectly fine in my Excel. I've tried setting:</p> <pre><code>Application.Calculation = XlCalculation.xlCalculationAutomatic; </code></pre> <p>This does not help at all, I've been googling this solution and have not found anything useful. Does anyone have a clue what might be wrong?</p>
1
Python redeclared variable defined before in PyCharm
<p>After having written this piece of code to execute queries on database separately, <em>PyCharm</em> highlighted the second <em>i</em> with the given comment. </p> <pre><code>for i in range(records): filler.apply_proc('AddCompany', gen_add_company()) for i in range(records): filler.apply_proc('AddConference', gen_add_conference()) </code></pre> <blockquote> <p>Redeclared 'i' defined above without usage.</p> </blockquote> <p>Could it be subject of any error? Should I achieve it in other way?</p>
1
RegEx to accept only numbers between 0-9
<p>I'm fairly new to using regex and I've got a problem with the results of this one.</p> <p>Regex @"^0[0-9]{9,10}$" is accepting spaces between the digits. How to I stop this as I only want digits between 0-9 to be acceptable characters.</p> <p>The valid result should start with zero and have either 9 or 10 digits (no spaces or any other character is permissible).</p> <p>All help appreciated.</p> <p>Here's my code</p> <pre><code>Regex telephoneExp = new Regex(@"^0[0-9]{9,10}$"); if (telephoneExp.Match(txtTelephoneNumber.Text).Success==false) { MessageBox.Show("The telephone number is not valid, it must only contain digits (0-9) and be either 10 or 11 digits in length."); return false; } </code></pre>
1
Android: setResult not returning result to Parent Activity
<p>I have started a child activity from parent activity using <strong>startActivityForResult</strong>. After performing required functions in child activity I am setting result using <strong>setResult</strong>. But I am not getting result at parent activity from child activity.</p> <p>Heres my code.</p> <p>Here is how I call my child activity from parent activity.</p> <pre><code> Intent i = new Intent(MainActivity.this, Child.class); i.putExtra("ID", intID); i.putExtra("aID", aID); i.putExtra("myMsg", myMsg); startActivityForResult(i, 1); </code></pre> <p>This is how I set result from my child activity.</p> <pre><code> @Override public void onBackPressed() { super.onBackPressed(); Intent resultInt = new Intent(); resultInt.putExtra("Result", "Done"); setResult(Activity.RESULT_OK, resultInt); finish(); } </code></pre> <p>This is my <strong>onActivityResult</strong></p> <pre><code> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == Activity.RESULT_OK) { if(data!=null) { Toast.makeText(MainActivity.this, "Data received", Toast.LENGTH_SHORT).show(); } } } } </code></pre> <p>Here the when i check for <strong>resultCode==Activity.RESULT_OK</strong> is giving false. And I also checked for intent passed outside of this if condition and its returning null.</p> <pre><code> &lt;activity android:name=".MainActivity" android:label="Main" android:parentActivityName=".MainPage" android:theme="@style/AppTheme.NoActionBar"&gt; &lt;meta-data android:name="android.support.PARENT_ACTIVITY" android:value="org.mydomain.mydomain.MainPage" /&gt; &lt;/activity&gt; &lt;activity android:name=".Child" android:label="Child" android:parentActivityName=".MainActivity" android:theme="@style/AppTheme1"&gt; &lt;meta-data android:name="android.support.PARENT_ACTIVITY" android:value="org.mydomain.mydomain.MainActivity" /&gt; &lt;/activity&gt; </code></pre> <p>Can anyone help me to fix this issue.</p>
1
How to synchronize TPL Tasks, by using Monitor / Mutex / Semaphore? Or should one use something else entirely?
<p>I'm trying to move some of my old projects from <code>ThreadPool</code> and standalone <code>Thread</code> to TPL <code>Task</code>, because it supports some very handy features, like continuations with <code>Task.ContinueWith</code> (and from C# 5 with <code>async\await</code>), better cancellation, exception capturing, and so on. I'd love to use them in my project. However I already see potential problems, mostly with synchronization.</p> <p>I've written some code which shows a Producer / Consumer problem, using a classic stand-alone <code>Thread</code>:</p> <pre><code>class ThreadSynchronizationTest { private int CurrentNumber { get; set; } private object Synchro { get; set; } private Queue&lt;int&gt; WaitingNumbers { get; set; } public void TestSynchronization() { Synchro = new object(); WaitingNumbers = new Queue&lt;int&gt;(); var producerThread = new Thread(RunProducer); var consumerThread = new Thread(RunConsumer); producerThread.Start(); consumerThread.Start(); producerThread.Join(); consumerThread.Join(); } private int ProduceNumber() { CurrentNumber++; // Long running method. Sleeping as an example Thread.Sleep(100); return CurrentNumber; } private void ConsumeNumber(int number) { Console.WriteLine(number); // Long running method. Sleeping as an example Thread.Sleep(100); } private void RunProducer() { while (true) { int producedNumber = ProduceNumber(); lock (Synchro) { WaitingNumbers.Enqueue(producedNumber); // Notify consumer about a new number Monitor.Pulse(Synchro); } } } private void RunConsumer() { while (true) { int numberToConsume; lock (Synchro) { // Ensure we met out wait condition while (WaitingNumbers.Count == 0) { // Wait for pulse Monitor.Wait(Synchro); } numberToConsume = WaitingNumbers.Dequeue(); } ConsumeNumber(numberToConsume); } } } </code></pre> <p>In this example, <code>ProduceNumber</code> generates a sequence of increasing integers, while <code>ConsumeNumber</code> writes them to the <code>Console</code>. If producing runs faster, numbers will be queued for consumption later. If consumption runs faster, the consumer will wait until a number is available. All synchronization is done using <code>Monitor</code> and <code>lock</code> (internally also <code>Monitor</code>).</p> <p>When trying to 'TPL-ify' similar code, I already see a few issues I'm not sure how to go about. If I replace <code>new Thread().Start()</code> with <code>Task.Run()</code>:</p> <ol> <li>TPL <code>Task</code> is an abstraction, which does not even guarantee that the code will run on a separate thread. In my example, if the producer control method runs synchronously, the infinite loop will cause the consumer to never even start. According to MSDN, providing a <code>TaskCreationOptions.LongRunning</code> parameter when running the task should <strong>hint</strong> the <code>TaskScheduler</code> to run the method appropriately, however I didn't find any way to ensure that it does. Supposedly TPL is smart enough to run tasks the way the programmer intended, but that just seems like a bit of magic to me. And I don't like magic in programming.</li> <li>If I understand how this works correctly, a TPL <code>Task</code> is not guaranteed to resume on the same thread as it started. If it does, in this case it would try to release a lock it doesn't own while the other thread holds the lock forever, resulting in a deadlock. I remember a while ago Eric Lippert writing that it's the reason why <code>await</code> is not allowed in a <code>lock</code> block. Going back to my example, I'm not even sure how to go about solving this issue.</li> </ol> <p>These are the few issues that crossed my mind, although there may be <em>(probably are)</em> more. How should I go about solving them?</p> <p>Also, this made me think, is using the classical approach of synchronizing via <code>Monitor</code>, <code>Mutex</code> or <code>Semaphore</code> even the right way to do TPL code? Perhaps I'm missing something that I should be using instead?</p>
1
UI Scrollbar Scroll Sensitivity For Mouse Wheel Scroll
<p>I am trying to adjust the scrollbar scroll speed because it is too slow. I only found this on the web. But I don't know how to use it. </p> <pre><code>UI.ScrollRect.scrollSensitivity </code></pre> <p>I am trying this to create a <code>Text</code> that contains some information (like what's new in unity 5.3? )</p>
1
R text mining - dealing with plurals
<p>I'm learning text mining in R and have had pretty good success. But I am stuck on how to deal with plurals. i.e. I want "nation" and "nations" to be counted as the same word and ideally "dictionary" and "dictionaries" to be counted as the same word.</p> <pre><code>x &lt;- '"nation" and "nations" to be counted as the same word and ideally "dictionary" and "dictionaries" to be counted as the same word.' </code></pre>
1
LibCurl SFTP get full list of files
<p>I need to get full file list from 2 servers (ftp and sftp) with libcurl.</p> <p>Libcurl Information:</p> <pre><code>System: Windows 7; Wrapper: SourcePawn; Version: libcurl/7.23.1 OpenSSL/0.9.8r zlib/1.2.5 libssh2/1.3.0; Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp scp sftp smtp smtps telnet tftp. </code></pre> <p>The point is, my code returns full filelist for the ftp server, but not for sftp. for the sftp server I only get one (first line).</p> <p>here is my code:</p> <pre><code>public RequestFileList() { new Handle:curl = curl_easy_init(); if(curl != INVALID_HANDLE) { LogMessage("RequestFileList"); CURL_DEFAULT_OPT(curl); curl_easy_setopt_function(curl, CURLOPT_WRITEFUNCTION, GetFileList); curl_easy_setopt_string(curl, CURLOPT_URL, "sftp://xxxxx:5000/"); curl_easy_setopt_string(curl, CURLOPT_USERPWD, "xxx:xxx"); curl_easy_setopt_int(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY); curl_easy_setopt_int(curl, CURLOPT_VERBOSE, 1); curl_easy_perform_thread(curl, onCompleteFilelist, 1); } } public GetFileList(Handle:hndl, const String:buffer[], const bytes, const nmemb) { LogMessage("%s %i %i", buffer, bytes, nmemb); } </code></pre> <p>output:</p> <pre><code>drwxr-xr-x 11 root root 0 Mar 27 2014 sys 1 60 </code></pre> <p>if i execute it with cmd: </p> <pre><code>curl -k -u xxx:xxx sftp://xxxx:5000/ </code></pre> <p>I get full filelist:</p> <pre><code>drwxr-xr-x 11 root root 0 Mar 27 2014 sys drwx------ 2 root root 16384 Jul 30 2009 lost+found drwxr-xr-x 22 root root 4096 Dec 31 2013 work drwxr-xr-x 2 root root 4096 Jul 30 2009 plugin </code></pre> <p>What shall I change to get full filelist?</p> <p>Here is full log:</p> <pre><code>* About to connect() to xxxxxxxxxxx port 5000 (#0) * Trying xxx.xxx.xxx.xxx... * connected * SSH authentication methods available: publickey,gssapi-keyex,gssapi-with-mic,password * Using ssh public key file id_dsa.pub * Using ssh private key file id_dsa * SSH public key authentication failed: Unable to open public key file * Initialized password authentication * Authentication complete L 02/07/2016 - 13:57:36: [pl.smx] STR - drwxr-xr-x 11 root root 0 Mar 27 2014 sys 1 60 * Connection #0 to host xxxxxxxxxxxxxxxx left intact * Closing connection #0 </code></pre>
1
How to Print Out the Square Root of A Negative Number with i Displayed in C
<p>I am trying to figure out how to display the square root of a number if it happens to be negative (as it is entered by the user), and if so, display it correctly with the "i" displayed as well. When I do the normal <code>sqrt</code> function, the result is always something like -1.#IND. When I tried using the double complex variables, the positive numbers nor the negative numbers would come out clean. </p> <p>Below is my code; the comments are what my goal is. The 4 num variables are entered by the user and can be any integer, positive or negative. </p> <pre><code> // Display the square root of each number. Remember that the user can enter negative numbers and // will need to find the negative root with the "i" displayed. printf("\nThe square root of %d is %.4f", num1, sqrt(num1)); printf("\nThe square root of %d is %.4f", num2, sqrt(num2)); printf("\nThe square root of %d is %.4f", num3, sqrt(num3)); printf("\nThe square root of %d is %.4f", num4, sqrt(num4)); </code></pre>
1
How to animate FAB (expand) to a new Activity
<p>What I'd like to achieve is an effect like this:</p> <p><a href="https://i.stack.imgur.com/ijj3X.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ijj3X.gif" alt="enter image description here"></a></p> <p>Is it something I can achieve using <code>ActivityOptionsCompat</code> or are there other options? How can I replicate an effect like this where the FAB kinda "expands" to a new <code>Activity</code>?</p>
1
Ignore pandas warnings
<p>There are <a href="https://stackoverflow.com/q/9031783/647991">some similar questions</a>, but the replies there do not work for me.</p> <p>I am trying to do this, as explained in the <a href="https://docs.python.org/3.4/library/warnings.html" rel="nofollow noreferrer">warnings documentation</a>:</p> <pre><code>def disable_pandas_warnings(): import warnings warnings.resetwarnings() # Maybe somebody else is messing with the warnings system? warnings.filterwarnings('ignore') # Ignore everything # ignore everything does not work: ignore specific messages, using regex warnings.filterwarnings('ignore', '.*A value is trying to be set on a copy of a slice from a DataFrame.*') warnings.filterwarnings('ignore', '.*indexing past lexsort depth may impact performance*') </code></pre> <p>And I call this at the start of my test/program:</p> <pre><code>disable_pandas_warnings() </code></pre> <p>As you can see in the comments, I have:</p> <ul> <li>made sure that the warnings filters are not polluted (since filtering is performed on a first-match way)</li> <li>ignore all messages</li> <li>ignore specific messages (by giving message regex)</li> </ul> <p>Nothing seems to work: messages are still displayed. How can I disable all warnings?</p>
1
UITextField secureTextEntry toggle set incorrect font
<p>I have an <code>UITextField</code> which I use as a password field. It has by default <code>secureTextEntry</code> set to <code>true</code>. I also have a <code>UIButton</code> to toggle the show/hide of the password.</p> <p>When I change the textfield from <code>secureTextEntry</code> set to <code>true</code> to <code>false</code>, the font gets weird. Seems it becomes Times New Roman or similar.</p> <p>I have tried re-setting the font to system with size 14, but it didn't change anything. </p> <p>Example of what happens (with initial <code>secureTextEntry</code> set to <code>true</code>): <a href="https://i.stack.imgur.com/ab5sy.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ab5sy.gif" alt="Example"></a></p> <p>My code:</p> <pre><code>@IBAction func showHidePwd(sender: AnyObject) { textfieldPassword.secureTextEntry = !textfieldPassword.secureTextEntry // Workaround for dot+whitespace problem if !textfieldPassword.secureTextEntry { let tempString = textfieldPassword.text textfieldPassword.text = nil textfieldPassword.text = tempString } textfieldPassword.font = UIFont.systemFontOfSize(14) if textfieldPassword.secureTextEntry { showHideButton.setImage(UIImage(named: "EyeClosed"), forState: .Normal) } else { showHideButton.setImage(UIImage(named: "EyeOpen"), forState: .Normal) } textfieldPassword.becomeFirstResponder() } </code></pre>
1
QNetworkReply error: Network access is disabled
<p>I am using QNetworkRequest/QNetworkReply to download a file. On an older program version which was used by thousands of people it worked flawlessly (VS 2010 compiler). After upgrading to Visual Studio 2015 and recompiling the whole project with XP target (the same procedure with OpenSSL) <strong>a few</strong> users started getting an error when the download is initiated: </p> <blockquote> <p>Network access is disabled.</p> </blockquote> <p>The error is logged in a slot that is connected to error() signal from QNetworkReply::NetworkError.</p> <p>Code:</p> <pre><code>QNetworkReply reply = nam.get(QNetworkRequest(url)); emit sendInfo("Starting download"); QObject::connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot())); QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(errorSlot(QNetworkReply::NetworkError))); QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(progressSlot(qint64, qint64))); </code></pre> <p>I managed to install Wireshark on one of the affected machines but no requests are made to the internet so it is failing from the very beginning. So far I was not able to find out what causes the problem on these machines. OS version does not matter, tried disabling AV/firewall etc. I am also unable to find any details of the error string that is returned.</p> <p>The code works fine for 90% of the people and was tested from XP SP3 up to Windows 10.</p> <p>What could be a problem and how do I even approach to debug this?</p>
1
Mule the namespace on the "definitions" element, is not a valid SOAP version
<p>I have a Mule flow that uses the Web Service Consumer to call a SOAP Web Service.</p> <p>I have checked that the XML that I give to the Web Service Consumer for the request is fine. The XML works fine for instance if I test it in SoapUI.</p> <p>The same produced XML throws the following error when using the Web Service Consumer component:</p> <pre><code>ERROR 2016-01-26 13:53:00,194 [[api-gateway].http-lc-0.0.0.0-8081.worker.01] org.mule.exception.CatchMessagingExceptionStrategy: ******************************************************************************** Message : "http://schemas.xmlsoap.org/wsdl/", the namespace on the "definitions" element, is not a valid SOAP version.. Message payload is of type: NullPayload Type : org.mule.module.ws.consumer.SoapFaultException </code></pre> <p>This seems to be like the Web Service Consumer does not detect the Soap Version correctly.</p>
1
gdb, breakpoint in multiple locations
<p>I've set a breakpoint in one of the .h files which has an implementation of a small method, </p> <pre><code>(gdb) break SmallVector.h:141 </code></pre> <p>And here is what I got from gdb:</p> <pre><code>Breakpoint 5 at 0x416312: SmallVector.h:141. (38 locations) </code></pre> <p>Why is the breakpoint set in 38 locations instead of a single location?</p> <p>I'm not new to debugging as well as C++ but unfortunately I've never worked with anything complex like I'm working now (compiler). So I've never encountered anything like this before.</p> <p>Any help is appreciated.</p>
1
Building Red-Black Tree from sorted array in linear time
<p>i know how to build it with n insertions ( each with O(log(n)) efficiency ) (n*log(n)) overall ,i also know that the equivalent structure of 2-3-4 tree can also be build with linear time from sorted array. can anyone please provide a simple explanation about the red-black version? </p>
1
How to display Oracle query output in Matrix/Pivot format
<p>I would like to display the output in Matrix/Pivot format of the following query.</p> <p><strong>Query :</strong></p> <pre><code>SELECT SUBSTR(mon, 4, 6) month, rmbs_cd, scdta, cl_nm, br_cd, brd_nm, prod, prod_nm, SUM(sale_net) sales FROM (SELECT LAST_DAY(x.deli_dt) mon, x.rmbs_cd, x.sc_cd || x.dist_cd || x.tha_cd || x.un_cd || x.cl_id scdta, INITCAP(cl_nm) cl_nm, a.br_cd, brd_nm, a.cat_cd || a.prd_cd prod, prod_nm, sale_cd, Nvl(sum(a.sale_net) - sum(rt_qty * flat_rt), 0) sale_net FROM bill_det a, bill_mas x, cl_info c, inv_brand d, inv_prod p WHERE (a.bill_no = x.bill_no AND a.sc_cd = x.sc_cd) AND x.fl_mvh IN ('1', '4') AND x.deli_dt BETWEEN '01-JUL-15' AND '31-DEC-15' AND a.br_cd = d.br_cd AND d.div_cd = '1' AND a.typ_cd || a.cat_cd || a.prd_cd = p.typ_cd || p.cat_cd || p.prd_cd AND p.typ_cd = '09' AND x.sc_cd = c.sc_cd (+) AND x.dist_cd = c.dist_cd (+) AND x.tha_cd = c.tha_cd (+) AND x.un_cd = c.un_cd (+) AND x.cl_id = c.cl_id (+) AND c.div_cd IN ('1', '4') AND sale_cd IN ('IM', 'IC', 'IN') AND cancl IS NULL GROUP BY LAST_DAY(x.deli_dt), x.rmbs_cd, x.sc_cd || x.dist_cd || x.tha_cd || x.un_cd || x.cl_id, cl_nm, a.br_cd, brd_nm, a.cat_cd || a.prd_cd, prod_nm, sale_cd ) GROUP BY SUBSTR(mon, 4, 6), rmbs_cd, scdta, cl_nm, br_cd, brd_nm, prod, prod_nm ORDER BY 1, 2, 3 </code></pre> <p><strong>Result :</strong></p> <p><a href="https://i.stack.imgur.com/5IS5x.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5IS5x.jpg" alt="mat" /></a></p> <p><strong>Expected Output :</strong></p> <p><a href="https://i.stack.imgur.com/qkW7k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qkW7k.jpg" alt="expected" /></a></p> <p>I would like to display each individual month in different vertical columns sequentially in Oracle.</p>
1
Running PowerShell commands from C#
<p>I have powershell script which connects to exchange online and performs tasks like creating shared mailboxes, calendars, adding licenses etc.</p> <p>The thing is that when I run those commands from C# class I get the error.</p> <p>This is my connection:</p> <pre><code> string schemaURI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; Uri connectTo = new Uri("https://outlook.office365.com/powershell-liveid/"); var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } this.credential = new PSCredential(login, securePassword); WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo, schemaURI, credential); connectionInfo.MaximumConnectionRedirectionCount = 5; connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; this.remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo); this.remoteRunspace.Open(); </code></pre> <p>This is my PowerShell which is working fine:</p> <pre><code> PowerShell powershell = PowerShell.Create(); powershell.Runspace = this.remoteRunspace; PSCommand command = new PSCommand(); command.AddCommand("new-mailbox"); command.AddParameter("Name", mailboxName); command.AddParameter("Shared"); command.AddParameter("PrimarySmtpAddress", formatedMailboxName); powershell.Commands = command; powershell.Invoke(); </code></pre> <p>And this is the code which is not working fine:</p> <pre><code> PowerShell powershell = PowerShell.Create(); powershell.Runspace = this.remoteRunspace; PSCommand command = new PSCommand(); command.AddCommand("Connect-MsolService"); command.AddCommand("Import-Module MSOnline"); command.AddParameter("Credential", this.credential); command.AddCommand("Set-MsolUser"); command.AddParameter("UserPrincipalName", userLogin); command.AddParameter("UsageLocation", "SE"); </code></pre> <p>The error I got is following:</p> <blockquote> <p>Additional information: The term 'Import-Module MSOnline' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.</p> </blockquote> <p>I tried various things like copy-paste dll's and changing active solution platform CPU to 64 bit and none of it helped me.</p>
1
How can I specify library dependencies using SystemJS?
<p>Using <a href="https://github.com/systemjs/systemjs" rel="noreferrer">SystemJS</a>, how do I specify that one library depends on another? For example, the <a href="http://getbootstrap.com/" rel="noreferrer">Bootstrap</a> JavaScript library depends on <a href="https://jquery.com/" rel="noreferrer">jQuery</a>. Based on the <a href="https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md#shim-dependencies" rel="noreferrer">SytemJS docs</a>, I assumed I would specify this dependency using <code>System.config.meta</code> property:</p> <pre><code>System.config({ baseUrl: './scripts', defaultJSExtensions: true, map: { jquery: './lib/jquery-2.2.0.min.js', bootstrap: './lib/bootstrap.min.js' }, meta: { bootstrap: { deps: ['jquery'] } } }); System.import('./scripts/app.js'); </code></pre> <p>But this seems to have no effect. When I run my application, the Bootstrap library throws a <code>Bootstrap's JavaScript requires jQuery</code> error - which means Bootstrap is being loaded before jQuery.</p> <p>How can I ensure that jQuery is always loaded before Bootstrap?</p>
1
Powershell Error initializing default drive: 'a call to SSPI failed see inner exception
<p>I have been using some powershell scripts to query active directory users and its very useful</p> <p>Recently the script stops working even though I have not changed it !</p> <p>I don't understand why. The prereqs etc. have not been altered</p> <p>The errors im getting include:</p> <p>"import-module: a local error has occurred .... { import-module $_ }...</p> <p>Error initializing default drive: 'a call to SSPI failed see inner exception...</p> <p>I am using windows 8 64 bit had all the pre reqs sorted e.g. RSAT tools, powershell option enabled. Dot net 4.5 etc. have enabled RSAT through add remove programs.</p> <p>I have tested the same script on another windows 7 machine and it works fine which makes it look like there is something awry on the windows 8 machine. I have googled about but haven't found a working solution.</p> <p>Ive checked to see if id unchecked anything that would upset powershell but don't see anything. Ive recreated my windows profile, I have reinstalled the RSAT tools for windows 8.1 64 bit. Ive re domained the machine.</p> <p>The active directory scripts were running fine then suddenly stopped. I haven't Installed any software recently. I'm a domain admin and can use active directory with the gui with no problems. I'm at a loss.</p> <p>Wondering if anyone knows what could have upset powershell on the windows 8 system or see anything ive overlooked</p> <p>Thanks for reading</p> <p>Confuseis</p>
1
How to set the volume via commandline on recent VLC versions?
<p>I've been trying, without success, to set the volume in VLC [2.2.1] via terminal, on Ubuntu.</p> <p>The parameter <code>--volume</code> doesn't exist anymore (<code>Warning: option --volume no longer exists</code>), and I can't find anything in the help which has "volume" in it.</p> <p>The documentation (<a href="https://wiki.videolan.org/Documentation:Advanced_Use_of_VLC/" rel="noreferrer">https://wiki.videolan.org/Documentation:Advanced_Use_of_VLC/</a>) is outdated, as it still has the <code>--volume</code> option in it.</p> <p>Is it still possible?</p>
1
SharedInstance in Swift
<p>Can anybody help me to convert this code into Swift?</p> <p>Here I mention <code>.h</code> and <code>.m</code> in Objective-C code.</p> <p><code>Abc</code> is a <code>UIViewController</code>. I want to perform this method in my Swift code. S how is possible?</p> <p><code>Abc.h</code></p> <pre><code>+ (Abc*)sharedInstance; - (void) startInView:(UIView *)view; - (void) stop; </code></pre> <p><code>Abc.m</code></p> <pre><code>static Abc*sharedInstance; + (Abc*)sharedInstance { @synchronized(self) { if (!sharedInstance) { sharedInstance = [[Abc alloc] init]; } return sharedInstance; } } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; } @end </code></pre>
1
How to move Eclipse.app under /Applications on MacOS?
<p>I used the fancy new installer to install Eclipse Mars on my OS X box and since it was asking for a folder and had a lot of fiddly config details to set, I wasn't sure what it was going to do to my system so I created a new folder ~/Applications/Eclipse/ to put it in.</p> <p>Fortunately it created an app package, Eclipse.app, so I wanted to move it into /Applications (out of my account folder into the common apps for all users of the box). So I dragged it (it's what you're supposed to be able to do, y'know).</p> <p>DOH! That did not work. It crashes and crashes and crashes. Moving it back makes it happy again.</p> <p>What would I need to do to move Eclipse.app, other than delete and reinstall and then reinstall all the plugins and SDKs I added?</p>
1
Common lisp :KEY parameter use
<p>The <code>:KEY</code> parameter is included in some functions that ship with Common Lisp. All of the descriptions that I have found of them are unhelpful, and <code>:KEY</code> is difficult to search in a search engine because the ":" is usually ignored.</p> <p>How would it be used, for example, in the <code>member</code> function which allows both <code>:TEST</code> and <code>:KEY</code>?</p>
1
How can I enable html rendering for TYPO3 7 tables?
<p>I am using TYPO3 7.6.2 and I can't use html inside the standard table element any more, because TYPO3 escape html tags inside the table element. Is there a specific RTE configuration which I have to enable or something else? My current RTE configuration looks like the following:</p> <pre><code>RTE.default { contentCSS = EXT:my_distribution/Resources/Public/Css/rte.css proc { allowedClasses := addToList(blue, button, caption, center, more, responsive, responsive2, subcaption, white) } showButtons := addToList(pastetoggle) buttons { blockstyle.tags.p.allowedClasses := addToList(caption, subcaption, white) blockstyle.tags.table.allowedClasses := addToList(responsive, responsive2) textstyle.tags.span.allowedClasses := addToList(blue, center, more, subcaption, white) link.properties.class.allowedClasses := addToList(button) pastetoggle.setActiveOnRteOpen = 1 } } </code></pre> <p>I don't want that an editor have to use plain html tables inside a text content element or a html content element.</p>
1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version etc
<p>I have a simple table having id(autoincrement) and name and i am trying to do a very simple insert query </p> <pre><code>if (connect != null) { query = new StringBuffer(""); query.append("INSERT INTO "); query.append("GROUP( "); query.append("GROUP_NAME "); query.append(") values ("); query.append("?)"); System.out.println(query.toString()); stmt = connect.prepareStatement(query.toString()); int i = 0; stmt.setString(1, group.getGroupName()); records = stmt.executeUpdate(); } </code></pre> <p>but it gives me an exception with stacktrace:</p> <blockquote> <p>2016-02-09T10:00:44.876+0500|Severe: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP( GROUP_NAME ) values ('Hockey')' at line 1</p> </blockquote> <p>I have searched about such problems but couldn't find a proper solution. </p>
1
how to normalize a numpy array in python
<p>I have the following numpy array:</p> <pre><code>from sklearn.decomposition import PCA from sklearn.preprocessing import normalize import numpy as np # Tracking 4 associate metrics # Open TA's, Open SR's, Open SE's associateMetrics = np.array([[111, 28, 21], [ 27, 17, 20], [ 79, 23, 17], [185, 125, 50], [155, 76, 32], [ 82, 24, 17], [127, 63, 33], [193, 91, 63], [107, 24, 17]]) </code></pre> <p>Now, I want to normalize every 'column' so that the values are between 0 and 1. What I mean is that the values in the 1st column for example should be between 0 and 1. </p> <p>How do i do this?</p> <pre><code>normed_matrix = normalize(associateMetrics, axis=1, norm='l1') </code></pre> <p>the above gives me rowwise normalization</p>
1
Create a List of unique values in java
<p>I have data of which the sequence is as important as its unique elements. Meaning if something has already been added it should not be added again and the sequence must be remembered.</p> <p>Set does not remember the sequence in which it was added (either hash or sort), and List is not unique.</p> <p>What is the best solution to this problem?</p> <p>Should one have a list and loop through it to test for uniqueness - which I'm trying to avoid? Or should one have two collections, one a List and one a Set - which I'm also trying to avoid? Or is there a different solution to this problem altogether.</p>
1
Lua - require fallback / error handling
<p>I'm currently using the <code>awesome</code> window manager on various Linux machines running different distributions. All of the machines utilize the same (<code>lua</code>) configuration file.</p> <p>Some of the machine have lua-filesystem (<code>lfs</code>) installed, while others don't. My configuration would preferably use <code>lfs</code>, but if it is not installed I'd like to provide an alternative (suboptimal) fallback routine.</p> <p>Here's my question in all of it's simplicity:</p> <ul> <li>How would I go about catching the error thrown by the <code>require(lfs)</code> statement?</li> </ul>
1
Ora-39000 bad dump file specification when exporting dump file using expdp
<p>I am trying to perform a windows scheduler job which will create back up of my database daily once. So for this reason I have created batch file <code>SYSTEM_BACKUP.bat</code> which contains data:</p> <pre><code>@echo off setlocal EnableDelayedExpansion expdp SYSTEM/SYSTEM@XE PARFILE=export_dump.par </code></pre> <p>The export_dump.par file contains information:</p> <pre><code>DIRECTORY=cron_jobs DUMPFILE=SYSTEM_!date:~10,4!!date:~6,2!.!date:~4,2!.dmp LOGFILE=SYSTEM.log SCHEMAS=B1,B2 CONTENT=ALL </code></pre> <p>When i trying to run the <code>SYSTEM_BACKUP.bat</code> I am getting error as </p> <pre><code> ORA-39001:invalid argument value, ORA-39000 bad dump file specification, ORA-39087:directory name ratormonitor_!date is invalid. </code></pre> <p>I am trying to create dump file with current datetimestamp attached to the file so the dump file name should look like this <code>SYSTEM_2015.02.03.37.029062831 but getting an error.</code></p>
1
How can I assign boost::filesystem::directory_entry::path() value to a string?
<p>I'm trying to write an algorithm that iterates recursively through a directory and compares each folder, sub-folder and file name to a user-defined regex object.</p> <p>I've found this piece of code for the iteration part:</p> <pre><code>path p(FilePath); for (directory_entry&amp; x : recursive_directory_iterator(p)) std::cout &lt;&lt; x.path() &lt;&lt; '\n'; </code></pre> <p>Where <em>Filepath</em> is the directory path defined by the user at runtime.</p> <p>It works great to print out paths on the console, but I can't figure out a way to use path() to do what I want, which would be to assign its value to a string and then compare that string to my regex object.</p> <p>I've been looking at other member function in boost::filesystem::directory_entry but I'm not really having any luck so far.</p> <p>Could anyone point me in the right direction?</p> <p>Thanks.</p> <p>EDIT:</p> <p>I'm dumb.</p>
1
Seek bar and media player and a time of a track
<p>In my media player (mp3) there is a seek bar. To play the next song i am using this logic:</p> <blockquote> <p>if (seek bar progress == mediaplayerObject.getDuration())</p> </blockquote> <p>if yes play the next song</p> <p>but this condition does not work, because there is a small mili second gap between the full seek bar progress and mediaplayerObject.getDuration() value that difference is not static it changes. I think it comes because of the processing time delays though. If I can use a condition like <code>if seek bar progress is 100%</code> I can use that, but I tried it does not seems working</p> <pre><code>import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; public class AndroidMediaPlayerExample extends Activity { private MediaPlayer mediaPlayer; public TextView songName, duration; private double timeElapsed = 0, finalTime = 0; private int forwardTime = 2000, backwardTime = 2000; private Handler durationHandler = new Handler(); private SeekBar seekbar; private Field[] fields; private String name; private int resourceID; private List&lt;String&gt; songNames; private int nameIntRandom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //set the layout of the Activity setContentView(R.layout.activity_main); songNames = new ArrayList(); //initialize views initializeViews(); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // seekBar.setMax(mediaPlayer.getDuration()); System.out.println("progress"+ (progress)); System.out.println("progress final - "+ finalTime); if(progress == finalTime){ System.out.println("progress 100 compleated "); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } public void initializeViews(){ listRaw(); songName = (TextView) findViewById(R.id.songName); nameIntRandom = Integer.parseInt(songNames.get(2)); mediaPlayer = MediaPlayer.create(this, nameIntRandom); finalTime = mediaPlayer.getDuration(); duration = (TextView) findViewById(R.id.songDuration); seekbar = (SeekBar) findViewById(R.id.seekBar); songName.setText("Sample_Song.mp3"); seekbar.setMax((int) finalTime); seekbar.setClickable(false); } // play mp3 song public void play(View view) { System.out.println("AndroidMediaPlayerExample play"); mediaPlayer.start(); timeElapsed = mediaPlayer.getCurrentPosition(); seekbar.setProgress((int) timeElapsed); durationHandler.postDelayed(updateSeekBarTime, 100); } //handler to change seekBarTime private Runnable updateSeekBarTime = new Runnable() { public void run() { //get current position timeElapsed = mediaPlayer.getCurrentPosition(); //set seekbar progress seekbar.setProgress((int) timeElapsed); //set time remaing double timeRemaining = finalTime - timeElapsed; duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining)))); //repeat yourself that again in 100 miliseconds durationHandler.postDelayed(this, 100); } }; // pause mp3 song public void pause(View view) { mediaPlayer.pause(); } // go forward at forwardTime seconds public void forward(View view) { //check if we can go forward at forwardTime seconds before song endes if ((timeElapsed + forwardTime) &lt;= finalTime) { timeElapsed = timeElapsed + forwardTime; //seek to the exact second of the track mediaPlayer.seekTo((int) timeElapsed); } } public void listRaw() { fields = R.raw.class.getFields(); for (int count = 0; count &lt; fields.length; count++) { Log.i("Raw Asset: ", fields[count].getName()); System.out.println("length .... " + fields[count].getName()); try { System.out.println("trytrytrytry"); resourceID = fields[count].getInt(fields[count]); System.out.println("resourceIDresourceID " + resourceID); name = String.valueOf(resourceID); songNames.add(name); System.out.println("songNames.size();" +songNames.size()); songNames.size(); } catch (IllegalAccessException e) { e.printStackTrace(); System.out.println("catch" + e); } } System.out.println("resourceIDresourceID---------lastone " + resourceID); System.out.println("resourceIDresourceID---------set " + fields.toString()); } // go backwards at backwardTime seconds public void rewind(View view) { //check if we can go back at backwardTime seconds after song starts if ((timeElapsed - backwardTime) &gt; 0) { timeElapsed = timeElapsed - backwardTime; //seek to the exact second of the track mediaPlayer.seekTo((int) timeElapsed); } } } </code></pre> <p>Currently mp3 arraylist id is hardcodeed </p> <p>XML here </p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:background="#333333" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" &gt; &lt;TextView android:id="@+id/songName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="songName" /&gt; &lt;ImageView android:id="@+id/mp3Image" android:layout_width="match_parent" android:layout_height="200dp" android:padding="30dp" android:src="@drawable/music" android:background="#ffffff" android:layout_margin="30dp" /&gt; &lt;TextView android:id="@+id/songDuration" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="songDuration" /&gt; &lt;SeekBar android:id="@+id/seekBar" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:orientation="horizontal" &gt; &lt;ImageButton android:id="@+id/media_rew" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="14dp" android:onClick="rewind" android:src="@android:drawable/ic_media_rew" /&gt; &lt;ImageButton android:id="@+id/media_pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="14dp" android:onClick="pause" android:src="@android:drawable/ic_media_pause" /&gt; &lt;ImageButton android:id="@+id/media_play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="14dp" android:onClick="play" android:src="@android:drawable/ic_media_play" /&gt; &lt;ImageButton android:id="@+id/media_ff" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="14dp" android:onClick="forward" android:src="@android:drawable/ic_media_ff" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
1
Use of undeclared type 'PHAsset' BSImagePicker
<p>I imported a module from CocoaPods inside swift. i did everythings as it needs to be done and it also works, because the module is succesfully imported. i now want to test some demo script of BSimagepicker but it says undeclared type : PHAsset. </p> <p>What i need to do is to select different images and load this into some sort of imagepicker preview inside the app. </p> <p>Someone can help to fix this error?</p> <pre><code>@IBOutlet var imageView: UIImageView! @IBOutlet weak var PicLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //startbsimpagepicker let vc = BSImagePickerViewController() bs_presentImagePickerController(vc, animated: true, select: { (asset: PHAsset) -&gt; Void in // User selected an asset. // Do something with it, start upload perhaps? }, deselect: { (asset: PHAsset) -&gt; Void in // User deselected an assets. // Do something, cancel upload? }, cancel: { (assets: PHAsset) -&gt; Void in // User cancelled. And this where the assets currently selected. }, finish: { (assets: [PHAsset]) -&gt; Void in // User finished with these assets }, completion: nil) //endbsimpagepicker </code></pre>
1
Bound attribute empty in an angular directive
<p>I've a simple directive </p> <pre><code>'use strict'; angular.module('ludaooApp') .directive('rating', function () { return { templateUrl: 'app/rating/rating.html', restrict: 'EA', link: function (scope, element, attrs) { scope.mark = attrs.mark; console.log(attrs); }; }) </code></pre> <p>This directive only log the attributes of the directive.</p> <p>Here is how I use that directive : </p> <pre><code>&lt;rating mark="{{game.rating}}" style="font-size: 30px"&gt;&lt;/rating&gt; </code></pre> <p>And here is the result of the web inspector : </p> <p><a href="https://i.stack.imgur.com/ZAken.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZAken.png" alt="enter image description here"></a></p> <p>As you can see, mark is empty <code>mark=""</code> on the first line. But after, it is filled in with its value <code>mark="4.16"</code>.</p> <p>The result is that if I <code>console.log(scope.mark)</code>, I see 0 instead of 4.16.</p> <p>I think it's because the 4.16 is retrieved from the database and, the code is executed before that <code>{{game.rating}}</code> is initialized in the controller. </p> <p>So the question is, how to deal with this problem ? And how to access to the "4.16" ? </p>
1