_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d19101
test
FirstDispositionNameOrDefault is for reading the values of form controls. You can use the [FromUri] attribute on the parameter: public HttpResponseMessage Photo([FromUri] int id) This tells Web API not to get the parameter from the message body.
unknown
d19102
test
Your computer doesn't have clairvoyant super powers and thus cannot reliably predict whether any observed WM_LBUTTONUP is or isn't followed up by any WM_LBUTTONDBLCLK message. What you could do is start a timer in your WM_LBUTTONDOWN message handler with a timeout of GetDoubleClickTime, and build up a complex state machine that moves between states on WM_TIMER, WM_LBUTTONUP, and WM_LBUTTONDBLCLK messages. That's doable, but a lot more complex than you'd expect. Plus, it will necessarily introduce a delay between the user releasing the left mouse button and the action they intended to trigger starting. What you should be doing instead is solving your UX issue. If you make your single click action unrelated to your double click action, then that is the bug that needs to be addressed. Logical consequences of the way Windows converts single-clicks into double-clicks goes into much more detail, and arrives at the same conclusion: Don't, just don't do it.
unknown
d19103
test
Why do you need to use jQuery at all? You can use this: .content-img:hover { -webkit-filter: grayscale(0%); filter: grayscale(0%); } Here, I made you this fiddle using css only, with :hover selector. But be careful, filter has limited support, look at filter article on MDN.
unknown
d19104
test
You need to move the creation of the relationship into a before block: context "when add a friend" do before do user.add_friend(other_user) end it "should put him in friend's list" do expect(user.friend? other_user).to be_truthy end it "should create a friendship" do expect(other_user.friend? user).to be_truthy end end In your code, you are only running it within the first it block, to the second one starts from scratch and it's not run. With the before block, it is run once before each of the it blocks, so the spec should pass then.
unknown
d19105
test
First get screen width Display mDisplay = activity.getWindowManager().getDefaultDisplay(); int width = mDisplay.getWidth(); int height = mDisplay.getHeight(); Set Size to Layout LinearLayout layout = (LinearLayout)findViewById(R.id.LayoutID); // Gets the layout params that will allow you to resize the layout LayoutParams params = layout.getLayoutParams(); // Changes the height and width to the specified *pixels* params.height = width; params.width = width; layout.setLayoutParams(params); In XML: <LinearLayout android:layout_width="0dp" android:layout_height="0dp" android:id="@+id/LayoutID" android:orientation="vertical" >
unknown
d19106
test
Im fine with: Template.registerHelper('repeat', function(max) { return _.range(max); // undescore.js but every range impl would work }); and {#each (repeat 10)}} <span>{{this}}</span> {{/each}} A: From http://docs.meteor.com/#/full/blaze_each: Constructs a View that renders contentFunc for each item in a sequence. So each must be used with a sequence (array,cursor), so you have to create a helper that create a sequence to use #each. Usually view is customized by item value, but in your case an array with max size will do the job. Or you can create a custom template helper where you can pass html to repeat and number of repetition and concat html in helper. Something like(code not tested): // Register helper htmlRepeater = function (html,n) { var out = ''; for(var i=0 ; i<n;i++) out.contat(html); return Spacebars.SafeString(out); }; Template.registerHelper('repeat', htmlRepeater); ------------------------ // in template.html {{{repeat '<li class="star">\u2605</li>' max}}} A: Simply return the required number of items from the underlying helper: html: {{> rating max=10 value=rating }} <template name="rating"> <ul class="rating"> {{#each myThings max}} <li class="star">\u2605</li> {{/each }} </ul> </template> Note that max needs to be passed through the html template to the {{#each}} js: Template.rating.helpers({ myThings: function(max){ // return an array 0...max-1 (as convenient as any other set of values for this example) return Array.apply(null, Array(max)).map(function (x, i) { return i; }); } }); Of course if you were iterating over a collection then you could just limit your .find() to max. I also notice your rating template isn't using the parameter value anywhere. Did you mean to do: <ul class = "{{value}}"> or was the value supposed to be substituted elsewhere?
unknown
d19107
test
Ok, I found out what the pb was... My hosting service (a french company : OVH) is caching static files and I have to ask them to stop it while I am working on the css. Sorry for bothering, it is not a joomla problem. A: Check the default template of your site and then go to: root_of_your_site/templates/default_template_named_folder/index.php and try to edit here, this will work. A: I had this problem too. spent hours trying to work it out. i solved it in the end.am sure someone else may do the same. i had checked JOOMLA cache was off, and my cache was cleared. In my situation i had forgotten i have set to domain up to use a CDN (cloudflare) This was caching the CSS files. so maybe check this and tick it off the list just in case. hope it helps someone
unknown
d19108
test
In Clean Architecture we would clearly separate between entities which are part of your domain model and request/response objects which are passed to/from the application logic. The request/response objects would be specific to some particular application logic (use case interactor) while the entities are representing "central business rules" which apply to all the use case interactors. For further explanation check out this article: http://www.plainionist.net/Implementing-Clean-Architecture-Controller-Presenter/ A: you will need to have an entity of a collection of entities that has the cursors in it for example message GamesList{ repeated Game games =1; string nextCursor =2; string previousCursor =3; } cause the entity you are dealing with on the domain layer is not just a list of games it's also the state of the list (offset, limit)
unknown
d19109
test
if you are searching for " How to fit a 3D text in a 3D object" I will explain how to do this, lets begin with the theory, Imagine having a flag with the form of the flag given sin(2*pi) if your camera is watching from y axis (three js axes) then you gonna add a text that exactly fits the function sin(2*pi), right? so, as you can see the idea of this is trying to get some tangets of sin(x) function, the secret of this is to cut the text in the number of tangents that will fit your text... for the text, "Montiel Software" it will be now ["Mon","tiel","Soft","Ware"] Flag: function flag(u,v,vector) { var x = 10*u; var y = 10*v; var z = Math.sin(2*Math.PI*u) ; vector.set(x,y,z);} Create the Geometry: var geometry_sin = new THREE.ParametricGeometry(flag, 100, 100); var material_sin = new THREE.MeshPhongMaterial({map:groundTexture,side:THREE.DoubleSide, color:0x000000} ); var flag = new THREE.Mesh( geometry_sin, material_sin ); Now add the text to flag (choose your tangents here) then the flag to scene: var loader = new THREE.FontLoader(); loader.load('js/examples/fonts/helvetiker_regular.typeface.json',function(font){ var geometry = new THREE.TextGeometry( 'Mon', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 0.2; txt_mesh.position.y = 5; txt_mesh.rotation.y = -Math.PI/8; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( 'tiel', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 1.2; txt_mesh.position.x = 2.5; txt_mesh.position.y = 5; txt_mesh.rotation.y = Math.PI/12; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( '$oft', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 0.28; txt_mesh.position.x = 4.5; txt_mesh.position.y = 5; txt_mesh.rotation.y = Math.PI/7; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( 'Ware', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = -1; txt_mesh.position.x = 7; txt_mesh.position.y = 5; txt_mesh.rotation.y = -Math.PI/8; flag.add(txt_mesh); } ); scene.add(flag); that's the only way I can imagine to do this in three JS, if you are just searching to make a 3D objet, I suggest you to install 3D builder and try options there then load the object to THREE js. A: Simply drawing the text to your 2D canvas will most likely never give you a satisfactory result. You have three possibilities to tackle this issue. * *Using textures loaded with a THREE.TextureLoader. * *several examples here: http://threejs.org/examples *tutorial: http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm *Using THREE.TextGeometry: * *an example: https://threejs.org/docs/index.html?q=textgeo#api/en/geometries/TextGeometry *Using a CSS3D solution. * *a nice blog post on this topic: http://learningthreejs.com/blog/2013/04/30/closing-the-gap-between-html-and-webgl/ Check also the UI example on the THREE.TextGeometry documentation page:
unknown
d19110
test
Add a .desktop file to one of the following directories: * *$XDG_CONFIG_DIRS/autostart/ (/etc/xdg/autostart/ by default) for all users *$XDG_CONFIG_HOME/autostart/ (~/.config/autostart/ by default) for a particular user See the FreeDesktop.org Desktop Application Autostart Specification for details. So for example, PrintWriter out = new PrintWriter(new FileWriter( System.getProperty("user.home")+"/.config/autostart/myapp.desktop")); out.println("[Desktop Entry]"); out.println("Name=myapp"); out.println("Comment=Autostart entry for myapp"); out.println("Exec=" + installPath + "/bin/myapp_wrapper.sh"); out.println("Icon=" + installPath + "/myapp_icon.png"); out.flush(); out.close();
unknown
d19111
test
left child = parent * 2 + 1 right child = parent * 2 + 2 I imagine this is homework so I will let you figure out the searching algorithm. A: To implement a binary tree as an array you put the left child for node i at 2*i+1 and the right child at 2*i+2. So for instance, having 6 nodes here's the indices of the corresponding array 0 | --------- | | ---1-- --2-- | | | | 3 4 5 6 A: I think you are looking for a heap. Or at least, you use a tree when an array structure is not enough for your needs so you can try to implement a tree inside an array but it wouldn't make much sense since every node contains references to its children without any need of indices. But an heap is an array that can also be seen as a binary tree, look it out here. It's a tree in the sense that it organizes data as a tree but without having direct references to the children, they can be inferred from the position.
unknown
d19112
test
Android and iOS both automatically pick up the ValueConverter names - the mechanism they do this by is described in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#referencing-value-converters-in-touch-and-droid Windows platforms don't do this by default - because Windows uses Xaml binding by default. If you want to add this use of named value converters, then you can do this using code in your Windows Setup.cs like: // call this in InitializeLastChance Mvx.CallbackWhenRegistered<IMvxValueConverterRegistry>(FillValueConverters); // add this method private FillValueConverters(IMvxValueConverterRegistry registry) { registry.Fill(ValueConverterAssemblies); } // add this property protected virtual List<Assembly> ValueConverterAssemblies { get { var toReturn = new List<Assembly>(); toReturn.AddRange(GetViewModelAssemblies()); toReturn.AddRange(GetViewAssemblies()); return toReturn; } }
unknown
d19113
test
Create a javascript function that performs an ajax call to a time function which can decide to set the stream or an image: <div id="stream-content"></div> setInterval(function() { $.ajax({ url : "/gettime.php", type: 'GET', success: function(data){ //check time, if correct, set video to the div #stream-content otherwise, set an image as the content } }); }, 1000);
unknown
d19114
test
It's not exactly the topic but I needed to find the roles associated with a specific user and this question pops first with my keywords web search. Here's what worked for me with keycloak client 13.0.1 RealmResource realmResource = keycloak.realm(REALM); UsersResource usersResource = realmResource.users(); UserResource userResource = usersResource.get(USER_ID); RoleMappingResource roleMappingResource = userResource.roles(); // either realmLevel or clientLevel RoleScopeResource roleScopeResource = roleMappingResource.realmLevel(); List<RoleRepresentation> rolesRepresentation = roleScopeResource.listAll(); I didn't find it elsewhere, I hope it can be useful.
unknown
d19115
test
Explanation is provided over here: https://stackoverflow.com/a/65082868/7225290 No error will be thrown if you are comparing value at particular index with the value(having same datatype). It occurs when you try to do array = numpy.array([(0,0,0,0), (0,0,0,0), (0,0,0,0)]) if array:#Comparing object of type numpy.ndarray with boolean causes the error pass
unknown
d19116
test
*argv[i+1] Accesses the 1st char of the char* argv[] argument. To get the whole value use something like std::string filename(argv[i+1]); instead. A: You can't store a string in a single char. Here's the once-an-idiom for copying the main arguments to more manageable objects: #include <string> #include <vector> using namespace std; void foo( vector<string> const& args ) { // Whatever (void) args; } auto main( int n, char* raw_args[] ) -> int { vector<string> const args{ raw_args, raw_args + n }; foo( args ); } Do note that this code relies on an assumption that the encoding used for the main arguments can represent the actual command line arguments. That assumption holds in Unix-land, but not in Windows. In Windows, if you want to deal with non-ASCII text in command line arguments, you'd better use a third party solution or roll your own, e.g. using Windows' GetCommandLine API function.
unknown
d19117
test
Use display:inline-block instead of float:left on your .item-component Living Demo .item-component { width: 33.33333333333333%; display: inline-block; padding-left: 15px; } Or, you can take a look at BootStrap and do it by using the :before element maintaning the float:left as you had it before. You would also need to wrap each row: .col{ float:left; width: 32.33%; min-height: 50px; background: #ccc; padding: 20px; box-sizing: border-box; } .row{ display:block; } /* This do the trick */ .row:before{ content: " "; display: table; box-sizing: border-box; clear: both; } Living example Update If you don't want the gap you will have to look for another HTML markup. You will have to print first each column with each rows. This is the needed html markup: <div class="col"> <div class="row" id="demo">1</div> <div class="row">4</div> <div class="row">7</div> </div> <div class="col"> <div class="row">2</div> <div class="row">5</div> <div class="row">8</div> </div> <div class="col"> <div class="row">3</div> <div class="row">6</div> <div class="row">9</div> </div> And the needed css: .col{ float:left; width: 32.33%; } .row{ display:block; padding: 20px; box-sizing: border-box; background: #ccc; min-height: 50px; } #demo{ height: 150px; background: red; } Living demo A: You can do it in the following way. HTML: <div class="container"> <div class="col">1</div> <div class="col">2</div> <div class="col">3</div> <br class="clear" /> <div class="col">4</div> <div class="col">5</div> <div class="col">6</div> <br class="clear" /> <div class="col">7</div> <div class="col">8</div> <div class="col">9</div> <div> CSS: .col { float: left; width: 100px; min-height: 100px; background: #ccc; padding: 20px; margin: 10px; cursor: pointer; } .col:hover { background: yellow; } JS: $('.col').click(function() { if ($(this).is('.clicked')) { $(this).removeClass('clicked'); } else { $(this).addClass('clicked') } }); Live demo: http://jsfiddle.net/S7r3D/1/ ETA: the problem with this solution is that it moves entire row down. I don't really see how to nicely achieve what you want...You could try to overflow the other divs, but it depends on your needs. Is such solution acceptable? ETA2: actually I made it perfect I think! Have a look here: http://jsfiddle.net/S7r3D/3/ The crucial change was rearranging divs and putting them in columns instead. HTML: <div class="container"> <div class="fleft"> <div class="col">1</div> <div class="col">4</div> <div class="col">7</div> </div> <div class="fleft"> <div class="col">2</div> <div class="col">5</div> <div class="col">8</div> </div> <div class="fleft"> <div class="col">3</div> <div class="col">6</div> <div class="col">9</div> </div> <div> CSS: .col { clear: both; width: 100px; min-height: 100px; background: #ccc; padding: 20px; margin: 10px; cursor: pointer; } .col:hover { background: yellow; } .col.clicked { height: 300px; background-color: red; } .fleft { float: left; } JS: /* same as above */ A: Create three container divs, and afterwards, put {1, 4, 7} into div1, {2, 5, 8} into div2, and {3, 6, 9} into div3. Otherwise you will have it very difficult to control their positioning.
unknown
d19118
test
You want to use the BulletDecorator as part of the ToolTip. Example: <ToolTip> <BulletDecorator> <BulletDecorator.Bullet> <Ellipse Height="10" Width="10" Fill="Blue"/> </BulletDecorator.Bullet> <TextBlock>Text with a bullet!</TextBlock> </BulletDecorator> </ToolTip> For more information, see http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.bulletdecorator(v=vs.100).aspx A: you must have a custom tooltip for this a nice blog example http://stevenhollidge.blogspot.co.il/2012/04/custom-tooltip-and-popup.html microsoft info http://msdn.microsoft.com/en-us/library/ms745107.aspx just put somekind of rich textbox or listbox in the content... A: Just a guess: Why don't use unicode characters (0x2981 for example) and \r\n for lie breaks? A: I got it displaying correctly with the following: <ListView x:Name="listView" Margin="0,-5,0,0" BackgroundColor="Transparent" HasUnevenRows="True" HeightRequest="50" HorizontalOptions="CenterAndExpand" ItemsSource="{Binding TradingHoursList}" SeparatorColor="Transparent"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <RelativeLayout> <Label Text="&#x2022;"/> <Label Margin="10,0,0,0" FontAttributes="Italic" FontFamily="Arial Black" FontSize="15" HorizontalOptions="Start" Text="{Binding}" VerticalOptions="Start"/> </RelativeLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
unknown
d19119
test
<div> <p v-if="showName">My name is Simon</p> </div> You should open a p tag under the div tag
unknown
d19120
test
$('#idOfYourDialog').dialog('widget').position(); use the 'widget' flag to get the ui-dialog (the div that is your dialog) to get it' parameters. As for the dialog drag-stop - are you binding in the init or through bind? Can you post a code sample? A: Hmmm... I have this ajax function that calls content from the server. That might be the problem. I have it like: $.ajax({ url: href, success: function(data) { if(handleAjaxErrors(data)==false) { openWindowsCount++; $(data).dialog({
unknown
d19121
test
This looks like a classic SQL injection problem. What if the description contains a single apostrophe i.e. "Wasn't available", this will break your code. In addition, if Student is an integer value (i.e. it is an integer/auto-incrementing ID or equivalent in your DB) it should not be wrapped in quotes, giving you - DataRow[] foundRow = dt.Select("Student=" + Student.ID + " AND [Student Description]='" + Student.AbsenceDescription.Trim() + "'");
unknown
d19122
test
To download something that requires authentication, I do public InputStream openStream(URL url, String user, String password) throws IOException { if (user != null) { Authenticator.setDefault(new MyAuthenticator(user, password)); } URLConnection connection = url.openConnection(); return connection.getInputStream(); } A more up to date answer since Java 11 would be to use the HttpClient and it's Builder. In there you can directly set the authenticator.
unknown
d19123
test
could be the SabreCommandLLSRQ which can be used to use host commands but using soap.
unknown
d19124
test
You are doing a lot of: Upload.bindEvents(); You need to unbind events for those 'li's before you bind them again. Otherwise, you add more click events. That's why you are seeing more and more clicks being fired. A: From what I see, you are trying to attach/remove event handlers based on what the user selects. This is inefficient and prone to errors. In your case, you are calling Upload.bindEvents() each time a photo is added, without cleaning all the previous handlers. You could probably debug until you don't leak event listeners anymore, but it's not worth it. jQuery.on is very powerful and allows you to attach handlers to elements that are not yet in the DOM. You should be able to do something like this: init: function ( config ) { this.config = config; this.counter = 1; this.config.photoContainer.on('change', 'li > input[name=images]', this.photoAdded); this.config.photoContainer.on('click', 'li > p > a.removePhoto', this.removePhoto); }, You attach just one handler to photoContainer, which will catch all events bubbling up from the children, regardless of when they were added. If you want to disable the handler on one of the elements, you just need to remove the removePhoto class (so that it doesn't match the filter).
unknown
d19125
test
Support for Visual Studio 2019 has been added to Unreal Engine 4.22: Release Notes. After updating to Unreal Engine 4.22 or newer, ensure that you have set the Source Code Editor to Visual Studio 2019 in the Editor Preferences. Additionally, if you have created your project with an earlier version of Visual Studio, you have to regenerate your project files: right click your .uproject file and click Generate Visual Studio project files.
unknown
d19126
test
It seems unlikely, but certainly not impossible, that your Windows 8 machine has only IPv6 addresses. However, it is not uncommon to turn off IPv6 support on network adapters for any OS as it is not commonly supported yet. Check the adapters for each computer to verify the addresses and compare to your result. Regardless, you would be advised to assume that your query will return multiple addresses of type IPv6, IPv4 and more with multiples of any type as well. If you are looking for specific types then use the AddressFamily property to identify type. For example, for IPv4 only: Dim hostEntry = Dns.GetHostEntry(hostNameOrAddress) Dim addressList As New List(Of IPAddress) For Each address In hostEntry.AddressList If address.AddressFamily = Sockets.AddressFamily.InterNetwork Then addressList.Add(address) End If Next Return addressList A: You can use this: System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName).AddressList.First.ToString() A: You can use LINQ to filter the results: Dim ipHostEntry = Dns.GetHostEntry(Dns.GetHostName) Dim ipAddress = ipHostEntry.AddressList.FirstOrDefault(Function(ip) ip.AddressFamily = AddressFamily.InterNetwork) If ipAdress IsNot Nothing Then ' Output ipAdress.ToString() Else ' No IPv4 address could be retrieved End If Explanation: IPHostAddress.AddressList returns an Array(Of IPAddress) which implements the IEnumerable interface and can therefore be enumerated by LINQ expressions. FirstOrDefault will return the first element from the AddressList array that matched the predicate lambda function that is submitted as first and only parameter of FirstOrDefault. The predicate function has to be written to return a boolean. The array is iterated from the first to the last element, and for each element the lambda function is evaluated, where its parameter ip is the current iteration item. With ip.AddressFamily = AddressFamily.InterNetwork we determine whether the current item is an IPv4 address. If so, the expression evaluates true and the item is returned by FirstOrDefault. If it evaluates to false, the next item from the array is checked and so on. If no element matches the predicate, FirstOrDefault returns the default value, in this case Nothing (N. B.: the extension First works the same way but throws an exception if no item matches the predicate; both First and FirstOrDefault can be called without any arguments, they return the first element of the sequence then). I prefer the extension methods based notation as above, but you can use the original From In Where Select LINQ notation as well if you prefer: Dim ipAddress = (From ip In ipHostEntry.AddressList Where ip.AddressFamily = AddressFamily.InterNetwork Select ip)(0) Note that (0) is the argument for another extension method ElementAtOrDefault(index As Integer) in this case. A: Public Function GetIPv4Address() GetIPv4Address = String.Empty Dim strmachine As String = System.Net.Dns.GetHostName() Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strmachine) For Each ipheal As System.Net.IPAddress In iphe.AddressList If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then GetIPv4Address = ipheal ' MsgBox(ipheal.ToString, MsgBoxStyle.Critical, "ERROR") End If Next End Function
unknown
d19127
test
It seems fixed on Amazon side, there is no more apt-get install failling on Amazon for me, even on load-balanced :)
unknown
d19128
test
echo %Loc% > C:\PLACE\LOCFILE.txt ↑ This space is written to the file. Fix: echo %Loc%> C:\PLACE\LOCFILE.txt A: This is more robust. >"C:\PLACE\LOCFILE.txt" echo(%Loc% The redirection at the starts stops numbers like 3,4,5 in %loc% from breaking your code when redirection is directly at the end (such as shown below). When using the technique below then constructs like test 2 in %loc% will also fail. This is because single digit numbers at the end are interpreted as stream designators, so numerals 0 to 9 are all problems when placed directly before a redirection character (> or >>). do not use this: echo %Loc%> C:\PLACE\LOCFILE.txt Extra tips: The echo( protects from other failures in the echo command and the ( character has been tested as the least problematic character when used in this way. The double quotes around the "drive:\path\filename" also protect against long filename elements such as spaces, as well as the & character.
unknown
d19129
test
In your btnClick function, you can set the Stretch parameter for each item in self.btnLayout. In this case you want to set the Stretch for the spacer on the left to 0 and the right spacer to 1: def btnClick(self, check=False): print('click') # align button left self.btnLayout.setStretch(0,0) self.btnLayout.setStretch(1,1) self.btnLayout.setStretch(2,1) pass For centering the button, set left and right spacers stretch to 1: # button is centered self.btnLayout.setStretch(0,1) self.btnLayout.setStretch(1,1) self.btnLayout.setStretch(2,1) And to align button on right, set left spacer to 1, right spacer to zero: # align button right self.btnLayout.setStretch(0,1) self.btnLayout.setStretch(1,1) self.btnLayout.setStretch(2,0)
unknown
d19130
test
If you can base64 serialize the data, then seems like you should be able to use this component to send data to your Webview. Not sure how performant it would be though. https://github.com/R1ZZU/react-native-webview-messaging
unknown
d19131
test
Solution found: const networkInterface = createNetworkInterface('http://localhost:8080/graphql'); this.client = new ApolloClient({ networkInterface, dataIdFromObject: r => r.id } ); dataIdFromObject is the one thing i am missing during the Apolloclient initiation dataIdFromObject (Object) => string A function that returns a object identifier given a particular result object. it will give unique ID for all result object.
unknown
d19132
test
Won't bash && <path_to_sh_file> enter a bash shell, successfully exit it, then try to run your sh file in a new shell? I think it would be better to put #! /usr/bin/bash as the top line of your sh file, and be sure the sh file has executable permissions chmod a+x <path_to_sh_file>
unknown
d19133
test
Sure take a look at documentation: http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest primaryBackendIpAddress A guest's primary private IP address. Type: string primaryIpAddress The guest's primary public IP address. Type: string if you do not see any value for any of those properties that means that the virtual guest does not have it. Regards
unknown
d19134
test
Why The Original Code Broke When you put ${array[@]} in a context that can only ever evaluate to a single string, it acts just like ${array[*]}. This is what your "working" code was doing (and why it wouldn't keep looking like it was working if your array values had spaces in their values or were otherwise at all interesting). When you put ${array[@]} in a context that evaluates to multiple words (like a command), it generates breaks between words at every boundary between the individual array items. Thus, your string starting with for_each was split up into several different arguments, rather than passing the entire array's contents at once; so the redirection was no longer present in do_cmd's $3 at all. How To Do This Well Starting with some general points: * *Array contents are data. Data is not parsed as syntax (unless you use eval, and that opens a can of worms that the whole purpose of using arrays in bash is to avoid). *Flattening your array into a string (string=${array[@]}) defeats all the benefits that might lead you to use an array in the first place; it behaves exactly like string=${array[*]}, destroying the original item boundaries. *To safely inject data into an evaled context, it needs to be escaped with bash 5.0's ${var@Q}, or older versions' printf %q; there's a lot of care that needs to be taken to do that correctly, and it's much easier to analyze code for correctness/safety if one doesn't even try. (To expand a full array of items into a single string with eval-safe escaping for all in bash 5.0+, one uses ${var[*]@Q}). Don't do any of that; the primitives you're trying to build can be accomplished without eval, without squashing arrays to strings, without blurring the boundary between data and syntax. To provide a concrete example: appending_output_to() { local appending_output_to__dest=$1; shift "$@" >>"$appending_output_to__dest" } for_each() { local -n for_each__source=$1; shift local for_each__elem for for_each__elem in "${for_each__source[@]}"; do "$@" "$for_each__elem" done } cmd=( redirecting_to "$log_file" func ) array=( item1 item2 item3 ) for_each array "${cmd[@]}" (The long variable names are to prevent conflicting with names used by the functions being wrapped; even a local is not quite without side effects when a function called from the function declaring the local is trying to reuse the same name).
unknown
d19135
test
the reason behind my issue was due to using a custom build of ngCordova. if i just the normal or Minified version of ngcordova it works perfectly. Thanks for all the help.
unknown
d19136
test
I found it! It was hidden in some file at /home/wegener/.gemrc ... I have no clue why it was set to wegejos or where that even came from.. there is not even a /home/wegejos/ I changed it to /home/wegener/ and now it's working.
unknown
d19137
test
This code: $this->loadModel($id)->okunma=1; $this->render('view',array( 'model'=>$this->loadModel($id), )); retrieves the model (object), changes the okunma property and throws it away (because the return value of loadModel() call is not being stored anywhere) and the other loadModel() call simply retrieves the model again. I think what you meant was: $model = $this->loadModel($id); $model->okunma=1; $this->render('view',array( 'model' => $model, )); this way the retrieved object is stored in a variable, allowing you to modify it and pass it to render() once modified. And if you want this change to propagate to database as well, you need to save() the model: $model = $this->loadModel($id); $model->okunma=1; $model->save(); A: You shouldn't perform update operation in views. I think you want to set model attribute and show this on view - then solution presented by @Liho is correct. If you want to save data to DB, you should assing $_POST attributes to your model: $model = $this->loadModel($id); $model->okunma=1; if(isset($_POST['yourModelName')) { $model->attributes = $_POST['yourModelName']); if($model->validate()) { $model->save(false); // other operations, eg. redirect } } $this->render('view',array( 'model' => $model, )); A: $model = YourModel::model()->findByPk($id); $model->okunma=1; $model->save(false); $this->render('view',array( 'model' => $model, ));
unknown
d19138
test
If there's no missprint - there's some dependencies missing. Create isolated virtualenv and install django and djangorestframework (maybe that's the problem you typed pip install django_rest_framework instead of djangorestframework).
unknown
d19139
test
Your idea is fine. What's wrong with what you had in your question at the bottom? M = reshape(T, [d1*d2 d3]); This would unroll each 2D slice in your 3D tensor into a single column and stack all of the columns together into a 2D matrix. I don't see where your problem lies, other than the fact that you didn't multiply d1 and d2 together. In general, you would want to do this, given T: M = reshape(T, [size(T,1)*size(T,2) size(T,3)]); Or, you can let MATLAB infer the amount of columns by doing: M = reshape(T, size(T,1)*size(T,2), []); To address your other question, to go back from the converted 2D matrix into its original 3D tensor, just do: T2 = reshape(M, d1, d2, d3); In our case, this would be: T2 = reshape(M, size(T,1), size(T,2), size(T,3)); Bear in mind that you must be cognizant of the original dimensions of T before doing this. Remember, reshape works by going over column by column and reshaping the matrix to whatever dimensions you see fit. This will now take each column and convert it back into a 2D slice, then do this for all columns until you get your original 3D matrix back. To illustrate going back and forth, suppose we have this matrix T: >> T = randi(10,3,3,3) T(:,:,1) = 9 10 3 10 7 6 2 1 10 T(:,:,2) = 10 10 2 2 5 5 10 9 10 T(:,:,3) = 8 1 7 10 9 8 7 10 8 To get our unrolled slices so that they fit into columns, use the first line of code above and you you should get a 9 x 3 matrix: >> M = reshape(T, size(T,1)*size(T,2), []) M = 9 10 8 10 2 10 2 10 7 10 10 1 7 5 9 1 9 10 3 2 7 6 5 8 10 10 8 As you can see, each column is a slice from the 3D tensor unrolled into a single vector. Each column takes every column of a slice and stacks them on top of each other to get a single column. To go backwards: >> T2 = reshape(M, size(T,1), size(T,2), size(T,3)) T2(:,:,1) = 9 10 3 10 7 6 2 1 10 T2(:,:,2) = 10 10 2 2 5 5 10 9 10 T2(:,:,3) = 8 1 7 10 9 8 7 10 8 As you can see, both T and T2 are the same.
unknown
d19140
test
By convention classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface. You need to annotate CREATOR property with @JvmField annotation to expose it as a public static field in containing data class. Also you can take a look at https://github.com/grandstaish/paperparcel — an annotation processor that automatically generates type-safe Parcelable wrappers for Kotlin and Java. A: In Kotlin, an interface can have a companion object but it is not part of the contract that must be implemented by classes that implement the interface. It is just an object associated to the interface that has one singleton instance. So it is a place you can store things, but doesn't mean anything to the implementation class. You can however, have an interface that is implemented by a companion object of a class. Maybe you want something more like this: interface Behavior { fun makeName(): String } data class MyData(val data: String) { companion object: Behavior { // interface used here override fun makeName(): String = "Fred" } } Note that the data class does not implement the interface, but its companion object does. A companion object on an interface would be useful for storing constants or helper functions related to the interface, such as: interface Redirector { fun redirectView(newView: String, redirectCode: Int) companion object { val REDIRECT_WITH_FOCUS = 5 val REDIRECT_SILENT = 1 } } // which then can be accessed as: val code = Redirector.REDIRECT_WITH_FOCUS
unknown
d19141
test
You have to decode it on the server using $applications = json_decode($this->input->post('applicants'), true); So, it'll become an associative array and you can use it like an array, without the second argument (true) in json_decode the json will be converted to an object. Until you decode it, it's only a string (json/java script object notation string). Update: Since it's already an array of objects then you don't need to use json_decode, just loop the array in your view like foreach($applicants as $item) { echo $item->firstname . '<br />'; echo $item->lastname . '<br />'; // ... } According to the edit 2 it should be access as an array echo $item['firstname'] . '<br />' A: try this plz $applicants = $this->input->post('applicants'); $json_output = json_decode($applicants ); foreach ( $json_output as $person) { $this->output->append_output("<br/>Here: " . $person->firstname ); } or $json_output = json_decode($applicants,TRUE ); echo $json_output[0][firstname] ;
unknown
d19142
test
We had the same problem. FF does not report correct image sizes if src is empty. Try and set src to a valid image to see if it works. In our project we use ng-src; not src. We created a mock of ng-src that kicks-in in all our tests. The mock replaces the ng-src value (empty or not) with a single fake image stored in /tests/image. This is useful if you unit test directives that include images in their html template. See also How do you mock directives to enable unit testing of higher level directive?
unknown
d19143
test
For those who struggle with this issue in Windows, Follow the instruction here A: When creating a Hyper-v VM using docker-machine on win10, an error was returned"Error with pre-create check: "Hyper-V PowerShell Module is not available"。 The solution is very simple. The reason is the version of the docker-machine program. Replace it with v0.13.0. The detailed operation is as follows: * *Download the 0.13.0 version of the docker-machine command. Click to download: 32-bit system or 64-bit system *After the download is complete, rename and replace the " docker-machine.exe " file in the " C:\Program Files\Docker\Docker\resources\bin" directory. It is best to back up the original file. A: Here is the solution https://github.com/docker/machine/releases/download/v0.15.0/docker-machine-Windows-x86_64.exe Save the downloaded file to your existing directory containing docker-machine.exe. For my system this is the location for docker-machine.exe /c/Program Files/Docker/Docker/Resources/bin/docker-machine.exe Backup the old file and replace it file with the new one. cp docker-machine.exe docker-machine.014.exe Rename the downloaded filename to docker-machine.exe mv docker-machine-Windows-x86_64.exe docker-machine.exe Build Instructions * *Create virtual switch in Hyper-V manager named myswitch *Request Docker to create a VM named myvm1 docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 Results docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 Running pre-create checks... (myvm1) Image cache directory does not exist, creating it at C:\Users\Trey Brister\.docker\machine\cache... (myvm1) No default Boot2Docker ISO found locally, downloading the latest release... (myvm1) Latest release for github.com/boot2docker/boot2docker is v18.05.0-ce (myvm1) Downloading C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v18.05.0-ce/boot2docker.iso... (myvm1) 0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100% Creating machine... (myvm1) Copying C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso to C:\Users\Trey Brister\.docker\machine\machines\myvm1\boot2docker.iso... (myvm1) Creating SSH key... (myvm1) Creating VM... (myvm1) Using switch "myswitch" (myvm1) Creating VHD (myvm1) Starting VM... (myvm1) Waiting for host to start... Waiting for machine to be running, this may take a few minutes... Detecting operating system of created instance... Waiting for SSH to be available... Detecting the provisioner... Provisioning with boot2docker... Copying certs to the local machine directory... Copying certs to the remote machine... Setting Docker configuration on the remote daemon... Checking connection to Docker... Docker is up and running! To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\Docker\Docker\Resources\bin\docker-machine.exe env myvm1 A: (1), V0.15 fixed this issue officially: Fix issue #4424 - Pre-create check: "Hyper-V PowerShell Module is not available" Official Introduction: https://github.com/docker/machine/pull/4426 Address to donload V0.15 https://github.com/docker/machine/releases (2), I tested this, it works fine. No need restart docker It take effect immdiately after the "docker-machine.exe" is replaced with version 0.15 (3), Backup the original one is a good habit A: Just start docker desktop if you are on Windows
unknown
d19144
test
You can use PhotoCamera class for this. This MSDN page clearly explains how to stream and capture images using camera The code given below shows how to initialize PhotoCamera PhotoCamera myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary); //viewfinderBrush is a videobrush object declared in xaml viewfinderBrush.SetSource(myCamera); myCamera.Initialized += myCamera_Initialized; myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted); myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
unknown
d19145
test
Maximum id value of Member model: use app\models\Member; // ... echo Member::find()->max('id');
unknown
d19146
test
Your individual posts will probably have a class or id on them - if not you need to add one. For example my site uses this: <div class="post"> <!-- post content --> </div> in the CSS for that class then add: .post img { width: 100%; } Note that this is a quick solution giving you exactly what you asked for. The images probably won't look very good in the posts unless you control your images i.e. only post images that are the same pixel width or larger than the column in which they appear on the site. Additionally this CSS will target ALL IMAGES in that post, which is fine if your posts are just text and the images you upload. A: Maybe you should try this - content width
unknown
d19147
test
The problem is that you create an array of size MAX(a) with a the list of your n numbers. This is inefficient if MAX(a) = 10^5 for example. You should find another way to check if a number A is multiple of number B, for example A%B == 0 (use of modulo). Try to remove countSieve and changed countMultiples. def countMultiples(query, numbers): count = 0 for i in numbers: if i%query == 0: count += 1 return count n=int(input()) numbers = [] for i in range(n): j=int(input()) numbers.append(j) q=int(input()) queries = [] for i in range(q): c=int(input()) queries.append(c) for i in queries: print(countMultiples(i, numbers)) EDIT : Here is an optimization. First I search for numbers divisors, for each divisor I increment a counter in a dict d, then for a query q I print d[q], which is the exact amount of multiples present in the n numbers. The method to search divisors of a number n : I make a loop until the square root of n, then for each divisor i, I also add r = n//i. I also use a dict divs to store divisors for each number n, in order not to re-calculate them if I already found them. Try this (it succeeded the problem https://hack.codingblocks.com/app/dcb/938) : import math d = {} divs = {} for _ in range(int(input())): num = int(input()) if num in divs: for e in divs[num]: d[e] = d.get(e, 0) + 1 else: div_list = [] for i in range(1, math.floor(math.sqrt(num)) + 1): if not num % i: div_list.append(i) d[i] = d.get(i, 0) + 1 r = num // i if (not num % r and r != i): div_list.append(r) d[r] = d.get(r, 0) + 1 divs[num] = div_list for i in range(int(input())): q = int(input()) print(d.get(q, 0)) A: Alternatively, you could try counting how often each number appears and then checking the counts for each multiple of k up to the largest of the N numbers. import collections n = int(input()) nums = [int(input()) for _ in range(n)] counts = collections.Counter(nums) m = max(nums) q = int(input()) for _ in range(q): k = int(input()) x = sum(counts[i] for i in range(k, m+1, k)) print(x) At first sign, this does not look much different than the other approaches, and I think this even still has O(N*Q) in theory, but for large values of Q this should give quite a boost. Let's say Q = 100,000. For all K > 10 (i.e. all except 10 values for K) you will only have to check at most 10,000 multiples (since m <= 100,000). For all K > 10,000 (i.e. 90% of possible values) you only have to check at most 10 multiples, and for 50% of Ks only K itself! I other words, unless there's an error in my logic, in the worst case of N = Q = 100,000, you only have about 1,1 million check instead of 10,000,000,000. >>> N = Q = 100000 >>> sum(N//k for k in range(1,Q+1)) 1166750 (This assumes that all K are different, but if not, you can cache the results in a dict and then will only need a single check for the duplicates, too.) On closer inspection, this approach is in fact pretty similar to what your sieve does, just a bit more compact and computing the values for each k as needed instead of all at once. I did some timing analysis using random inputs using gen_input(n, q, max_k). First, all the algorithms seem to produce the same results. For small-ish input sizes, there is no dramatic difference in speed (except for naive modulo), and your original sieve is indeed the fastest. For larger inputs (maximal values), yours is still the fastest (even by a larger margin), and the divisors approach is considerably slower. >>> n, q = gen_input(10000, 1000, 1000) >>> modulo(n, q) == mine(n, q) == sieve(n, q) == modulo(n, q) True >>> %timeit modulo(n, q) 1 loop, best of 3: 694 ms per loop >>> %timeit mine(n, q) 10 loops, best of 3: 160 ms per loop >>> %timeit sieve(n, q) 10 loops, best of 3: 112 ms per loop >>> %timeit divisors(n, q) 1 loop, best of 3: 180 ms per loop >>> n, q = gen_input(100000, 100000, 100000) >>> %timeit mine(n, q) 1 loop, best of 3: 313 ms per loop >>> %timeit sieve(n, q) 10 loops, best of 3: 131 ms per loop >>> %timeit divisors(n, q) 1 loop, best of 3: 1.36 s per loop Not sure why you are getting timeouts for yours and mine algorithm while @phoenixo's divisors allegedly works (did not try it, though)...
unknown
d19148
test
I encountered the same problem and was not able to get a comma as the decimal separator with <input type="number"> even when setting the language to a different locale and using a step smaller than 1: <input type="number" step="0.01" lang="en-US"> So I opted for a custom solution based on <input type="text"> with a custom filtering mechanism to only allow numbers in. See this stackblitz for a complete demo. The most important part is filtering what the user inputs in the field. I suggest you write a directive that listens to input/keydown/paste events and that uses a regex to only allow float/integer numbers. The following regex (/^-?\d*(,|\.)?\d*$/) allows a number to begin with an optional - followed by digits, then a comma or dot and more digits. If the new value (current value + key pressed) does not match the regex, simply prevent the event from happening with event.preventDefault(). Otherwise, do nothing and let the value go to the input. Note that you also have to take care of the copy/cut/paste/undo/redo special keys. And also take into account the cursor position and the selection if any. Once the filtering is done, you can implement the ControlValueAccessor interface and bind it to your input via its change/input events. Do the string to number conversions in these handlers and do the number to string conversion in a getter or a pipe that you bind to the value attribute. Here is an example of such a directive, you could generalize it by giving the regex as an input parameter. import { Directive, Input, HostListener, forwardRef } from '@angular/core'; @Directive({ selector: '[appNumberOnly]' }) export class NumberOnlyDirective { @HostListener('keydown', ['$event']) public onKeydown(event: KeyboardEvent): void { const { key } = event; if (this.isSpecialOperation(event) || !this.isKeyPrintable(event)) { return; } const newValue = this.getNewValue(event.target as HTMLInputElement, key); if (!this.valueIsValid(newValue)) { event.preventDefault(); } } @HostListener('paste', ['$event']) public onPaste(event: ClipboardEvent): void { const pastedText = event.clipboardData.getData('text'); const newValue = this.getNewValue(event.target as HTMLInputElement, pastedText); if (!this.valueIsValid(newValue)) { event.preventDefault(); } } private getNewValue(target: HTMLInputElement, str: string): string { const { value = '', selectionStart, selectionEnd } = target; return [ ...value.split('').splice(0, selectionStart), str, ...value.split('').splice(selectionEnd)].join(''); } private valueIsValid(value: string): boolean { return /^-?\d*(,|\.)?\d*$/.test(value); } private isSpecialOperation(event: KeyboardEvent): boolean { const { keyCode, ctrlKey, metaKey } = event; // allow ctr-A/C/V/X/Y/Z const keysACVXYZ = [65, 67, 86, 88, 89, 90]; if ((ctrlKey || metaKey) && keysACVXYZ.indexOf(keyCode) >= 0) { return true; } return false; } private isKeyPrintable(event: KeyboardEvent): boolean { const { keyCode } = event; return ( (keyCode > 47 && keyCode < 58) || // number keys keyCode === 32 || keyCode === 13 || // spacebar & return key(s) (keyCode > 64 && keyCode < 91) || // letter keys (keyCode > 95 && keyCode < 112) || // numpad keys (keyCode > 185 && keyCode < 193) || // ;=,-./` (in order) (keyCode > 218 && keyCode < 223)); // [\]' (in order) } } And a custom input-number component implementing ControlValueAccessor: import { Component, ViewChild, forwardRef, ElementRef, Input, Output, EventEmitter } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; @Component({ selector: 'app-input-number', template: ` <input type="text" #input appNumberOnly [placeholder]="placeholder" [value]="_stringifiedValue" (input)="_onInput($event.target.value)" (change)="_onChange($event.target.value)" (blur)="input.value = _stringifiedValue"> `, styles: [` :host { width: 100%; display: block; } input { width: 100%; } `], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputNumberComponent), multi: true } ] }) export class InputNumberComponent implements ControlValueAccessor { private onChange = [(_: number) => {}]; private onTouch = [() => {}]; @Input() placeholder; @ViewChild('input') _input: ElementRef; @Input() get value(): number { return this._value; } set value(value: number) { const safeValue = this.safeValue(value); if (safeValue !== this._value) { this._value = safeValue; this.onChange.forEach(fn => fn(safeValue)); } } private _value: number = undefined; @Output() valueChange = new EventEmitter<number>(); get _stringifiedValue(): string { const val = (this._input.nativeElement.value || '').replace('.', ','); if (val === '-' || val === ',') return val; const safeValue = this.safeValue(this.value); return this.stringify(safeValue).replace('.', ','); } _onInput(value: string): void { this.value = this.safeValue(value); } _onChange(value: string): void { this.value = this.safeValue(value); this.valueChange.emit(this.value); } private safeValue(val: string | number): number { const safeValue = parseFloat(this.stringify(val).replace(',', '.')); return isNaN(safeValue) ? undefined : safeValue; } private stringify(val: string | number): string { return val === undefined || val === null ? '' : `${val}`; } public registerOnChange(fn: any): void { this.onChange.push(fn); } public registerOnTouched(fn: any): void { this.onTouch.push(fn); } public writeValue(inputValue: number): void { this.value = this.safeValue(inputValue); } } The component can then be used with two-way binding with [(ngModel)] or with [(value)]. It will work with reactive-forms too: <app-input-number [(ngModel)]="value"></app-input-number> <app-input-number [(value)]="value"></app-input-number>
unknown
d19149
test
These are the jquery selectors (as of jQuery 1.10 and jQuery 2.0): * *All Selector ("*") Selects all elements. *:animated Selector Select all elements that are in the progress of an animation at the time the selector is run. *Attribute Contains Prefix Selector [name|="value"] Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-). *Attribute Contains Selector [name*="value"] Selects elements that have the specified attribute with a value containing the a given substring. *Attribute Contains Word Selector [name~="value"] Selects elements that have the specified attribute with a value containing a given word, delimited by spaces. *Attribute Ends With Selector [name$="value"] Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive. *Attribute Equals Selector [name="value"] Selects elements that have the specified attribute with a value exactly equal to a certain value. *Attribute Not Equal Selector [name!="value"] Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value. *Attribute Starts With Selector [name^="value"] Selects elements that have the specified attribute with a value beginning exactly with a given string. *:button Selector Selects all button elements and elements of type button. *:checkbox Selector Selects all elements of type checkbox. *:checked Selector Matches all elements that are checked or selected. *Child Selector ("parent > child") Selects all direct child elements specified by “child” of elements specified by “parent”. *Class Selector (“.class”) Selects all elements with the given class. *:contains() Selector Select all elements that contain the specified text. *Descendant Selector ("ancestor descendant") Selects all elements that are descendants of a given ancestor. *:disabled Selector Selects all elements that are disabled. *Element Selector (“element”) Selects all elements with the given tag name. *:empty Selector Select all elements that have no children (including text nodes). *:enabled Selector Selects all elements that are enabled. *:eq() Selector Select the element at index n within the matched set. *:even Selector Selects even elements, zero-indexed. See also odd. *:file Selector Selects all elements of type file. *:first-child Selector Selects all elements that are the first child of their parent. *:first-of-type Selector Selects all elements that are the first among siblings of the same element name. *:first Selector Selects the first matched element. *:focus Selector Selects element if it is currently focused. *:gt() Selector Select all elements at an index greater than index within the matched set. *Has Attribute Selector [name] Selects elements that have the specified attribute, with any value. *:has() Selector Selects elements which contain at least one element that matches the specified selector. *:header Selector Selects all elements that are headers, like h1, h2, h3 and so on. *:hidden Selector Selects all elements that are hidden. *ID Selector (“#id”) Selects a single element with the given id attribute. *:image Selector Selects all elements of type image. *:input Selector Selects all input, textarea, select and button elements. *:lang() Selector Selects all elements of the specified language. *:last-child Selector Selects all elements that are the last child of their parent. *:last-of-type Selector Selects all elements that are the last among siblings of the same element name. *:last Selector Selects the last matched element. *:lt() Selector Select all elements at an index less than index within the matched set. ***Multiple Attribute Selector [name="value"][name2="value2"] Matches elements that match all of the specified attribute filters. *Multiple Selector (“selector1, selector2, selectorN”) Selects the combined results of all the specified selectors. *Next Adjacent Selector (“prev + next”) Selects all next elements matching “next” that are immediately preceded by a sibling “prev”. *Next Siblings Selector (“prev ~ siblings”) Selects all sibling elements that follow after the “prev” element, have the same parent, and match the filtering “siblings” selector. *:not() Selector Selects all elements that do not match the given selector. *:nth-child() Selector Selects all elements that are the nth-child of their parent. *:nth-last-child() Selector Selects all elements that are the nth-child of their parent, counting from the last element to the first. *:nth-last-of-type() Selector Selects all elements that are the nth-child of their parent, counting from the last element to the first. *:nth-of-type() Selector Selects all elements that are the nth child of their parent in relation to siblings with the same element name. *:odd Selector Selects odd elements, zero-indexed. See also even. *:only-child Selector Selects all elements that are the only child of their parent. *:only-of-type Selector Selects all elements that have no siblings with the same element name. *:parent Selector Select all elements that have at least one child node (either an element or text). *:password Selector Selects all elements of type password. *:radio Selector Selects all elements of type radio. *:reset Selector Selects all elements of type reset. *:root Selector Selects the element that is the root of the document. *:selected Selector Selects all elements that are selected. *:submit Selector Selects all elements of type submit. *:target Selector Selects the target element indicated by the fragment identifier of the document’s URI. *:text Selector Selects all elements of type text. *:visible Selector Selects all elements that are visible. Source: http://api.jquery.com/category/selectors/
unknown
d19150
test
Using library(data.table) we can do dt[, paste(drug, collapse = '-'), by = .(id,date)] # id date V1 # 1: A234 2014-01-01 5FU # 2: A234 2014-01-02 adderall-tylenol # 3: B324 1990-06-01 adderall-tylenol Although this also includes id-date combinations where the drug combination is not a tuple. If you want to only have the lines which have exactly two drugs, then we add a test for this: dt[, if (.N == 2) paste(drug, collapse = '-'), by = .(id,date)] # id date V1 # 1: A234 2014-01-02 adderall-tylenol # 2: B324 1990-06-01 adderall-tylenol To further subset these results to only those patients where a drug combination was applied more than 25 times on different days, we can chain the result to another test for this: dt[, if (.N == 2) paste(drug, collapse = '-'), by = .(id,date)][, if (.N>25) .(date,V1), by=id] If you need, you can write these results to a new file using write.table The data dt = fread("id, date, drug A234,2014-01-01,5FU A234,2014-01-02,adderall B324,1990-06-01,adderall A234,2014-01-02,tylenol B324,1990-06-01,tylenol") A: You can use dplyr library to summarize the data table. library(dplyr) data = data.frame(id = c("A234","A234", "B324", "A234","B324"), date = strptime(c("2014-01-01","2014-01-02", "1990-06-01", "2014-01-02", "1990-06-01"), format = "%Y-%m-%d"), drug = c("5FU", "adderall", "adderall", "tylenol", "tylenol")) data %>% group_by(id, date) %>% summarise(drug_used = paste(drug,collapse = "-")) Source: local data frame [3 x 3] Groups: id [?] id date drug_used <fctr> <dttm> <chr> 1 A234 2014-01-01 5FU 2 A234 2014-01-02 adderall-tylenol 3 B324 1990-06-01 adderall-tylenol
unknown
d19151
test
Approach 1 allows you to use multipart features, for example, uploading multiple files at the same time, or adding extra form to the POST. In which case you can change the server side signature to: @POST @Path("upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadMultipart(FormDataMultiPart multiPart) throws IOException { } I also found that I had to register the MultiPartFeature in my test client... public FileUploadUnitTest extends JerseyTest { @Before public void before() { // to support file upload as a test client client().register(MultiPartFeature.class); } } And server public class Application extends ResourceConfig { public Application() { register(MultiPartFeature.class); } } Thanks for your question, it helped me write my jersey file unit test!
unknown
d19152
test
No, whatever you display as text in webpage can be found by digging into the source of the webpage (including js). What would this be useful for btw.? Edit: This looks useful but ends up using canvas or flash I believe. Still might be tuned to be fairly fast and therefor useful: http://eric-blue.com/2010/01/03/how-to-create-your-own-personal-document-viewer-like-scribd-or-google-books/ A: You most likely won't find a way to do this easily, as when the browser downloads the page, in order to show the text to the user it has to be decoded or decrypted. So no matter what, if the user can see it, they can copy it. If all you want is to block selection in the browser, this answer should help A: No, if you want to place something on the page a browser need to know what you want to place on the page. And everything what was sent to the browser is readable for a user. So you cannot do this. The answer is very simple: If you don't want to publish something don't place it on the internet. A: yes, this my logic check out make you string in ascii code and write on document check below link and find example may you help Link W3School A: I guess no one could do that. Just use some image instead, old-style, but useful.
unknown
d19153
test
You will need a controller for Friendships e.g. FriendshipsController. Your Add button should point to an action in FriendshipsController which will copy the parameters you provide. * *In your view you should have something like this: <%= button_to "Add friend", friendships_path(:name => user.name, :email => user.email ...) %> *FriendshipsController: def create # handle params here (you can get user's data from params[:name], params[:email] and such # e.g. @friendship = Friendship.create(:name => params[:name], ...) end Also consider this article http://railscasts.com/episodes/163-self-referential-association explaining self referential association in Rails.
unknown
d19154
test
So, apparently - transaction.atomic(): is managing the transaction for the 'default' DB by default, unless other DB is mentioned: transaction.atomic(using='otherDB'): Since we use more than one DB and the one that I worked on was not set as the default, I was missing the 'using'.
unknown
d19155
test
var current = $(this).attr('href').slice(1); alert(current); A: I assume you're dealing with a <a> element? this.hash.substring(1); // yes, it's that simple... A: As easy as this, just use replace: var current = $(this).attr('href').replace('#','');
unknown
d19156
test
You might have to think about this a little more: Users have a contact and billing address, what about shipping and other addresses? Is it possible to have two users from one company, each with different contact addresses but the same billing address? Is it possible for one user to have multiple billing addresses that they will choose at the time of order? Then when it comes to your orders, what happens if a customer updates his billing address, and then you pull up an order from before the billing address changed. Should the billing address on the old order be the new one, or the one from the time of the order? If the problem is as simple as you describe, and a user simply has contact and billing addresses, and there are no other "what ifs", then it makes sense to just put those addresses in the user's table. From my limited experience in this domain, however, you may very well find that addresses need to be entities in their own right, separate from specific users. In fact, it may be that you think of a "user" as a "contact address". A: Contact, billing, and shipping (if needed) information are logically separate. From a pure normalization point of view, an address should be a separate entity, and you should have a relationship between Customers and Addresses. The most 'correct' approach from a normalization point of view would have a many-to-many relationship between Customers and Addresses, with a Type for differentiation between billing, contact and shipping addresses (assuming it's allowable to have more than one of each). You also need to consider your products as well. A common approach is to have an Order table, with a Lines table below it (one-to-many relationship from Order to Lines). Each Line will reference a single Product, with a Quantity, a Price and any other relevant information (discount, etc.). Simple pricing can be accomodated with a price entry in the products table; more complex pricing strategies will require more effort, obviously. Before anyone says I've gone too far: 'simple' sites often evolve. Getting your data model right beforehand will save you untold agony down the road. A: I think the contact information should be in the users table, there's no need to normalize it down to dedicated zip code tables etc. Its the same with the billing information, if they are perhaps creditcard number or something like this. If billing information means a certain plan, then i would put the different available plans into a seperate table and "link" it by a foreign key. A: If you'll be looking up contact and billing information at the same time and you'll rarely be using just one of them then there is no use separating them into different tables since you'll be joining them anyway. On the other hand, if you often only lookup one of contact or billing then performance might benefit from the separation. I, personally, would not separate them since I can't foresee many times where I don't want both of them. A: Will you have cases where a "user" could have multiple contacts? I've had database designs where a "customer" could have multiple contacts, and in such cases you should maintain a separate table for contacts. Otherwise, as the others said, you can keep the users and their contact information in the same table since you'll always be querying them together.
unknown
d19157
test
I must say https://github.com/gabrielg/periscope_api/ implementation is a bit complicated. Author using 2 sets of keys (IOS_* and PERISCOPE_*) when you actually need only one to access API. I didn't tried to broadcast but in my PHP library all other functions works without troubles with only what he call PERISCOPE_* set of keys. You will get session_secret and session_key from Twitter after getting access to it as Periscope application. So Periscope's login via Twitter process looks like * *Request OAuth token via https://api.twitter.com/oauth/request_token *Redirect user to https://api.twitter.com/oauth/authorize?oauth_token=[oauth_token] *Wait for user login and get oauth_token and oauth_verifier from redirect url *Get oauth_token, oauth_token_secret, user_id and user_name via request to https://api.twitter.com/oauth/access_token?oauth_verifier=[oauth_verifier] *Send request to https://api.periscope.tv/api/v2/loginTwitter { "bundle_id": "com.bountylabs.periscope", "phone_number": "", "session_key": "oauth_token", "session_secret": "oauth_token_secret", "user_id": "user_id", "user_name": "user_name", "vendor_id": "81EA8A9B-2950-40CD-9365-40535404DDE4" } *Save cookie value from last response and add it to all JSON API calls as some kind of authentication token. Requests in 1 and 4 steps should be signed with proper Authorization header which requires Periscope application's consumer_key and consumer_secret. While consumer_key can be sniffed right in first step (if you are able to bypass certificate pinning) consumer_secret never leaves your device and you can't get it with simple traffic interception. There is PHP example of login process https://gist.github.com/bearburger/b4d1a058c4f85b75fa83 A: Periscope's API is not public and the library you are referring to is sort of a hack. To answer the original question, oauth_key & oauth_secret are keys sent by your actual device to periscope service. You can find them by sniffing network traffic sent by your device.
unknown
d19158
test
There's no way to make the CLR ignore a field. I would instead use two structures, and perhaps make one a member of the other. struct MyNativeStructure { public int foo; public int bar; } struct MyStructure { public MyNativeStruct native; public int ignored; } A: Two methods: * *Use a class instead of a struct: structures are always passed by pointer to the Windows API or other native functions. Replacing a call to doThis(ref myStruct) with a call to doThis([In, Out] myClass) should do the trick. Once you've done this, you can simply access your not-to-be-marshaled fields with methods. *As i already stated, structs are (almost) always passed by reference: hence the callee knows nothing about structure dimensions: what about simply leaving your additional fields to be the last ones? When calling a native function that needs your structure's pointer and the structure's size, simply lie about its size, giving the one it would have without your extra fields. I don't know if it's a legal way to marshal such a structure back when obtaining it FROM a native function. Side question: does the Marshaller process class fields marked as private? (I hope not...) A: based on my tests, auto property like: private int marshaled { get; set; } will consume space while marshaling (Marshal.SizeOf) But! explicitly specified property will not: private int skipped { get { return 0; } set { } }
unknown
d19159
test
Yes this is the infamous "ie6 z-index bug". It has been discussed a couple of time on StackOverflow and on the web. Personnaly, the best resource that I found for this bug is Solutions to the IE z-index Bug: CSS. It clearly describe the bug and the solution. By the way, questions like "Look at my site and please tell me how to fix it" are better answered on doctype.com.
unknown
d19160
test
I was also facing same issue. What I did this: Just right click on maven dependencies of project A > select properties > click on use maven project settings > uncheck Resolve dependencies from Workspace projects Eclipse displays that when the dependency is found in the same workspace. You can disable this in maven or project settings, then you'd need to build using mvn to see your dependency jar listed like other. A: I have solved it! the dependency should be: <dependency> <groupId>AWSTest</groupId> <artifactId>AWSUtil</artifactId> <version>0.0.1-SNAPSHOT</version> <type>test-jar</type> </dependency>
unknown
d19161
test
As was mentioned in the comments, if you have a single quotation marks/ double quotation marks issue you need to use the \' syntax (adding a \ sign before a special character, like \' or \"). <html> <body onload="onPageLoad()"> <script> function onPageLoad() { var testString = "This is the test text..."; var divElement = document.createElement('div'); divElement.innerHTML = '<h1 onclick="onClickFunc(\''+ testString + '\')">Click Me!</h1>'; document.body.appendChild(divElement); } function onClickFunc(str) { alert(str); } </script> </body> </html> A: You are passing p as a variable not a string. Here, p is not defined so error is coming. Give it as string. Try this: function test(p) { } ...innerHTML = '<div onclick=test("p")>ABC</div>'; or function test(p) { } ...innerHTML = '<div onclick="test(\'p\')">ABC</div>';
unknown
d19162
test
It won't help performance, in fact it will be harmful. It's recommended to spawn N-1 workers, N being the amount of CPU cores. You can issue: pm2 start app.js -i -1 for that. Given that you only have 2 cores, this will only use one, so you won't take advantage of clustering. If you want to try using 2 cores in your case, you should run your own benchmarks, but make sure that your machine is not doing much work outside of Node.js, otherwise it will be better to just use 1 core. If you use more workers than CPU cores, the processes will start competing for resources, which will downgrade the performance of the application.
unknown
d19163
test
Please read the documentation on NSArray. It can contain any number of arbitrary objects. That said, without knowing more about what you're doing, I'd suggest you look at NSDictionary and its mutable subclass. A: Yes, you can store any type of object into one of the NSArray classes. The only difficulty is in conceptually dealing with how to access this data structure; complex nesting of arrays within arrays can be hard to manage and lead to bugs. Make sure your needs aren't better solved by another data structure, or a custom class. A: Yes. You can use the following (enormous) line of code: NSMutableArray * completeArray = [NSMutableArray arrayWithArray: [[myArray objectAtIndex:0] arrayByAddingObjectsFromArray: [myArray objectAtIndex:1]]]; edit: Assuming that myArray is defined as follows: NSArray * stringArray = [NSArray arrayWithObjects: @"one", @"two", @"three", nil]; NSArray * otherArray = [NSArray arrayWithObjects: someObj, otherObj, thirdObj, nil]; NSArray * myArray = [NSArray arrayWithObjects: stringArray, otherArray, nil]; The line of code I posted above will give you one big NSMutableArray which contains: @"one, @"two", @"three", someObj, otherObj, thirdObj
unknown
d19164
test
The problem was that the .append() was being called before the value was returned from getJson(). Placing the .append() inside the .getJson() solved the problem. This works: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script src="http://josscrowcroft.github.com/money.js/money.js"></script> <script type="text/javascript"> function ConvertMoney(to, from, amt) { // Load exchange rates data via the cross-domain/AJAX proxy: $.getJSON('http://openexchangerates.org/latest.json', function (data) { // Check money.js has finished loading: if (typeof fx !== "undefined" && fx.rates) { fx.rates = data.rates; fx.base = data.base; } else { // If not, apply to fxSetup global: var fxSetup = { rates: data.rates, base: data.base }; } var result = "<li>" + fx.convert(amt, { from: from, to: to }) + "</li>"; $("#result").append(result); }); } $("#convert").live("click", function () { var from = $("#pfx-from-currency").val(); var to = $("#pfx-to-currency").val(); var amt = $("#pfx-input-amount").val(); ConvertMoney(to, from, amt); }); $(document).keypress(function(e) { if(e.keyCode == 13) { var from = $("#pfx-from-currency").val(); var to = $("#pfx-to-currency").val(); var amt = $("#pfx-input-amount").val(); ConvertMoney(to, from, amt); } }); </script> </head> <body> Amount: <input type='text' id='pfx-input-amount' /><br /> From: <select id='pfx-from-currency'> <option>Please Choose</option> <option>GBP</option> </select><br /> To: <select id='pfx-to-currency'> <option>Please Choose</option> <option>USD</option> </select><br /> <input type='button' id="convert" value='Convert' /> <ul id="result"> </ul> </body> </html> A: Looks like you have an object terminated by a semicolon var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency; }); that is not valid, try changing it to var convertedValue = fx.convert(inputAmount, {to: pfxToCurrency }); Also I would expect var pfxToCurrency = document.getElementById('pfx-to-currency').value and not just var pfxToCurrency = document.getElementById('pfx-to-currency') A: Looks like you have an extra <script> tag: <script type="text/javascript"> $(document).ready(function(){ <script type="text/javascript"> A: please make sure that properly Closing your Document ready function ( ** closing ) $(document).ready(function () { ........ .......... }); } //end pfxCurrencyConverter **});** $(document).ready(function(){ pfxCurrencyConverter(); });
unknown
d19165
test
Given that forks is claiming to provide the same interface as threads I'd be more inclined to report it against forks over HTML::DOM. Especially since the forks is the one doing the deep magic, whereas HTML::DOM is just a normal everyday module. Its not likely the HTML::DOM authors will have any idea what you're on about. A: Problem "solved". I had a weird settings in $PERLLIB and $PERL5LIB, that linked to non-existing directories or directories with outdated libraries. Once I fixed that, forks started working as it should. So, if you have similar troubles with forks, check your $PERLLIB and $PERL5LIB, if it links where it should link.
unknown
d19166
test
This works for me (Note this uses the jquery library): $(document).ready(function () { Your code here... }); This will wait for the page to load then run the function. I personally use this for animations but then the animations also take more time for me so I have to also include the setTimeout function like this: setTimeout(function () { Your code here... }, 1000); It waits a specific amount of milliseconds before executing the function. A: Turns out the issue was coming from my index.php structure; I moved the php code in separate files and included it at the end of index.php instead of the top. Now Im having other issues but the main question is resolved.
unknown
d19167
test
all: clean check this line. The default (first) Target of your Makefile depends on clean, so before any build is started, the clean target is executed that likely will remove all built files, to rebuild them. Drop the clean and you should get the incremental behaviour make was designed for.
unknown
d19168
test
import pandas as pd from sklearn.linear_model import LinearRegression # setup dictionary = {'bedrooms': [3,3,2,4,3,4,3,3,3,3,3,2,3,3], 'bathrooms': [1,2.25,1,3,2,4.5,2.25,1.5,1,2.5,2.5,1,1,1.75], 'sqft_living': [1180, 2570,770,1960,1680,5420,1715,1060,1780,1890,'',1160,'',1370], 'sqft_lot': [5650,7242,10000,5000,8080,101930,6819,9711,7470,6560,9796,6000,19901,9680]} df = pd.DataFrame(dictionary) # setup x and y for training # drop data with empty row clean_df = df[df['sqft_living'] != ''] # separate variables into my x and y x = clean_df.iloc[:, [0,1,3]].values y = clean_df['sqft_living'].values # fit my model lm = LinearRegression() lm.fit(x, y) # get the rows I am trying to do my prediction on predict_x = df[df['sqft_living'] == ''].iloc[:, [0,1,3]].values # perform my prediction lm.predict(predict_x) # I get values 1964.983 for row 10, and 1567.068 row row 12 It should be noted that you're asking about imputation. I suggest reading and understanding other methods, trade offs, and when to do it. Edit: Putting Code back into DataFrame: # Get index of missing data missing_index = df[df['sqft_living'] == ''].index # Replace df.loc[missing_index, 'sqft_living'] = lm.predict(predict_x)
unknown
d19169
test
You can use any API provided by apple to use it in your React app. You can find the documentation here.
unknown
d19170
test
How about lazy loading and proper DTO response objects ? * *WCF returns custom Order or GetOrderResponse (Contracts.Order) *Load Order from EntityModel through repository (just the order) *Use automapper for mapping EntityModel.Order => Contracts.Order Result : only the corresponding properties inside Contracts.Order are loaded: Ex. Contracts.Order Number OrderDetails (=> Only this property is loaded through lazy loading because it is mapped) If you are building a SOA or webservice, don't let the client specify load graphs. If it's necessary for the client to specify load graphs consider deploying the Model using WCF Data Services, works great. Perhaps you could build two systems .. one SOA and one (readonly) Data Service.
unknown
d19171
test
In C++03 function local types are not viable template arguments. In C++11 function local types are viable template arguments. The key quote in C++03 is 14.3.1 [temp.arg.type] paragraph 2: The following types shall not be used as a template-argument for a template type-parameter: * *a type whose name has no linkage *... In C++11 this constraint is removed. The relevant section on when linkage is defined is 3.5 [basic.link] (in both standard) which is fairly long and points to entities without linkage by exclusion, paragraph 8 in C++03: Names not covered by these rules have no linkage. ... Types defined within a function are not listed in "these rules".
unknown
d19172
test
Environment variables is an OS concept, and are passed by the program that starts your Java program. That is usually the OS, e.g. double-click in an explorer window or running command in a command prompt, so you get the OS-managed list of environment variables. If another program starts your Java program1, e.g. an IDE (Eclipse, IntelliJ, NetBeans, ...) or a build tool (Maven, Groovy, ...), it can modify the list of environment variables, usually by adding more. E.g. the environment variable named MAVEN_CMD_LINE_ARGS would tend to indicate that you might be running your program with Maven. In a running Java program, the list of environment variables cannot be modified. System properties is a Java concept. The JVM will automatically assign a lot of system properties on startup. You can add/override the values on startup by using the -D command-line argument. In a running Java program, the list of system properties can be modified by the program itself, though that is generally a bad idea. 1) For reference, if a Java program wants to start another Java program, it will generally use a ProcessBuilder to set that up. The environment variables of the new Java process will by default be the same as the current Java program, but can be modified for the new Java program by calling the environment() method of the builder.
unknown
d19173
test
The reason you get the PHP source itself, rather than the output it should be rendering, is that your local HTTP server - receiving your request targeted at http://localhost/test.php - decided to serve back the PHP source, rather than forward the HTTP request to a PHP processor to render the output. Why this happens? that has to do with your HTTP server's configuration; there might be a few reasons for that. For starters, you should validate your HTTP server's configuration. * *Which HTTP server are you using on your machine? *What happens when you browse http://localhost/test.php through your browser? A: The problem here is not the Java code - the problem lies with the web server. You need to investigate why your webserver is not executing your PHP script but sending it back raw. You can begin by testing using a simple PHP scipt which returns a fixed result and is accessed using a GET request (from a web browser). Once that is working you can test using the one that responds to POST requests.
unknown
d19174
test
There no asyncData/fetch methods on components in nuxt. It is available only for page components. Reference https://nuxtjs.org/api/ asyncData is called every time before loading the component (only for page components). A: context.params.id is a string and the id in the array of objects is an integer therefore find() is not returning the expected object. Changing id to a string in the array of objects fixed the error. A: in my case I was missing the .id in context.params.id simple oversight.
unknown
d19175
test
Looks like index = row * width + column to me.
unknown
d19176
test
This is an example of a GET string. Anything after the "?" will be the parameters. You don't have anything after the "?". Thus no parameters. For some reason, this makes soapui remove it. But it really should be without any consequence. Both https://mydomain/response? and https://mydomain/response will reach the same endpoint with no parameters.
unknown
d19177
test
Magick::Image#read returns an array of images, because this method may be used for reading animated gifs. Simply call .first on the result: img = Magick::Image.read('public/images/bg.png').first Another problem is that you should call annotate on instance of Draw, passing img as first parameter: Magick::Draw.new.annotate(img, 0, 0, 90, 15, 'hello world') do # set options here self.gravity = Magick::SouthEastGravity # … end
unknown
d19178
test
I figured out how to do it Here's the code: from kivymd.uix.screen import MDScreen from kivymd.uix.menu import MDDropdownMenu from kivymd.uix.dropdownitem import MDDropDownItem from kivymd.app import MDApp class Contents(MDScreen): def __init__(self, **kwargs): super().__init__(**kwargs) self.langlist =MDDropDownItem(pos_hint={'right': 0.85, 'top': 0.98}) self.langlist.set_item('English') self.langlist.md_bg_color = [1,1,1,1] self.add_widget(self.langlist) self.langlist.bind(on_release=self.menuopen) self.langlistmenu = MDDropdownMenu(position='bottom',callback=self.menuclose,caller=self.langlist,items=[{'viewclass':'MDMenuItem','text':'English'},{'viewclass':'MDMenuItem','text':'Français'},{'viewclass':'MDMenuItem','text':'Deutsche'},{'viewclass':'MDMenuItem','text':'русский'},{'viewclass':'MDMenuItem','text':'Español'}],width_mult=4) def menuclose(self,instance): self.langlist.set_item(instance.text) self.langlistmenu.dismiss() def menuopen(self,instance): self.langlistmenu.open() class AndroidApp(MDApp): def build(self): #self.theme_cls.theme_style = "Dark" self.theme_cls.primary_palette = 'Red' self.theme_cls.primary_hue = 'A400' return Contents() AndroidApp().run()
unknown
d19179
test
Yes, you have it correct. There is a trade-off when adding indexes. They have the potential to make selects faster, but they will make updates/inserts/deletes slower. A: When you design an index, consider the following database guidelines: * *Large numbers of indexes on a table affect the performance of INSERT, UPDATE, DELETE, and MERGE statements because all indexes must be adjusted appropriately as data in the table changes. For example, if a column is used in several indexes and you execute an UPDATE statement that modifies that column's data, each index that contains that column must be updated as well as the column in the underlying base table (heap or clustered index). *Avoid over-indexing heavily updated tables and keep indexes narrow, that is, with as few columns as possible. *Use many indexes to improve query performance on tables with low update requirements, but large volumes of data. Large numbers of indexes can help the performance of queries that do not modify data, such as SELECT statements, because the query optimizer has more indexes to choose from to determine the fastest access method. *Indexing small tables may not be optimal because it can take the query optimizer longer to traverse the index searching for data than to perform a simple table scan. Therefore, indexes on small tables might never be used, but must still be maintained as data in the table changes. For more information have a look at the below link:- http://technet.microsoft.com/en-us/library/jj835095(v=sql.110).aspx
unknown
d19180
test
No. TCP is a byte-stream protocol. No messages, no datagram-like behaviour. A: For UDP, that is true, because all data written by the app is sent out in one UDP datagram. For TCP, that is not true, unless the application sends only 1 byte of data at a time. A write to a TCP socket will write all of the data to a buffer that is associated with that socket. TCP will then read data from that buffer in the background and send it to the receiver. How much data TCP actually sends in one TCP segment depends on variables of its flow control mechanisms, and other factors, including: * *Receive Window published by the other node (receiver) *Amount of data sent in previous segments in flight that are not acknowledged yet *Slow start and congestion avoidance algorithm state *Negotiated maximum segment size (MSS) In TCP, you can never assume what the application writes to a socket is actually received in one read by the receiver. Data in the socket's buffer can be sent to the receiver in one or many TCP segments. At any moment when data is made available, the receiver can perform a socket read and return with whatever data is actually available at that moment. Of course, all sent data will eventually reach the receiver, if there is no failure in the middle preventing that, and if the receiver does not close the connection or stop reading before the data arrives.
unknown
d19181
test
Try this $(document).ready(function() { /* fetch elements and stop form event */ $("form.follow-form").submit(function(e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html) { $("ul.statuses").append(html); $("form.follow-form").remove(); } }); $(".morebox").html('The End'); return false; }); });​ A: You’ve got an else, but no if. Here’s the code with some proper indentation — indentation makes the code much easier to understand, so you spot errors more quickly. $(document).ready(function(){ /* fetch elements and stop form event */ $("form.follow-form").submit(function (e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html){ $("ul.statuses").append(html); $("form.follow-form").remove(); } }); ======> /* HERE’S THE ELSE WITHOUT AN IF */ else { $(".morebox").html('The End'); } return false; }); });
unknown
d19182
test
You will find all office id's you want on microsoft website http://www.microsoft.com/en-us/download/details.aspx?id=6627. You will find your id's in PowerPointControls.xlsx file. For create you own menu : Open your Ribbon.xml And add following after <ribbon> <tabs> <tab idMso="TabAddIns"> <group id="ContentGroup" label="Content"> <button id="textButton" label="Insert Text" screentip="Text" onAction="OnTextButton" supertip="Inserts text at the cursor location."/> <button id="tableButton" label="Insert Table" screentip="Table" onAction="OnTableButton" supertip="Inserts a table at the cursor location."/> </group> </tab> </tabs> For a custom addin shortcut, I think you have to add a new tab : <tab id="YourTab" visible="true" label="Name"> <group id="YourGroup" label="name"> <button onAction="CallAddinsHere();" label="Call add-ins"/> </group> </tab> If you want to interact with custom addin shortcut, have a look at : Automate Office Ribbon through MSAA (CSOfficeRibbonAccessibility)
unknown
d19183
test
You would have to use a custom decorator. You can see the code for the Django decorator here. It's already returned a response before your code is reached at all, so absolutely nothing you do in your view function would be run anyway. There is nothing wrong with manually returning a redirect if the request is not a POST. If you use this pattern in a few different places in your code I would then refactor it into a decorator later. But if this is the first place you are using it then it's overkill. A: A custom decorator is the way to go. I myself use one similar to the one you need and I'll post the code. Do upvote @aychedee s answer since he was first. :) def require_post_decorator(function=None, redirect_url='/'): def _decorator(view_function): def _view(request, *args, **kwargs): if request.method == 'POST': #do some before the view is reached stuffs here. return view_function(request, *args, **kwargs) else: return HttpResponseRedirect(redirect_url) _view.__name__ = view_function.__name__ _view.__dict__ = view_function.__dict__ _view.__doc__ = view_function.__doc__ return _view if function: return _decorator(function) return _decorator
unknown
d19184
test
Sockets do not have a thread affinity, so you can freely create a socket in one thread and use it in another thread. You do not need to call WSAStartup() on a per-thread basis. If accept() reports WSANOTINITIALISED then either WSAStartup() really was not called beforehand, or else WSACleanup() was called prematurely.
unknown
d19185
test
Two ideas: a) limit the depth your "bomb" is going to fork: @echo off set args=%* if "%args%" EQU "" (set args=0) else set /a args=%args%+1 if %args% LSS 8 start /min thisfile.bat (this will produce 2^9 -1 command windows, but only your main window is open.) b) kill the cmd.exe process in the main batch file @echo off SET args=%* :repeat start /min thisfile.bat.bat some_arg if "%args%" NEQ "" goto repeat pause taskkill /im cmd.exe pressing any key in the initial batch file will instamntly kill all cmd windows currently open. These solutions were tested with some restrictions, so if they work in a "hot" forkbomb, please let me know. hope this helps. EDIT: c)implement a time switch in the original bat: (still stops even if you can't get past pause) @echo off set args=%* :repeat start /min thisfile.bat some_arg if "%args%" NEQ "" goto repeat timeout /T 10 taskkill /im cmd.exe or, using the smaller "bomb": @echo off set args=%* if "%args%" NEQ "" (%0 some_arg|%0 some_arg) else start /min thisfile.bat some_arg timeout /T 10 taskkill /im cmd.exe A: If you're out to just show your friend fork bombs why not go for a silent but deadly approach? The fork bomb is in vbs, the cleanup is in batch. Do note, the vbs fork bomb does nothing turning your pc off/on wont fix, it just floods your session proccess's. The fork bomb: Do until true = false CreateObject("Wscript.Shell").Run Wscript.ScriptName Loop Source Cleanup: title=dontkillme FOR /F "tokens=2 delims= " %%A IN ('TASKLIST /FI ^"WINDOWTITLE eq dontkillme^" /NH') DO SET tid=%%A echo %tid% taskkill /F /IM cmd.exe /FI ^"PID ne %tid%^" Source A: If it runs in an accessible directory, you could try IF EXIST kill.txt (exit /b) ELSE (%0|%0) and make a file called kill.txt in the directory to stop the bomb.
unknown
d19186
test
As web requests are stateless at heart, each new page render will require re-fetching data from somewhere. Your current_user method is itself making a database call behind the scenes (assuming a stock Devise setup) to load the user on each page load. Similarly, while you can define a helper or module to share current_org and current_project values, like Ritaful pointed out, they will need to make database calls to fetch their values. Or at least, that's the typical Rails answer. You do have some other options. The first is to use the session storage to store the objects, through either native Ruby marshaling (a dangerous path, as the legacy systems I work with have shown) or through perhaps JSON serialization: # marshalling def current_org # this will break if your organization object contains a proc, and # can risk exploding your session storage if your object gets large session[:current_org] ||= current_user.organization end # serialization def current_org session[:current_org] ||= current_user.organization.to_json end However, the JSON object won't be an ActiveRecord model, so your code will have to adapt. You can technically make it a record through #from_json, but your relations won't work like you expect and in general you'd be straying too far into the woods at that point. Overall, I would avoid trying to prematurely optimize your database calls. A schema with proper indices can perform index lookups very quickly, so these lookups are unlikely to cause a problem. If you do start seeing issues, I'd start with looking into eager loading to reduce the number of queries made per page load, but not try too hard to eliminate them. As you scale, you can add layers of caching and dig into optimizations to further reduce database impact. A: You can create two methods in your ApplicationHelper def current_project current_user.current_project end def current_org current_user.current_org end These will be available to all controllers and views. For more information, check "How to Use Rails Helpers (Complete Guide)". A: What about the session? It's probably the easiest way. I remember I did something like this: * *When use logs in assign that id to session[:current_user_id] *Whenever a user navigates to another page have a private method that looks something like this: def setup(id) @user = User.find(id) end *Run that method in a before_action method like this: before_action do setup(session[:current_session_id]) end
unknown
d19187
test
Try to rollback on exception.. and also close the session no matter what heppens: Session session = this.sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); for (StepFlow stepFlow : stepFlows) { session.save(stepFlow); session.flush(); session.clear(); } tx.commit(); } catch (JDBCException e) { SQLException cause = (SQLException) e.getCause(); System.out.println(cause.getMessage()); tx.rollback(); }finally{ session.close(); }
unknown
d19188
test
Multi-targeting is a valid approach here, actually. You just need to merge the dictionaries during runtime, just like you would when setting a custom color theme. In your application's .csproj file, add the following <ItemGroup> elements (showing Android and Windows only, but the same applies for iOS, etc.): <!-- Platform specific XAML Android --> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-android')) == true"> <MauiXaml Update="Resources\Styles\Platform\SpecialStyles.android.xaml"> <Generator>MSBuild:Compile</Generator> </MauiXaml> </ItemGroup> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-android')) != true"> <MauiXaml Remove="Resources\Styles\Platform\SpecialStyles.android.xaml" /> <None Include="Resources\Styles\Platform\SpecialStyles.android.xaml" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> <Compile Remove="Resources\Styles\Platform\SpecialStyles.android.xaml.cs" /> <None Include="Resources\Styles\Platform\SpecialStyles.android.xaml.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> </ItemGroup> <!-- Platform specific XAML Windows --> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-windows')) == true"> <MauiXaml Update="Resources\Styles\Platform\SpecialStyles.windows.xaml"> <Generator>MSBuild:Compile</Generator> </MauiXaml> </ItemGroup> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-windows')) != true"> <MauiXaml Remove="Resources\Styles\Platform\SpecialStyles.windows.xaml" /> <None Include="Resources\Styles\Platform\SpecialStyles.windows.xaml" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> <Compile Remove="Resources\Styles\Platform\SpecialStyles.windows.xaml.cs" /> <None Include="Resources\Styles\Platform\SpecialStyles.windows.xaml.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> </ItemGroup> Then, under the Resources/Styles folder, you could create a new folder called Platform or similar and add a new Resource XAML file, e.g. SpecialStyles.android.xaml (and SpecialStyles.android.xaml.cs). Make sure to rename the class and remove the "android" from the name and add some special style you want to apply only on Android, e.g. red background for a Button: <?xml version="1.0" encoding="utf-8" ?> <ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiSamples.Resources.Styles.SpecialStyles"> <Style ApplyToDerivedTypes="True" TargetType="Button"> <Setter Property="BackgroundColor" Value="Red" /> </Style> </ResourceDictionary> Also rename the class in the code-behind: namespace MauiSamples.Resources.Styles; public partial class SpecialStyles : ResourceDictionary { public SpecialStyles() { InitializeComponent(); } } Do the same for Windows but make the Button green instead: <?xml version="1.0" encoding="utf-8" ?> <ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiSamples.Resources.Styles.SpecialStyles"> <Style ApplyToDerivedTypes="True" TargetType="Button"> <Setter Property="BackgroundColor" Value="Green" /> </Style> </ResourceDictionary> Finally, in your App.xaml.cs, you can merge the resource dictionary with the default resource dictionary as follows: #if ANDROID || WINDOWS ICollection<ResourceDictionary> mergedDictionaries = Current.Resources.MergedDictionaries; if (mergedDictionaries != null) { mergedDictionaries.Clear(); mergedDictionaries.Add(new MauiSamples.Resources.Styles.SpecialStyles()); } #endif Attention: Mind the preprocessor directive, this is only necessary, if the SpecialStyles class only exists for Android or Windows. If you provide a SpecialStyles class for each platform respectively with their own suffix (e.g. SpecialStyles.ios.xaml, etc.), then you wouldn't need the preprocessor directive. As I was curious about this, I quickly implemented the full sample in my open source MAUI samples GitHub repo: https://github.com/ewerspej/maui-samples Result on Android: Result on Windows: UPDATE This approach works, I only noticed that the newly created XAML files might disappear from the Solution Explorer, but they still get processed during the build. Apparently, the <MauiXaml> build action does not get reevaluated in the Solution Explorer according to the selected target framework. I regard this as an inconvenience and I'm happy to update the answer if I find a better solution or if someone has suggestions to improve it.
unknown
d19189
test
Try that: <telerik:GridBoundColumn DataField="fromDate" DataType="System.DateTime" HeaderText="تاريخ البداية" UniqueName="fromDate" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
unknown
d19190
test
In serialization and deserialization without annotation the membernames need to match your JSON structure. The class world and worldData are OK-ish but the world class is missing the property world. If I change your class structure to this: public class worldData { public string Text { get; set; } public string Icon { get; set; } public int sectionID { get; set; } } // notice I had to change your classname // because membernames cannot be the same as their typename public class worldroot { public worldData world { get; set; } } I can deserialize your json in an array whicjh gives me two elements: var l = JsonConvert.DeserializeObject<worldroot[]>(json); And on the catching of exceptions: Only catch exceptions if you are going to do something sensible with them. try { var stream = File.OpenText("Application/story/"+level+".json"); //Read the file st = stream.ReadToEnd(); } catch(SystemException e){} empty catches like that are useless and only hinder in debugging. You can live with unchecked exceptions.
unknown
d19191
test
You just need to add the package name while getting the file For example if your properties name is "ABC.properties" in package a.b.c then the below code will work perfectly ResourceBundle labels = ResourceBundle.getBundle("a.b.c.ABC"); A: Just copy the resource file over to where your class files are. In my case my directory was: bin - com - brookf - all my packages here. copy your resource file to the bin folder. A: Follow the hints in this post and see if you made one of those mistakes, which could be (copy pasted from the link): * *These resource properties files are loaded by classloader, similar to java classes. So you need to include them in your runtime classpath. *These resources have fully-qualified-resource-name, similar to a fully-qualified-class-name, excerpt you can't import a resource into your java source file. Why? because its name takes the form of a string. *ResourceBundle.getBundle("config") tells the classloader to load a resource named "config" with default package (that is, no package). It does NOT mean a resource in the current package that has the referencing class. *ResourceBundle.getBundle("com.cheng.scrap.config") tells the classloader to load a resource named "config" with package "com.cheng.scrap." Its fully-qualified-resource-name is "com.cheng.scrap.config" A: Loading the Properties file for localization stuff is also affected by the package naming. If you put your Properties file in a package like org.example.com.foobar and load it just by its name abc you have to add the prefix org.example.com.foobar, too. If you have the properties at a different location (like in the root directory or in another subdir) you have to change either the name to load or the classpath. I run fine in placing the properties file in the same location where the .java file is and using something like private static ResourceBundle RES = ResourceBundle.getBundle(NameOfTheCurrentClass.class.getCanonicalName()); A: I had the same issue today and it took me a while until I figured out a fix (I'm using Eclipse as an IDE). My project folder contains the *.properties-Files in the following path: project/src/strings Since strings is a sub-folder of src and src is already in the build path of the project (see Property Window), all I needed was to add an Inclusion-Pattern for the *.properties-Files: **/*.properties There should be already an Inclusion-Pattern for *.java-Files (**/*.java) Maybe there is something similar for your IDE A: Is the file in your classpath? If it is, try renaming it to abc_en_US.properties
unknown
d19192
test
The problem is that draw is defined in window.onclick, but you are trying to call it from window.onload. Are you sure you do not have a closing bracket missing before the definition of draw? A: Try moving the draw() function out of the window.click function. window.onclick = function(e) { // ... }; function draw() { // ... } One of the major benefits of being strict with your indentation is that you can pick up these bugs very quickly. window.click = function(e) { // ... function draw() { // ... } }; Is the code you had. A: As a result of draw being located inside of the window.onclick anonymous function, it is scoped there. Since window.onload does not share the scope of that anonymous function, you cannot access draw from window.onload. You should removed the draw function from your window.onclick event so that it may be called from other scopes. function draw(){} window.onload = function(){ /*code*/ }; window.onclick = function(){ /* code */ };
unknown
d19193
test
+1 to Siddharth for that answer. There's another bit that won't be apparent if you're just getting started out. You can have PPT pass a reference to the clicked shape when the shape triggers a macro (caution: Mac PPT is buggy/incomplete. This won't work there). Using Siddharth's suggestion as a jumping off point, you can do something like this: Option Explicit Sub SelectMe(oSh As Shape) ' assign this macro to each of the shapes you want to color ' saves time to assign it to one shape, then copy the shape as many ' times as needed. ActivePresentation.Tags.Add "LastSelected", oSh.Name End Sub Sub ColorMeRed(oSh As Shape) ' assign this macro to the "color it red" shape ' when this runs because you clicked a shape assigned to run the macro, ' oSh will contain a reference to the shape you clicked ' oSh.Parent returns a reference to the slide that contains the shape ' oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) returns a reference ' to the shape whose name is contained in the "LastSelected" tag, ' which was applied in the SelectMe macro above. ' Whew! If Len(ActivePresentation.Tags("LastSelected")) > 0 Then With oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) .Fill.ForeColor.RGB = RGB(255, 0, 0) End With End If End Sub Sub ColorMeBlue(oSh As Shape) ' assign this macro to the "color it blue" shape If Len(ActivePresentation.Tags("LastSelected")) > 0 Then With oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) .Fill.ForeColor.RGB = RGB(0, 0, 255) End With End If End Sub
unknown
d19194
test
location_string = location_string.replace(/ \([^)]*\)/, ''); On a side note, please stop thinking that jQuery is necessary for anything at all, especially not a string manipulation task like this. It really isn't, and jQuery is overhyped. A: I'm not sure how you're given "Peal River NY..." (variable? innerHTML?), but you need to use a regular expression to match the (numbers), and the replace method to substitute the match for nothing "". "Peal River, NY (10965)".replace(/ \([0-9]+\)/, ""); This doesn't use jQuery! See the String.replace method. As mentioned by @James in the comments, this snippet will leave "Peal River, NY ()" as "Peal River, NY ()", rather than removing the brackets. If this is a case you need to consider, change the + to *: "Peal River, NY (10965)".replace(/ \([0-9]*\)/, ""); A: Use a regex: var s = "Pearl River, NY (10965)"; alert(s.replace(/ \([\d]*\)/,'')); See it at this JSFiddle Of course, here I am assuming you'll be wanting to replace only numbers in the brackets. For letter and underscore, use \w in place of \d You might also want to make it a requirement that the item occurs at the end. In which case, the following will suffice: alert(s.replace(/ \([\d]*\)$/,'')); You'll note that none of the above references jQuery. This is something that can be achieved with pure JavaScript.
unknown
d19195
test
I agreed with the experts that we should not go for so many partitions in a table. Also I would like to quote this as most of the nodes are unix/linux based and we can not create folder or file name having length greater than 255 bytes. That may be the reason you are getting this error, as partition is a folder only. Linux has a maximum filename length of 255 characters for most filesystems (including EXT4), and a maximum path of 4096 characters. eCryptfs is a layered filesystem.
unknown
d19196
test
Try This Query $query = (new yii\db\Query()) ->select('id, username, auth_assignment.created_at') ->from('user') ->innerJoin('auth_assignment','user.id=auth_assignment.user_id') ->innerJoin('auth_item','auth_item.name = auth_assignment.item_name') ->where([ 'auth_item.name' => 'Admin' ])->all();
unknown
d19197
test
You have to add Custom page for Change password page also. I thin you have added Custom Page only for Forgot password page.
unknown
d19198
test
db.getCollection("orders").aggregate(Arrays.asList(new Document("$group", new Document("_id", "$name").append("total", new Document("$sum", "$count"))))); Hopes this will help.
unknown
d19199
test
You can do it this way: case = str.lower # Take the lower() method of the str class. case('UPPERCASE') # pass your string as the first argument, which is self. In this case, Python being explicit about self being the first argument to methods makes this a lot clearer to understand.
unknown
d19200
test
Look up how to set up models and their relationships using Eloquent ORM: http://laravel.com/docs/database/eloquent Specifically http://laravel.com/docs/database/eloquent#relationships You should have three models, Thread, Post and User (change poster_userid to user_id... or you can keep it but I wouldn't suggest it... just keep things simple. You could also use author_id or maybe even poster_id if that floats your boat.. just be sure to change 'user_id' out with what you choose) //application/models/User.php class User extends Eloquent { public function posts() { return $this->has_many('Post', 'user_id'); } } and //application/models/Post.php class Post extends Eloquent { public function author() { return $this->belongs_to('User', 'user_id'); } public function thread() { return $this->belongs_to('Thread', 'thread_id'); } } and //application/models/Thread.php class Thread extends Eloquent { public function posts() { return $this->has_many('Post', 'thread_id'); } } and instead of $query = DB::table('threads')->where('title', '=', $title)->first(); //Do we have this thread? if(!$query) {return Redirect::to('entry/suggest');} //We have? so lets rock it! $view->title = $query->title; //we get the title. $thread_id = $query->id; //getting posts. $posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get(); I would just put $thread = Thread::where('title', '=', $title)->first(); if(!$query) {return Redirect::to('entry/suggest');} $posts = $thread->posts()->get(); //or if you want to eager load the author of the posts: //$posts = $thread->posts()->with('author')->get(); Then in your view you can look up the user's name by the following: $post->author->username; Easy peezy. A: With Eloquent you can do this in multiple ways. First, you can add a method to your post model that retrieves the related data. This approach will create a new query for each post, so it's normally not the best choice. class Post extends Eloquent { public function user() { return $this->has_one('User'); } } Second, you can modify your initial query to join your desired data and avoid creating undo queries. Know as "Eager Loading". // Example from Laravel.com foreach (Book::with('author')->get() as $book) { echo $book->author->name; }
unknown