_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d3601
train
Please check out the Storage category in the AWS Amplify library. There's some setup/configuration to do (as noted in that guide), but the actual upload will look like this: Amplify.Storage.uploadFile( "remoteS3Key", localFile, result -> Log.i("Demo", "Successfully uploaded: " + result.getKey()), failure -> Log.e("Demo", "Upload failed", failure) );
unknown
d3602
train
Try this: SELECT a.month, a.courses, b.absences FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month, COUNT(*) AS courses FROM Course c GROUP BY month) a LEFT JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month, COUNT(*) AS absences FROM Absence a LEFT JOIN Course c ON a.course_id = c.id GROUP BY month) b ON a.month = b.month; This does two subqueries, one to find the count of courses and one for absences. Then you join them by the month. It should give you what you are looking for. A: You should be able to do this with inline views: SELECT c.month, c.courses, a.absences FROM ( SELECT DATE_FORMAT(date, "%M") AS month, COUNT(*) AS courses FROM Course GROUP BY month ) AS c JOIN ( SELECT DATE_FORMAT(date, "%M") AS month, COUNT(*) AS absences FROM Absence GROUP BY month ) AS a ON a.month = c.month ORDER BY c.month
unknown
d3603
train
In this case, it is preferable to use a List<Integer> instead of int[] List<Integer> arr = new ArrayList<Integer>(); Random random = new Random(); int randonint = arr.remove(random.nextint(arr.getSize())); Every time this code is runned, it will grab a random int from the list arr, then you can add it to a different List/Array So, if you want to take all values from one list, and randomly place them to 3 other lists, use the following code: List<Integer> arr1 = new ArrayList<Integer>(); List<Integer> to1 = new ArrayList<Integer>(); List<Integer> to2 = new ArrayList<Integer>(); List<Integer> to3 = new ArrayList<Integer>(); Random random = new Random(); for (int i = 1 ; i <= 10 ; i++) { arr1.add(i); } for (int count = 0 ; count < arr1.size() ; count++) { List<Integer> arr = new ArrayList<Integer>(); int randomvalue = arr.remove(random.nextint(arr.getSize())); switch (random.nextInt(3)) { case 0: to1.add(randomvalue); case 1: to2.add(randomvalue); case 2: to2.add(randomvalue); } } A: public static void GenerateRandomArray() { var inputArray = new[] {1, 2, 3, 4}; var outputArray = GetRandomArray(inputArray); PrintArray(outputArray); } private static void PrintArray(int[,] outputArray) { for (var i = 0; i < outputArray.GetLength(0); i += 1) { for (var j = 0; j < outputArray.GetLength(1); j += 1) { Console.Write(outputArray[i, j]); } Console.WriteLine(); } } private static int[,] GetRandomArray(int[] inputArray) { var lengthOfArray = inputArray.Length; var outputArray = new int[lengthOfArray,lengthOfArray]; for (var i = 0; i < lengthOfArray; i++) { var counterShifter = i; for (var j = 0; j < lengthOfArray;j++) { outputArray[i, j] = inputArray[counterShifter]; counterShifter = counterShifter + 1 < lengthOfArray ? counterShifter + 1 : 0; } } return outputArray; }
unknown
d3604
train
I just did a test (using ICMP rule) , you have to add a rule in the security group as you said. you should add it normally, and set the source to 1.2.3.4/32 (following your example). please note that I am using Elastic IP in my tests. A: According to the docs, it should also be possible to list that security group as its own source. This would permit the loopback even if the IP address changes due to a stop/start. Another security group. This allows instances associated with the specified security group to access instances associated with this security group. This does not add rules from the source security group to this security group. You can specify one of the following security groups: * *The current security group *A different security group for the same VPC *A different security group for a peer VPC in a VPC peering connection
unknown
d3605
train
To see whether the element has class .price, use the $.hasClass() method. $(this).hasClass("price"); A: You could combine both your tests into a single jQuery command: if( $(e.target).is('.price, a') ) { .... } That tests if the target is either has the class price, or is an a tag, or is both. If you wanted to test that it was an a tag and had the price class, you would use this: if( $(e.target).is('a.price') ) { .... } Update: I may have misread your question. If you were going to add this second test to the same if test, then use my code. If you wanted to add a else if then use the .hasClass method as explained by the other answers. A: you can try: $(this).attr("class"); but this will return you names of all the classes applied to the element.
unknown
d3606
train
(Duplicated from https://social.msdn.microsoft.com/Forums/windowsapps/en-US/6ce9be89-8b14-46fa-b3d5-622bef0adb81/xaml-touch-events-dont-work-properly?forum=winappswithnativecode ) That sounds like correct behaviour. The mouse is a single pointer, not separate pointers for the separate buttons. So long as any button is down the pointer is pressed, and you can check the state to see which buttons are down. If you can explain what you are actually trying to do we may be able to provide more directed help. I suspect you'll be best off looking at the pointer state in your update loop rather than waiting for pointer events, but it depends on the ultimate goal.
unknown
d3607
train
You have to setup DynamoDB streams. A lambda function attached to the stream is going to analyze db changes for related to the specific item and then perform other actions specific to your application.
unknown
d3608
train
It looks like this project you found is fairly old and is using older dependencies. You would need to go into your SDK manager and install SDK version 22 (Lollipop MR1). You could also fork the project and update it to use API version 24 so it works with your project. A: <uses-feature android:name="android.software.leanback" android:required="false" /> <uses-feature android:name="android.hardware.touchscreen" android:required="true" /> Just place this, it runs in mobile devices. A: Please check my fork, I fixed the build issue and updated the build configuration to android 30. https://github.com/moaz-cliqz/MaterialLeanBack
unknown
d3609
train
Posting the solution which I implemented as a work around. Turns out that you cannot access angular merge field values inside visualforce components. So instead of manipulating(segregating input into key-value pair) values inside angular controller, I have to push the logic to apex controller. <apex:component controller="RegistrationController" access="global"> <apex:repeat value="{!ObjectApiFieldsetMap}" var="apiName"> <c:FieldSetComponent objectAPIName="{!apiName}" fieldSet="{!ObjectApiFieldsetMap[apiName]}" cid="{!apiName}{!ObjectApiFieldsetMap[apiName]}" columns="1" textAlign="center"> </c:FieldSetComponent> </apex:repeat> </apex:component> And in my apex controller i.e RegistrationController , I have set the logic to segregate key values from a map input which I'm using inside visualforce component global class RegistrationController { global Map<String,String> ObjectApiFieldsetMap { get { ObjectApiFieldsetMap = arrangeApiFieldSetsByOrder(); return ObjectApiFieldsetMap; } set; } global Map<String,String> arrangeApiFieldSetsByOrder() { Map<String,String> ObjectApiFieldsetMap = new Map<String,String>(); /* logic for segregation */ return ObjectApiFieldsetMap; } }
unknown
d3610
train
One thing you can try is to have a CustomValidator(see here) check that both textboxes are not empty. Then validate both textboxes with a regular expression. The expression should check for either a valid entry OR a blank field. A: You can create a CustomValidator and handle it there http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic7
unknown
d3611
train
Since you are assigning the return value of the method invocation to a variable, this now becomes scripted, and you will need to encapsulate the step within a script block for declarative DSL: pipeline { agent any stages { stage('Hello') { steps { echo 'Hello World' script { result=sh(script:'ls -al', returnStdout: true) } } } } } A: The shell commands must be run inside a sh block in a declarative pipeline. eg: pipeline { agent any stages { stage('Hello') { steps { sh 'echo "Hello World"' result=sh(script:'ls -al', returnStdout: true) } } } } You can also refer to https://www.jenkins.io/doc/pipeline/tour/running-multiple-steps/ for more information. A: do something like this pipeline { agent any stages { stage('Hello') { steps { sh 'echo Hello World' scripts { result = sh(script:'ls -al', returnStdout: true) } } } } }
unknown
d3612
train
Try this: <Switch android:id="@+id/calendar_selection_switch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_centerVertical="true" android:layout_gravity="end|center_vertical" android:layout_marginStart="10dp" android:minHeight="40dp" android:minWidth="80dp" android:textOn="" android:textOff="" android:switchMinWidth="48.0sp" android:thumb="@drawable/switch_selector" android:track="@drawable/switch_track" android:checked="false"/> switch_selector.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true"> <shape android:shape="rectangle" android:visible="true" android:useLevel="false"> <gradient android:startColor="@color/white" android:endColor="@color/white" android:angle="270"/> <corners android:radius="14.0sp"/> <size android:width="28.0sp" android:height="28.0sp" /> <stroke android:width="4.0sp" android:color="#11000000"/> </shape> </item> <item android:state_checked="false"> <shape android:shape="rectangle" android:visible="true" android:dither="true" android:useLevel="false"> <gradient android:startColor="@color/white" android:endColor="@color/white" android:angle="270"/> <corners android:radius="16.0sp"/> <size android:width="28.0sp" android:height="28.0sp" /> <stroke android:width="2.0sp" android:color="#11000000"/> </shape> </item> </selector> switch_track.xml: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:visible="true" android:useLevel="false"> <gradient android:startColor="@color/white" android:endColor="@color/white" android:angle="270"/> <stroke android:width="2.0sp" android:color="#11000000"/> <corners android:radius="14.0sp"/> <size android:width="42.0sp" android:height="28.0sp" /> </shape> Then in code you can do: aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { aSwitch.setTrackResource(R.drawable.switch_track_off); } else { aSwitch.setTrackResource(R.drawable.switch_track); } } }); switch_track_off.xml: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:visible="true" android:useLevel="false"> <gradient android:startColor="#00A4FD" android:endColor="#00A4FD" android:angle="270"/> <stroke android:width="2.0sp" android:color="#00A4FC"/> <corners android:radius="14.0sp"/> <size android:width="42.0sp" android:height="28.0sp" /> </shape> You can change the colors and other styles as you wish. As far as I know this is the only reliable way to make Switch look and feel same in all Android versions anywhere in the app. Please leave a comment if there is any better suggestion. A: Use this <Switch android:id="@+id/switchCalls" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:textOff="" android:textOn="" />
unknown
d3613
train
Model: namespace MvcApplicationrazor.Models { public class CountryModel { public List<State> StateModel { get; set; } public SelectList FilteredCity { get; set; } } public class State { public int Id { get; set; } public string StateName { get; set; } } public class City { public int Id { get; set; } public int StateId { get; set; } public string CityName { get; set; } } } Controller: public ActionResult Index() { CountryModel objcountrymodel = new CountryModel(); objcountrymodel.StateModel = new List<State>(); objcountrymodel.StateModel = GetAllState(); return View(objcountrymodel); } //Action result for ajax call [HttpPost] public ActionResult GetCityByStateId(int stateid) { List<City> objcity = new List<City>(); objcity = GetAllCity().Where(m => m.StateId == stateid).ToList(); SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0); return Json(obgcity); } // Collection for state public List<State> GetAllState() { List<State> objstate = new List<State>(); objstate.Add(new State { Id = 0, StateName = "Select State" }); objstate.Add(new State { Id = 1, StateName = "State 1" }); objstate.Add(new State { Id = 2, StateName = "State 2" }); objstate.Add(new State { Id = 3, StateName = "State 3" }); objstate.Add(new State { Id = 4, StateName = "State 4" }); return objstate; } //collection for city public List<City> GetAllCity() { List<City> objcity = new List<City>(); objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" }); objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" }); objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" }); objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" }); objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" }); objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" }); return objcity; } View: @model MvcApplicationrazor.Models.CountryModel @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> <script language="javascript" type="text/javascript"> function GetCity(_stateId) { var procemessage = "<option value='0'> Please wait...</option>"; $("#ddlcity").html(procemessage).show(); var url = "/Test/GetCityByStateId/"; $.ajax({ url: url, data: { stateid: _stateId }, cache: false, type: "POST", success: function (data) { var markup = "<option value='0'>Select City</option>"; for (var x = 0; x < data.length; x++) { markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>"; } $("#ddlcity").html(markup).show(); }, error: function (reponse) { alert("error : " + reponse); } }); } </script> <h4> MVC Cascading Dropdown List Using Jquery</h4> @using (Html.BeginForm()) { @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" }) <br /> <br /> <select id="ddlcity" name="ddlcity" style="width: 200px"> </select> <br /><br /> }
unknown
d3614
train
Follow advice listed in this railscast <%= javascript_tag do %> $('#createhotelModal').modal('toggle') <% end %>
unknown
d3615
train
Arrays are reference types, not value types. That means that the variable, examplearray doesn't actually contain 1280 bits of data, it just contains a reference (sometimes also referred to as a pointer) to the actual data, which is stored elsewhere (for the purposes of this post, it doesn't matter where "elsewhere" actually is). Passing that variable to a method, as you have done there, is only copying that reference (which is 32 or 64 bits, depending on the system), not the underlying 1280 bits of data.
unknown
d3616
train
Make the IDs unique. Here is the below I tried and worked <script> function desactivacasillas() { var formularioprincipal = document.getElementById("troncocomun"); var primerelemento = document.getElementById("1").value; if (document.getElementById("1").value < 6) { var checkbox1 = document.getElementById("checkbox2"); checkbox1.disabled = true; } } </script> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" value="6" onkeydown="return validarnumero(event)" onkeypress="return compruebacampo(event,this)" onkeyup="desactivacasillas(event)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62"> </td> </tr> </table> A: Try this <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script> function desactivacasillas(args) { if (document.getElementById("1").value.length < 6) { $("#checkbox2").attr("disabled", true); } else { $("#checkbox2").attr("disabled", false); } } </script> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" onkeyup="desactivacasillas(this.value)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62"> </td> </tr> </table> </body> </html> Feel free to ask anything if you don't understand the above program. A: Try this. Use on load function in java script to disable check box while loading. and use parse Int function because input returns value as string. change the ID's of check boxes. ID's are always Unique. <script> function disableCheckbox(){ document.getElementById("checkbox2").disabled = true; } function desactivacasillas() { var formularioprincipal = document.getElementById("troncocomun"); var primerelemento = document.getElementById("1").value; if (parseInt(document.getElementById("1").value,10) > 6) { document.getElementById("checkbox2").disabled = false; } } </script> <body onload="disableCheckbox();"> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" onkeyup="desactivacasillas(event)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62"> </td> </tr> </table> </body>
unknown
d3617
train
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you: String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new); A: You can simply do it by creating an ArrayList and then converting it to the String Array. Here is a sample code to get you started: public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("notepad.txt")); List<String> outputList = new ArrayList<>(); String input = null; while (in.hasNextLine() && null != (input = in.nextLine())) { outputList.add(input); } String[] outputArray = new String[outputList.size()]; outputArray = outputList.toArray(outputArray); in.close(); } A: Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this - List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
unknown
d3618
train
I know this is an old question, but it's ranking high in Google results, so I figured I'd answer it anyway. Make sure you're not running any code in the layout page's codebehind that calls and then closes SPContext.Current.Web. I had this exact behavior and that was the culprit To test, add a different web part to a default page layout. If it adds, then it's either your web part or your code behind. If you can't add any web parts to your custom layout, it's your code behind. If it's just your web part, it's your web part. Remember, SPContext.Current.Web returns a reference to the current SPWeb object. SharePoint will close the object itself when it's done, and closing it early can cause "unpredictable behavior." A: We had the same problem with Firefox some time ago, but the problem disappeared when we installed SP2 for SharePoint 2007. The only thing that surprises me is that you also have the problem with IE.
unknown
d3619
train
Use Device.OpenUri and pass it the appropriate URI, combined with Device.OnPlatform to format the URI per platform string url; Device.OnPlatform(iOS: () => { url = String.Format("http://maps.apple.com/maps?q={0}", address); }, Android: () => { url = String.Format("http://maps.google.com/maps?q={0}", address); }); Device.OpenUri(url); A: As of Xamarin.Forms v4.3.0.908675 (probably v4.3.0) Device.OpenUri is deprecated and you should use Launcher.TryOpenAsync from Xamarin.Essentials instead. Although you will find it troublesome, or at least I did. A: Use Below code, and add namespaces Xamarin.Essentials and Xamarin.Forms if (Device.RuntimePlatform == Device.iOS) { // https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html await Launcher.OpenAsync("http://maps.apple.com/?daddr=San+Francisco,+CA&saddr=cupertino"); } else if (Device.RuntimePlatform == Device.Android) { // opens the 'task chooser' so the user can pick Maps, Chrome or other mapping app await Launcher.OpenAsync("http://maps.google.com/?daddr=San+Francisco,+CA&saddr=Mountain+View"); } else if (Device.RuntimePlatform == Device.UWP) { await Launcher.OpenAsync("bingmaps:?rtp=adr.394 Pacific Ave San Francisco CA~adr.One Microsoft Way Redmond WA 98052"); }
unknown
d3620
train
Since cell is limited to 50,000 characters, using CONCATENATE is not possible. Alternative solution is to use Google Apps Script's custom function. The good thing about Apps Script is it can handle millions of string characters. To create custom function: * *Create or open a spreadsheet in Google Sheets. *Select the menu item Tools > Script editor. *Delete any code in the script editor and copy and paste the code below. *At the top, click Save. To use custom function: * *Click the cell where you want to use the function. *Type an equals sign (=) followed by the function name and any input value — for example, =myFunction(A1) — and press Enter. *The cell will momentarily display Loading..., then return the result. Code: function myFunction(text) { var arr = text.flat(); var newStr = arr.join(' '); var slicedStr = stringChop(newStr, 50000); return [slicedStr]; } function stringChop(str, size){ if (str == null) return []; str = String(str); size = ~~size; return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str]; } Example: Based on your sample spreadsheet, there are 4 rows that matches the criteria of the filter and each cell contains 38,976 characters, which is 155,904 characters in total. Dividing it by 50,000 is 3.12. The ceiling of 3.12 is 4 which means we have 4 columns of data. Usage: Paste this in cell E1: =myFunction(FILTER(C1:C, B1:B=A1)) Output: Reference: * *Custom Function
unknown
d3621
train
Here is an example of what I meant on my comment. I moved most of the calculations out of the draw, in setup we load the spheres array with the positions and an initial color then the setInterval(changeColor, 500) changes the color, on this case is just something random but you could do the same with data coming from a json like you are doing. colors = ["red", "blue", "green", "cyan", "white", "black", "yellow"] function setup() { spheres = [] forRange(x => forRange(y => forRange(z => { color = "red" spheres.push({ x, y, z, color }) }))) createCanvas(windowWidth, windowHeight, WEBGL); frameRate(500); document.oncontextmenu = () => false; setInterval(changeColor, 500) } function changeColor() { spheres.forEach(obj => { obj.color = colors[int(random(colors.length))] }) } function forRange(fn) { const cubeSpacing = 120 for (let i = -250; i <= 250; i += cubeSpacing) { fn(i); } } function draw() { background(155); translate(0, 0, -500); rotateY(millis() / 2000); rotateX(millis() / 8000); spheres.forEach(obj => { noStroke() push(); translate(obj.x, obj.y, obj.z); fill(obj.color) sphere(18) pop(); }) } Here is that in action: https://raw.githack.com/heldersepu/hs-scripts/master/HTML/p5_spheres.html no-refresh and no flickers (at least not in google chrome, I only tested there)
unknown
d3622
train
I think you can use fitdistr %Generate data r=randn(100,1); [counts,centers]=hist(r,20) %r=Data in your case %fit a Gaussian pd=fitdist(r(:),'normal') pd = NormalDistribution Normal distribution mu = 0.0700439 [-0.111376, 0.251463] sigma = 0.914313 [0.802773, 1.06213] x=-3:0.1:3; PDF=pdf(pd,x); %PDF is a vector of y values: it's our fit %overplot PDF=PDF/max(PDF); %scale to y axis y=ylim; PDF=PDF*y(2); hold on plot(x,PDF,'r-','LineWidth',2) hold off
unknown
d3623
train
"{{" and "}}" A: What I think you want is this... string formatString = @" using System; public class ClassName {{ public double TheFunction(double input) {{ {0} }} }}"; string entireClass = string.Format(formatString, userInput); A: Escape them by doubling them up: string s = String.Format("{{ hello to all }}"); Console.WriteLine(s); //prints '{ hello to all }' From http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1 A: Double the braces: string.Format("{{ {0} }}", "Hello, World"); would produce { Hello, World } A: Be extra extra cautious in who has access to the application. A better solution might be to create a simple parser that only expects a few, limited, commands.
unknown
d3624
train
You should specify the status=… [Django-doc] code in your render call, this is by default a 200: def error_404(request, exception): return render(request,'MyApp/404.html', status=404)
unknown
d3625
train
You'll want to use the React Native component instead of standard HTML tags. Instead of styled.div, you'll use styled.View. Also you have to use react native's Text component in replace of standard HTML tags that would hold textual data such as <H1>. So, this is what your code should translate to import * as React from 'react' import { Text } from 'react-native' import styled from 'styled-components/native' export default class View extends React.PureComponent { render() { return( <Container> <Text>Hey</Text> </Container> ) } } const Container = styled.View
unknown
d3626
train
In function addArray you keep recreating the array with the line: parent::$this->arraybase(); Remove this line and call arraybase when you want to create it. A: Well, first off, you don't need to parent::$this->arraybase(). Just do $this->arraybase(). In fact, I'm not even sure your way is even valid syntax. But I digress. As for your specific problem, you can either: * *Add a constructor (and remove the ->arraybase() call from addArray()): public function __construct() { $this->array = new ArrayObject(); } *Add an if check around the call to ->arraybase(): public function addArray($value) { if (!isset($this->array) || !is_object($this->array)) { $this->arraybase(); } ... } Personally, I'd do #1. It's going to be more reliable, faster, and more in keeping with OOP paradigms. EDIT: Adding Constructor Info So, if your base class has this constructor: public function __construct($some, $vars) { ...... } You would do this in your extending class: public function __construct($some, $vars) { parent::__construct($some, $vars); $this->array = new ArrayObject(); } NOTE: Don't call parent::__construct() unless one of the parents has a __construct method... A: Why do you want to set a wrapper around ArrayObject? If it's for adding the possibility of chaining method calls, then you'd better extend ArrayObject: <?php class MyArrayObject extends ArrayObject { public function append($value) { parent::append($value); return $this; } } $ao = new MyArrayObject(); $ao->append('a')->append('b')->append('c'); var_dump($ao->getArrayCopy()); /* array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } */
unknown
d3627
train
Try the below approach to get the Id,Title and body from that webpage. Sub Get_data() Dim HTTP As New XMLHTTP60, res As Variant Dim r As Long, v As Long With HTTP .Open "GET", "https://jsonplaceholder.typicode.com/posts", False .setRequestHeader "User-Agent", "Mozilla/5.0" .send res = Split(.responseText, "id"":") End With r = UBound(res) For v = 1 To r Cells(v, 1) = Split(res(v), ",")(0) Cells(v, 2) = Split(Split(Split(res(v), "title"":")(1), """")(1), """,")(0) Cells(v, 3) = Split(Split(Split(res(v), "body"":")(1), """")(1), """,")(0) Next v End Sub Reference to add to the library: Microsoft XML, V6.0
unknown
d3628
train
Mysql doesn't support TOP that is for SQL Server. Instead of using TOP you can use mysql LIMIT so your query would be: SELECT `id` FROM radcheck ORDER BY `id` DESC LIMIT 1; A: You do not have to use single quotes around column names. if you need to escape it use backticks. And TOP is not mysql syntax. You have to use limit SELECT `id` FROM radcheck ORDER BY `id` DESC limit 1 Do not longer use the depricated mysql_* API. Use mysqli_* or PDO A: Remove the 's around field names - "SELECT TOP 1 id FROM radcheck ORDER BY id DESC"; But as Daan told it will not work for mysql, then ORDER & LIMIT will do the trick. "SELECT id FROM radcheck ORDER BY id DESC LIMIT 1"; A: i hope you never mind trying this pattern Select id from radcheck WHERE id=1 ORDER BY 'id' DESC ;
unknown
d3629
train
_low] RewriteCond %{HTTP_USER_AGENT} (acer\ s100|android|archos5|blackberry9500|blackberry9530|blackberry9550|cupcake|docomo\ ht\-03a|dream|htc\ hero|htc\ magic|htc_dream|htc_magic|incognito|ipad|iphone|ipod|lg\-gw620|liquid\ build|maemo|mot\-mb200|mot\-mb300|nexus\ one|opera\ mini|samsung\-s8000|series60.*webkit|series60/5\.0|sonyericssone10|sonyericssonu20|sonyericssonx10|t\-mobile\ mytouch\ 3g|t\-mobile\ opal|tattoo|webmate|webos) [NC] RewriteRule .* - [E=W3TC_UA:_high] RewriteCond %{HTTPS} =on RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{SERVER_PORT} =443 RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=W3TC_ENC:.gzip] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{QUERY_STRING} ="" RewriteCond %{REQUEST_URI} \/$ RewriteCond %{REQUEST_URI} !(\/wp-admin\/|\/xmlrpc.php|\/wp-(app|cron|login|register|mail)\.php|wp-.*\.php|index\.php) [NC,OR] RewriteCond %{REQUEST_URI} (wp-comments-popup\.php|wp-links-opml\.php|wp-locations\.php) [NC] RewriteCond %{HTTP_COOKIE} !(comment_author|wp-postpass|wordpress_\[a-f0-9\]\+|wordpress_logged_in) [NC] RewriteCond "/home/btk1sk/public_html/wp-content/w3tc/pgcache/$1/_index%{ENV:W3TC_UA}%{ENV:W3TC_SSL}.html%{ENV:W3TC_ENC}" -f RewriteRule (.*) "/wp-content/w3tc/pgcache/$1/_index%{ENV:W3TC_UA}%{ENV:W3TC_SSL}.html%{ENV:W3TC_ENC}" [L] </IfModule> # END W3TC Page Cache # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress A: I think if you change this line: RewriteCond %{REQUEST_URI} !(\/wp-admin\/|\/xmlrpc.php|\/wp-(app|cron|login|register|mail)\.php|wp-.*\.php|index\.php) [NC,OR] to this: RewriteCond %{REQUEST_URI} !(\/zencart\/|\/wp-admin\/|\/xmlrpc.php|\/wp-(app|cron|login|register|mail)\.php|wp-.*\.php|index\.php) [NC,OR] you'll be able to access the contents of your 'zencart' directory. A: We solved that creating a Wordpress page using the same "url". But as you said, it's not a dynamic solution. The fact is that we have not many folders at the same level of WP index :o... Greetings!
unknown
d3630
train
http://technet.microsoft.com/en-us/library/jj219429.aspx This explains the process in detail. The process is slightly different depending on which office app you're building for. You can do task panes in... Excel, Word, Project and PowerPoint. Here is a link to tutorials and samples... http://msdn.microsoft.com/en-us/library/office/fp142152.
unknown
d3631
train
Your issue: * *PHP serves on page request the respective date values. *You store those values into JS *You loop all over again the same values. Therefore the loop works but the values are unchanged. Instead what you should: * *Create a var D = new Date("<?php echo date('D M d Y H:i:s O');?>"); outside of your function. *On every timeout, add one second to your initial PHP Date DATE = PHP:initial + JS:now - JS:initial function zero(n) { return n > 9 ? n : "0" + n; } var months = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря", ]; var jsDate = new Date(); // Store JS time // I'll hardcode a date string for demo purpose: var phpDate = new Date("Sun Sep 09 2018 23:59:55 +0000"); // You, use this instead: // var phpDate = new Date("<?php echo date('D M d Y H:i:s O');?>"); function clock() { var diff = +new Date() - +jsDate; // Get seconds difference var date = new Date(+phpDate + diff); // Add difference to initial PHP time var y = date.getFullYear(), M = date.getMonth(), d = zero(date.getDate()), h = zero(date.getHours()), m = zero(date.getMinutes()), s = zero(date.getSeconds()); document.getElementById("doc_time").innerHTML = ` Дата: ${d} ${months[M]} ${y}. &emsp; Время: ${h}:${m}:${s} `; setTimeout(clock, 1000); } clock(); <div id="doc_time"></div> A: The php code runs once on page load so hour, minute and seconds will always remain same in each call of clock() function. If you really need to do such a thing, you have to use AJAX to request a php script each second to get current time from server but remember these requests will have delay and also can put a huge load on server if multiple users open the page at the same time.
unknown
d3632
train
information_schema.COLUMNS contains all the columns in your DB so you can query for a specific pattern in the name like this: select c.COLUMN_NAME from information_schema.COLUMNS as c where c.TABLE_NAME = 'mytable' and c.COLUMN_NAME like 'PREFIX_%'; A: You are going to have to construct the query with a query and use EXECUTE. Its a little easier w/ 8.3+. Here's a query that will run on 8.1 and pulls all columns starting with r% from the film table $$ DECLARE qry TEXT; BEGIN SELECT 'SELECT ' || substr(cols, 2, length(cols) - 2) || ' FROM film' INTO qry FROM ( SELECT array( SELECT quote_ident(column_name::text) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'film' AND column_name LIKE 'r%' ORDER BY ordinal_position )::text cols -- CAST text so we can just strip off {}s and have column list ) sub; EXECUTE qry; END; $$ A: To me it looks like the syntax description of PostgreSQL 8.x's SELECT statement does not allow this. A SELECT list must be an expression or list of expressions, and the syntax for expressions does not seem to allow for wildcarded partial column names. Share and enjoy.
unknown
d3633
train
By adding scalaSource in Test := baseDirectory.value / "test" "/scala", to my Build.scala file, I've been able to make the "scala" folder a test source, but the parent "test" folder was still also a test source: As far as I could tell, this is a setting inherited from Play, since if I removed the .enablePlugins(PlayScala) code, the "test" folder stops being a test source. Following the instructions in https://www.playframework.com/documentation/2.5.x/Anatomy#Default-SBT-layout, I disabled the play layout, and then manually added the source and resource directories, which I copied from https://github.com/playframework/playframework/blob/master/framework/src/sbt-plugin/src/main/scala/play/sbt/PlayLayoutPlugin.scala#L9, only modifying the test source, and adding my own resource folders. My modified Build.scala file is now: val main = Project("Mp3Streamer", file(".")) .enablePlugins(PlayScala) .disablePlugins(PlayLayoutPlugin) .settings( target := baseDirectory.value / "target", sourceDirectory in Compile := baseDirectory.value / "app", // My change sourceDirectory in Test := baseDirectory.value / "test" / "scala", resourceDirectory in Compile := baseDirectory.value / "conf", scalaSource in Compile := baseDirectory.value / "app", // My change scalaSource in Test := baseDirectory.value / "test" / "scala", // I've added this resource resourceDirectory in Test := baseDirectory.value / "test" / "resources", javaSource in Compile := baseDirectory.value / "app", sourceDirectories in(Compile, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Compile).value), sourceDirectories in(Test, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Test).value), // sbt-web sourceDirectory in Assets := (sourceDirectory in Compile).value / "assets", sourceDirectory in TestAssets := (sourceDirectory in Test).value / "assets", resourceDirectory in Assets := baseDirectory.value / "public", // Native packager sourceDirectory in Universal := baseDirectory.value / "dist", // Everything else is the same as the original Build.scala file Honestly, this feels so hacky that I'll probably end up modifying my directory structure to match Play's default... But it's the principle that counts!
unknown
d3634
train
There are some requirements for streaming to work. The file might not be encoded "correctly" http://developer.android.com/guide/appendix/media-formats.html For video content that is streamed over HTTP or RTSP, there are additional requirements: * *For 3GPP and MPEG-4 containers, the moov atom must precede any mdat atoms, but must succeed the ftyp atom. *For 3GPP, MPEG-4, and WebM containers, audio and video samples corresponding to the same time offset may be no more than 500 KB apart. To minimize this audio/video drift, consider interleaving audio and video in smaller chunk sizes. You might be on an older version of Android that doesn't support it HTTP progressive streaming was only added in 2.2, HTTPS only supported 3.0+, Live streaming is only supported in even later versions. A: I have work on YouTube Video streaming and that was without downloading video. This will only work if you will play YouTube video . You have to use YouTube API and using that you can easily manage your task. You have to enable YouTube service and using Developer Key you can access YouTube API. How to use YouTube API ? You can Find Here Sample code for same. Out of that sample example i have use PlayerViewDemoActivity.java & YouTubeFailureRecoveryActivity.java and that XMl view as per the needs. Play Video public class PlayerViewDemoActivity extends YouTubeFailureRecoveryActivity { String youtube_id = "_UWXqFBF86U"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playerview_demo); YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); // Replace your developer key youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { player.cueVideo(youtube_id); } } @Override protected YouTubePlayer.Provider getYouTubePlayerProvider() { return (YouTubePlayerView) findViewById(R.id.youtube_view); } } Hope this will be help you,Let me know if you have any query. A: Use Like this: Uri uri = Uri.parse(URL); //Declare your url here. VideoView mVideoView = (VideoView)findViewById(R.id.videoview) mVideoView.setMediaController(new MediaController(this)); mVideoView.setVideoURI(uri); mVideoView.requestFocus(); mVideoView.start(); Another Method: String LINK = "type_here_the_link"; VideoView mVideoView = (VideoView) findViewById(R.id.videoview); MediaController mc = new MediaController(this); mc.setAnchorView(videoView); mc.setMediaPlayer(videoView); Uri video = Uri.parse(LINK); mVideoView.setMediaController(mc); mVideoView.setVideoURI(video); mVideoView.start(); If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this. Hope this will give you some solution. A: For showing buffering you have to put progressbar of ProgressDialog ,... here i post progressDialog for buffering ... pDialog = new ProgressDialog(this); // Set progressbar message pDialog.setMessage("Buffering..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); // Show progressbar pDialog.show(); try { // Start the MediaController MediaController mediacontroller = new MediaController(this); mediacontroller.setAnchorView(mVideoView); Uri videoUri = Uri.parse(videoUrl); mVideoView.setMediaController(mediacontroller); mVideoView.setVideoURI(videoUri); } catch (Exception e) { e.printStackTrace(); } mVideoView.requestFocus(); mVideoView.setOnPreparedListener(new OnPreparedListener() { // Close the progress bar and play the video public void onPrepared(MediaPlayer mp) { pDialog.dismiss(); mVideoView.start(); } }); mVideoView.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { if (pDialog.isShowing()) { pDialog.dismiss(); } finish(); } });
unknown
d3635
train
Windows displays this in the shell by using the Windows Property System in the Win32 API to check the undocumented shell property System.Volume.BitLockerProtection. Your program will also be able to check this property without elevation. If the value of this property is 1, 3, or 5, BitLocker is enabled on the drive. Any other value is considered off. During my search for a solution to this problem, I found references to this shell property in HKEY_CLASSES_ROOT\Drive\shell\manage-bde\AppliesTo. Ultimately, this discovery lead me to this solution. The Windows Property System is a low-level API, but you can use the wrapper that's available in the Windows API Code Pack. Package Install-Package WindowsAPICodePack Using using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Shell.PropertySystem; Code IShellProperty prop = ShellObject.FromParsingName("C:").Properties.GetProperty("System.Volume.BitLockerProtection"); int? bitLockerProtectionStatus = (prop as ShellProperty<int?>).Value; if (bitLockerProtectionStatus.HasValue && (bitLockerProtectionStatus == 1 || bitLockerProtectionStatus == 3 || bitLockerProtectionStatus == 5)) Console.WriteLine("ON"); else Console.WriteLine("OFF"); A: The following COM method combined with reflection works with .NET 6 (and probably older versions) without requiring any external libraries. COM isn't really the most supported path but it is a good alternative. var netFwMgrType = Type.GetTypeFromProgID("Shell.Application", false); var manager = Activator.CreateInstance(netFwMgrType); var c = manager.GetType().InvokeMember("NameSpace", BindingFlags.InvokeMethod, null, manager, new object[] { "C:" }); var self = c.GetType().InvokeMember("Self", BindingFlags.GetProperty, null, c, new object[] { }); var result = self.GetType().InvokeMember("ExtendedProperty", BindingFlags.InvokeMethod, null, self, new object[] { "System.Volume.BitLockerProtection" }); You might need to add this to your csproj file depending on how you build your project. <BuiltInComInteropSupport>true</BuiltInComInteropSupport> The above doesn't work for LOCAL_SYSTEM account for some reason. So here is how you do it when you have admin privileges using WMI. Even though the question is specifically asking without admin, I think this is a good place to have this piece of code. This requires the .NET System.Management library. var result = new ManagementObjectSearcher(@"root\cimv2\security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_Encryptablevolume") .Get().OfType<ManagementObject>() .Where(obj => obj.GetPropertyValue("DriveLetter").ToString() == "C:") .Select(obj => obj.GetPropertyValue("ConversionStatus")) .Cast<uint>() Note that this returns a different code than the other approach. Documented here: https://learn.microsoft.com/en-us/windows/win32/secprov/getconversionstatus-win32-encryptablevolume
unknown
d3636
train
You can convert the variable labels to variable names from within Stata before exporting it to a R or text file. As Ian mentions, variable labels usually do not make good variable names, but if you convert spaces and other characters to underscores and if your variable labels aren't too long, you can re-label your vars with the varlabels quite easily. Below is an example using the inbuilt Stata dataset "cancer.dta" to replace all variable names with var labels--importantly, this code will not try to rename variable with no variable labels. Note that I also picked a dataset where there are lots of characters that aren't useful in naming a variable (e.g.: =, 1, ', ., (), etc)...you can add any characters that might be lurking in your variable labels to the list in the 5th line: "local chars "..." " and it will make the changes for you: ****************! BEGIN EXAMPLE //copy and paste this code into a Stata do-file and click "do"// sysuse cancer, clear desc ** local chars "" " "(" ")" "." "1" "=" `"'"' "___" "__" " ds, not(varlab "") // <-- This will only select those vars with varlabs // foreach v in `r(varlist)' { local `v'l "`:var lab `v''" **variables names cannot have spaces or other symbols, so:: foreach s in `chars' { local `v'l: subinstr local `v'l "`s'" "_", all } rename `v' ``v'l' **make the variable names all lower case** cap rename ``v'l' `=lower("``v'l'")' } desc ****************! END EXAMPLE You might also consider taking a look at Stat Transfer and it's capabilities in converting Stata to R datafiles. A: Here's a function to evaluate any expression you want with Stata variable labels: #' Function to prettify the output of another function using a `var.labels` attribute #' This is particularly useful in combination with read.dta et al. #' @param dat A data.frame with attr `var.labels` giving descriptions of variables #' @param expr An expression to evaluate with pretty var.labels #' @return The result of the expression, with variable names replaced with their labels #' @examples #' testDF <- data.frame( a=seq(10),b=runif(10),c=rnorm(10) ) #' attr(testDF,"var.labels") <- c("Identifier","Important Data","Lies, Damn Lies, Statistics") #' prettify( testDF, quote(str(dat)) ) prettify <- function( dat, expr ) { labels <- attr(dat,"var.labels") for(i in seq(ncol(dat))) colnames(dat)[i] <- labels[i] attr(dat,"var.labels") <- NULL eval( expr ) } You can then prettify(testDF, quote(table(...))) or whatever you want. See this thread for more info. A: R does not have a built in way to handle variable labels. Personally I think that this is disadvantage that should be fixed. Hmisc does provide some facilitiy for hadling variable labels, but the labels are only recognized by functions in that package. read.dta creates a data.frame with an attribute "var.labels" which contains the labeling information. You can then create a data dictionary from that. > data(swiss) > write.dta(swiss,swissfile <- tempfile()) > a <- read.dta(swissfile) > > var.labels <- attr(a,"var.labels") > > data.key <- data.frame(var.name=names(a),var.labels) > data.key var.name var.labels 1 Fertility Fertility 2 Agriculture Agriculture 3 Examination Examination 4 Education Education 5 Catholic Catholic 6 Infant_Mortality Infant.Mortality Of course this .dta file doesn't have very interesting labels, but yours should be more meaningful. A: I would recommend that you use the new haven package (GitHub) for importing your data. As Hadley Wickham mentions in the README.md file: You always get a data frame, date times are converted to corresponding R classes and labelled vectors are returned as new labelled class. You can easily coerce to factors or replace labelled values with missings as appropriate. If you also use dplyr, you'll notice that large data frames are printed in a convenient way. (emphasis mine) If you use RStudio this will automatically display the labels under variable names in the View("data.frame") viewer pane (source). Variable labels are attached as an attribute to each variable. These are not printed (because they tend to be long), but if you have a preview version of RStudio, you’ll see them in the revamped viewer pane. You can install the package using: install.packages("haven") and import your Stata date using: read_dta("path/to/file") For more info see: help("read_dta") A: When using the haven package: if the data set you are importing is heavy, viewing the data in Rstudio might not be optimal. You can instead get a data.frame with column names, column labels and an indicator for whether the column is labelled: d <- read_dta("your_stata_data.dta") vars <- data.frame( "name" = names(d), "label" = sapply(d, function(x) attr(x, "label")) %>% as.character(), "labelled" = sapply(d, is.labelled) ) Note: need to use as.characted in order to avoid NULL in the labels being dropped and therefore ending up with different vector lengths.
unknown
d3637
train
If you were using jq it'd as simple as jq '.[:1] + [{"x":"x", "y":"y"}] + .[1:]' input.json Demo and jq '.[:2] + [{"m":"m", "n":"n"}] + .[2:]' input.json Demo respectively. A: If it's something that you are planning to reuse you can do it in python. #! /usr/bin/env python3 import json import sys j = json.load(sys.stdin) j.insert(int(sys.argv[1]), json.loads(sys.argv[2])) print(j) and you can invoke it passing the position and object as parameters ./json-insert 1 '{"x": "x", "y": "y"}' < input.json A: cat file.json|tr '\n' ' '| sed 's/},/},{"x":"x", "y":"y"},/2'|json_pp [ { "a" : "a", "b" : "b" }, { "c" : "c", "d" : "d" }, { "x" : "x", "y" : "y" }, { "e" : "e", "f" : "f" } ] #-------------------------------------------------------------- cat file.json|tr '\n' ' '| sed 's/},/},{"x":"x", "y":"y"},/2'|json_pp > tmp.json mv tmp.json file.json A: This might work for you (GNU sed & Bash): cat <<\! | sed -Ee '/\}/{x;s/^/x/;/^x{1}$/{x;r /dev/stdin' -e 'x};x}' file { "x": "x", "y": "y" }, ! or: cat <<\! | sed -Ee '/\}/{x;s/^/x/;/^x{2}$/{x;r /dev/stdin' -e 'x};x}' file { "m": "m", "n": "n" }, ! Pipe strings to be inserted via /dev/stdin into a sed invocation, using a counter in the hold space to initiate the placement of the strings. N.B. The r command has to be terminated by a newline, hence the reason for splitting the sed commands into two parts using the -e command option. The strings can be collected in a here-document and passed to /dev/stdin of the following pipe using the cat command.
unknown
d3638
train
Serve App With Express Basically, when you change paths you are moving away from your index.html unless you serve the react app with a server of some kind. Try to setup an express server for index with something like this: const express = require('express') const path = require('path') const port = process.env.PORT || 3000 const app = express() // serve static assets eg. js and css files app.use(express.static(__dirname + '/public')) // Handles all routes app.get('*', function (request, response){ response.sendFile(path.resolve(__dirname, 'public', 'index.html')) }) app.listen(port) console.log("server started on port " + port) You can put this in your root directory as server.js, make sure index is being referred to in the sendFile line (right now assumes index.html is in /public directory), run this with babel-node server.js, and should serve your app on localhost:3000.
unknown
d3639
train
You can make a jquery function, that initializes the value of the input to some text when the document is loaded (this should be your placeholder) and then put this value to "" (nothing) when there is an onclick event in the input. Hope it helps A: Try this JSFiddle. _selector is a custom variable that I've made. Just change the line to the ID of whatever field you want to put this placeholder on. You can chance the _placeholder to contain whatever placeholder text you want inside the field :). I just change the css and html properties of the input field on when the user clicks inside it (or outside). One problem with this technique is that when you post the form, it will think the value's are set (since the value is _placeholder (or "Address" in this example). Your best bet would be to check if the value is equal to your placeholder in the PHP script. If it is you can just tell your script to use "" instead of the var. A: Going with @Hamdi, you can try jQuery. This is a very good article for that.
unknown
d3640
train
With the polled adapter, you can use a Smart Poller to change the selector expression before each poll; call setMessageSelector() on the JmsDestinationPollingSource. You cannot dynamically change the selector on a message-driven adapter; you have to stop the adapter first.
unknown
d3641
train
Try to use "\n" instead of '\n' (or even PHP_EOL predefined constant). Use double quotes. Related: * *What is the difference between single-quoted and double-quoted strings in PHP? *FPDF multicell alignment not working
unknown
d3642
train
you can try like below select ip, count(distinct uid) from table t group by ip A: SELECT uid,COUNT(ip)NoOfVotes FROM (SELECT uid,ip,Serial=ROW_NUMBER() OVER(PARTITION BY ip,uid ORDER BY uid) FROM dbo.tbl_user)A WHERE Serial=1 GROUP BY uid I think this will give you perfect vote counting. Using Row Number actively remove duplicates from same ip,same uid. Voting to multiple uid from same ip is allowed in this query.
unknown
d3643
train
Simple solution is to try to replace your <img src="/LoggedUserHome/GetGender"/> in the view with @{ var d = new PrimeTrekkerEntities1(); var AllGender = new List<string>(from c in d.tbl_Profile select c.sex).ToList(); var Groping = AllGender .GroupBy(i => i) .Select(i => new { sex = i.Key, Count = i.Count() }); //get a count for each var key = new Chart(width: 600, height: 400) .AddSeries( chartType: "pie", legend: "Gender Popularity", xValue: Groping, xField: "sex") .Write("gif"); } And "yes" you don't need action GetGender in this case. More complex solution would be to leave <img src="/LoggedUserHome/GetGender"/> in the view, but make GetGender() action return chart image URL. So, what you can do in GetGender() is somehow render chart into image file and return response that contains the image's path. update: I've updated your example a bit, so it displays data in the chart. Here is what I've got: @{ var AllGender = new List<string>() { "Male", "Female", "Male"}; var Groping = AllGender .GroupBy(i => i) .Select(i => new { sex = i.Key, Count = i.Count() }).ToArray(); //get a count for each var key = new Chart(width: 600, height: 400) .AddSeries( chartType: "pie", legend: "Gender Popularity", xValue: Groping, xField: "sex", yValues: Groping, yFields: "count") .Write("gif"); } There are two main differences with your example: * *Groping is now an array. As far as I understand Chart expects data to be enumerated *I added yValues and yFields parameters, so chart knows what values to use on Y axis
unknown
d3644
train
The purpose of a servlet is to respond to an HTTP request. What you should do is refactor your code so that the logic you want is separated from the other servlet and you can reuse it independently. So, for example, you might end up with a Mailman class, and a MailServlet that uses Mailman to do its work. It doesn't make sense to call a servlet from another servlet. If what you need is to go to a different page after you hit the first one, use a redirect: http://www.java-tips.org/java-ee-tips/java-servlet/how-to-redirect-a-request-using-servlet.html Edit: For example, suppose you have a servlet like: public class MailServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); response.setContentType("text/html"); Message message =new MimeMessage(session1); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(...); message.doSomeOtherStuff(); Transport.send(message); out.println("mail has been sent"); } } Instead, do something like this: public class MailServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); response.setContentType("text/html"); new Mailer().sendMessage("[email protected]", ...); out.println("mail has been sent"); } } public class Mailer { public void sendMessage(String from, ...) { Message message =new MimeMessage(session1); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(...); message.doSomeOtherStuff(); Transport.send(message); } } A: I think this may be what you were originally looking for: a request dispatcher. From the Sun examples documentation: public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("selectedScreen", request.getServletPath()); RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("selectedScreen", request.getServletPath()); RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp"); if (dispatcher != null) dispatcher.forward(request, response); } } This appears to specify a new URL, for a different servlet, JSP, or other resource in the same container, to generate the response instead of the current servlet. From the tutorial here: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags6.html A: You can use forward() method of RequestDispatcher So the code goes as follows: LoginServlet.java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String emailID = "[email protected]"; //Write code to retrieve email id from MySql and store in emailID variable request.setAttribute("emaiID", emailID); RequestDispatcher rd = request.getRequestDispatcher("MailServlet"); rd.forward(request, response); } MailServlet.java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String value = (String) request.getAttribute("emaiID"); pw.println("The value of email id is: " + value); } Let me know if this answer is not clear to you.
unknown
d3645
train
.list_container { direction: rtl; overflow:auto; height: 50px; width: 50px; } .item_direction { direction:ltr; } <div class="list_container"> <div class="item_direction">1</div> <div class="item_direction">2</div> <div class="item_direction">3</div> <div class="item_direction">4</div> <div class="item_direction">5</div> <div class="item_direction">6</div> <div class="item_direction">7</div> <div class="item_direction">8</div> <div class="item_direction">9</div> <div class="item_direction">10</div> <div class="item_direction">11</div> <div class="item_direction">12</div> </div> Working Example: JSFiddle or Cut and paste solution that works for all major browsers (Even Safari) Any height or width will work <style> .list_container { direction: rtl; overflow:auto; height: 50px; width: 50px; } .item_direction { direction:ltr; } </style> <div class="list_container"> <div class="item_direction">1</div> <div class="item_direction">2</div> <div class="item_direction">3</div> <div class="item_direction">4</div> <div class="item_direction">5</div> <div class="item_direction">6</div> <div class="item_direction">7</div> <div class="item_direction">8</div> <div class="item_direction">9</div> <div class="item_direction">10</div> <div class="item_direction">11</div> <div class="item_direction">12</div> </div> Optionally add class="item_direction to each item to change the direction of the text flow back, while preserving the container direction. A: No, you can't change scrollbars placement without any additional issues. You can change text-direction to right-to-left ( rtl ), but it also change text position inside block. This code can helps you, but I not sure it works in all browsers and OS. <element style="direction: rtl; text-align: left;" /> A: Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked. You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1) on a parent <div>, then apply the same transform to reverse a child, "sleeve" element. HTML <div class="parent"> <div class="sleeve"> <!-- content --> </div> </div> CSS .parent { overflow: auto; transform: scaleX(-1); //Reflects the parent horizontally } .sleeve { transform: scaleX(-1); //Flips the child back to normal } Note: You may need to use an -ms-transform or -webkit-transform prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements. A: I have the same problem. but when i add direction: rtl; in tabs and accordion combo but it crashes my structure. The way to do it is add div with direction: rtl; as parent element, and for child div set direction: ltr;. I use this first https://api.jquery.com/wrap/ $( ".your selector of child element" ).wrap( "<div class='scroll'></div>" ); then just simply work with css :) In children div add to css .your_class { direction: ltr; } And to parent div added by jQuery with class .scroll .scroll { unicode-bidi:bidi-override; direction: rtl; overflow: scroll; overflow-x: hidden!important; } Works prefect for me http://jsfiddle.net/jw3jsz08/1/ A: You could try direction:rtl; in your css. Then reset the text direction in the inner div #scroll{ direction:rtl; overflow:auto; height:50px; width:50px;} #scroll div{ direction:ltr; } Untested. A: Here is what I have done to make the right scroll bar work. The only thing needed to be considered is when using 'direction: rtl' and whole table also need to be changed. Hopefully this gives you an idea how to do it. Example: <table dir='rtl'><tr><td>Display Last</td><td>Display Second</td><td>Display First</td></table> Check this: JSFiddle A: There is a dedicated npm package for it. css-scrollbar-side
unknown
d3646
train
import requests import xmltodict url = 'http://192.168.1.8:8060/query/apps' text = requests.get(url).text #content = """ #<?xml version="1.0" encoding="UTF-8"?> #<apps> #<app id="31012" type="menu" #version="2.0.53">Vudu Movie &amp; #TV Store</app> #</apps> #""" text = text.split('\n') text = text[1:] text = ''.join(text) data = xmltodict.parse(text) data = dict(data) for key1, value1 in data.items(): for key2, value2 in value1.items(): if isinstance(value2, list): for item in value2: print(item['@id']) print(item['@type']) print(item['#text'])
unknown
d3647
train
Using your posted data this works for me: Sub Tester() Dim ws As Worksheet, c As Range, rng As Range, arr, proj, impl, rw As Long, v Set rng = Selection 'for example ReDim arr(1 To rng.Rows.Count, 1 To 3) 'size the output array proj = "" impl = "" rw = 0 For Each c In Selection.Cells v = c.value Select Case Len(v) - Len(LTrim(v)) '# of leading spaces Case 4: proj = Trim(v) 'or a range (eg) Case 3 To 7 Case 12: impl = Trim(v) Case 20 rw = rw + 1 arr(rw, 1) = proj arr(rw, 2) = impl arr(rw, 3) = Trim(v) End Select Next c Range("D1").Resize(rw, 3).value = arr 'output the results array End Sub Input/Output:
unknown
d3648
train
So this is what you can do: 1) create a vector of dates to interpolate months <- lapply(X = data$date, FUN = seq.Date, by = "month", length.out = 3) months <- data.frame(date = do.call(what = c, months)) 2) left join you date.frame to the months data.frame to create NAs for extrapolation library(dplyr) monthly_data <- left_join(x = months, y = data, by = "date") 3) use one of na.locf() na.appox() na.spline() to interpolate f.ex StressC library(zoo) monthly_data$StressC <- na.spline(object = monthly_data$StressC) Note: the extrapolations above are * *na.locf() - most recent point *na.appox() - linear *na.spline() - spline (often used in graphics) Run the following (before interpolation) to see the difference: plot(x = monthly_data$StressC, ylab = "StressC", xlab="", xaxt = "n") lines(x = na.locf(monthly_data$StressC), col = "red") lines(x = na.approx(monthly_data$StressC), col = "green") lines(x = na.spline(monthly_data$StressC), col = "blue") Can also do something like this to get gglot: ggplot(monthly_data, aes(x=date)) + geom_point(aes(y = StressC), colour="black") + geom_line(aes(y = na.locf(StressC)), col="red") + geom_line(aes(y = na.spline(StressC)), col="red")
unknown
d3649
train
If possible, you can use directly the LSQCURVEFIT function using Levenberg-Marquardt - method, which is Coder-compatible, with some limitations - see it's documentation that describes the limitations in detail. Under the hood FIT uses LSQCURVEFIT, but in a non-Coder-compatible way.
unknown
d3650
train
Apparently the singleton class has to be explicitly declared public...now it works on both the emulator and the device.
unknown
d3651
train
You might need some checking if there are any keywords in the $keywords variable but here is a solution that works with your current structure. Presuming each keyword in the string is separated by a space: $keywordSeparator = " "; $keywords = explode($keywordSeparator, $keywords); $keywordsWhere = " WHERE keywords LIKE '%" . implode("%' OR keywords LIKE '%", $keywords) . "%'"; $query = "SELECT * FROM questions " . $keywordsWhere; if ($sugg_qs = $db->query($query)) { Edit Paul Spiegel made some good comments (not just pointing out the error in my code:) If you want to avoid partial matches on keywords then you should wrap all keywords in a separator. So to avoid apple matching appliepie you would store the keyword with spaces around the keyword. So apple oranges becomes apple oranges. A search for those keywords would be WHERE keywords LIKE '% apple %' OR keywords LIKE '% oranges %'. However, at that point, you should see performance improvements if you store the keywords in there own table, one keyword per row. A sample table structure for a modified questions table and the new question_keywords table below: -- -- Table structure for table `questions` -- CREATE TABLE IF NOT EXISTS `questions` ( `question_id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(254) NOT NULL, PRIMARY KEY (`question_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Table structure for table `question_keywords` -- CREATE TABLE IF NOT EXISTS `question_keywords` ( `keyword_id` int(11) NOT NULL AUTO_INCREMENT, `question_id` int(11) NOT NULL, `keyword` varchar(50) NOT NULL, PRIMARY KEY (`keyword_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Indexes for table `question_keywords` -- ALTER TABLE `question_keywords` ADD KEY `question_id_keyword` (`question_id`,`keyword`); Some sample data INSERT INTO `questions` (`title`) VALUES ('Question #1'), ('Question #2'), ('Question #3'); INSERT INTO `question_keywords` (`question_id`, `keyword`) VALUES (1, 'apple') ,(2, 'orange') ,(3, 'ILikeFruit') ,(3, 'banana') ,(3, 'grape') ,(3, 'apple'); You can then search like this $keywordSeparator = " "; $keywords = explode($keywordSeparator, $keywords); $keywordsAnd = "'" . implode("','", $keywords) . "'"; $query = " SELECT DISTINCT q.* FROM questions q INNER JOIN question_keywords k ON q.question_id = k.question_id AND k.keyword IN (" . $keywordsAnd . ")"; if ($sugg_qs = $db->query($query)) { The search might seem more complicated since we now need that JOIN but it should speed up since it doesn't have to search using % and can take advantage of the index we have of the keyword column. A: You could try: if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE CONCAT('%', $keywords ,'%') LIMIT 4")) {
unknown
d3652
train
You are setting offset to 0 inside the loop. So offset is always 0. You should move this line: let offset = 0; before the for statement.
unknown
d3653
train
here's some pseudo code if (a.x-b.x)**2 + (a.y-b.y)**2 <= a.radius**2: vec_a_b = b-a # or you can do this component wise a.velocity = normalized(vec_a_b)*a.velocity.magnitude this assumes point a has a velocity vector, which encodes the direction it's currently headed in and its speed. now you can use the velocity to move a: a.x += a.velocity.x a.y += a.velocity.y
unknown
d3654
train
The hash differs because the data differs. The file is UTF-8, not ASCII, so you should use the UTF-8 encoding to convert the string to bytes to get the same result: byte[] data = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); Also, the file may contain a BOM (byte order mark) at the beginning. That is included in the data, as the file isn't read as text. Adding the UTF-8 BOM at the beginning of the data would give the same hash: byte[] bom = { 239, 187, 191 }; byte[] data = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); byte[] bomdata = new byte[bom.Length + data.Length]; bom.CopyTo(bomdata, 0); data.CopyTo(bomdata, bom.Length); byte[] hash = MD5.Create().ComputeHash(bomdata); A: Did you trim the string from the file for whitespace and new lines?
unknown
d3655
train
[UIView animateWithDuration:1.5 animations:^ { removeView.transform = CGAffineTransformMakeScale(0.0f, 0.0f); } completion:^(BOOL finished) { [removeView removeFromSuperview]; }]; A: Some changes: UIView *removeView=[self.tableView viewWithTag:10] ; removeView .transform = CGAffineTransformMakeScale(1.0f, 1.0f); [removeView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.5]; [UIView animateWithDuration:1.5 animations: ^{ removeView .transform = CGAffineTransformMakeScale(0.01f, 0.01f); } ]; Try setting your final transform to something small but nonzero. A: Try waiting to remove the view until the animation is over: [removeView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2.0]; A: Try this one, it's worked for me: [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1.5f]; removeView.transform = CGAffineTransformMakeTranslation(removeView.frame.origin.x,1000.0f + (removeView.frame.size.height/2)); aview.alpha = 0; [UIView commitAnimations]; A: Refer the following sample from Apple. [UIView transitionWithView:containerView duration:0.2 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{ [fromView removeFromSuperview]; [containerView addSubview:toView]; } completion:NULL]; The above code creates a flip transition for the specified container view. At the appropriate point in the transition, one subview is removed and another is added to the container view. This makes it look as if a new view was flipped into place with the new subview, but really it is just the same view animated back into place with a new configuration. May be the animation type you need to manage. Refer:- https://developer.apple.com/documentation/uikit/uiview/1622574-transition
unknown
d3656
train
Your command uses pipe |. It requires a shell: p = subprocess.Popen(command, shell=True) The command itself as far as I can tell looks ok. A: It's not necessary to use shell=True to achieve this with pipes. This can be done programmatically with pipes even where concern about insecure input is an issue. Here, conn_params is a dictionary with PASSWORD, NAME (database name), USER, and HOST keys. raster2pgsql_ps = subprocess.Popen([ 'raster2pgsql', '-d', '-I', '-C', '-e', '-Y', '-F', '-t', '128x128', 'C:\\temp\\SampleDTM\\SampleDTM.tif', 'test' ], stdout=subprocess.PIPE) # Connection made using conninfo parameters # http://www.postgresql.org/docs/9.0/static/libpq-connect.html psql_ps = subprocess.check_output([ 'psql', 'password={PASSWORD} dbname={NAME} user={USER} host={HOST}'.format(**conn_params), ], stdin=raster2pgsql_ps.stdout) A: The following worked for me on Windows, while avoiding shell=True One can make use of Python's fstring formatting to make sure the commands will work in windows. Please note that I used shp2pgsql but it should be a very similar process for raster2pgsql. Parameters for the shp2pgsql: srid is the coordinate system of the shape file, filename is the path to the shape file to be imported, tablename is the name you'd like to give your table. import os import subprocess shp2pgsql_binary = os.path.join(pgsql_dir, "bin", "shp2pgsql") psql_binary = os.path.join(pgsql_dir, "bin", "psql") command0 = f'\"{shp2pgsql_binary}\" -s {srid} \"{filename}\" {tablename}' command1 = f'\"{psql_binary}\" \"dbname={databasename} user={username} password={password} host={hostname}\"' try: shp2pgsql_ps = subprocess.Popen(command0, stdout=subprocess.PIPE) psql_ps = subprocess.check_output(command1, stdin=shp2pgsql_ps.stdout) except: sys.stderr.write("An error occurred while importing data into the database, you might want to \ check the SQL command below:") sys.stderr.write(command) raise To adpat to raster2pgsql, you just need to modify the string in command0, e.g. -s {srid} becomes -d -I -C -e -Y -F -t 128x128. The string for command1 can remain the same. A: It will be better to use subprocess.Popen in this way: proc = subprocess.Popen(['"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe"', '-d', '-I', '-C', '-e', '-Y', '-F', '-t', '128x128', '"C:\\temp\\SampleDTM\\SampleDTM.tif"', 'test', '|', '"C:\\Program Files\\PostgreSQL\\9.2\\bin\\psql.exe"', '-h', 'localhost', '-p', '5432', '-d', 'adr_hazard', '-U', 'postgres'], shell = True, stdout = subprocess.pipe, stderr = subprocess.STDOUT) proc.wait() result = proc.stdout.readlines()#if you want to process the result of your command proc.kill() B.T.W, it's good to format the path first, use: path = os.path.normalpath("C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe") this will avoid some path problems for different OS platform. The shell = True is important if you want to execute your command just like executing it in local shell. Hope will help you. A: PIPE = subprocess.PIPE pd = subprocess.Popen(['"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe", '-d', '-I', '-C', '-e', '-Y', '-F', '-t', '128x128', "C:\\temp\\SampleDTM\\SampleDTM.tif", 'test'], stdout=PIPE, stderr=PIPE) stdout, stderr = pd.communicate()
unknown
d3657
train
Combine all the dataframes in one dataframe with a unique id value which will distinguish each dataframe. I created two dataframes here with data column representing the dataframe number. library(dplyr) x1 <- data.frame(id = round(runif(21, 1, 21)), TestDay = rep(c("m","t","w","th","f","sa","su"), 3)) x2 <- data.frame(id = round(runif(21, 1, 21)), TestDay = rep(c("m","t","w","th","f","sa","su"), 3)) combine_data <- bind_rows(x1, x2, .id = 'data') group by the id column and count how many dataframes that id is present in. combine_data %>% group_by(id) %>% summarise(count_unique = n_distinct(data)) You can add filter(count_unique > 1) to the above chain to get id's which are present in more than 1 dataframe. A: To add to @Ronak 's answer, you can also concatenate c() the dataframe number using summarise(). This tells you which dataframe the ID comes from. df1 <- data.frame(id = letters[1:3]) df2 <- data.frame(id = letters[4:6]) df3 <- data.frame(id = letters[5:10]) library(tidyverse) df <- list(df1, df2, df3) df4 <- df %>% bind_rows(.id = "df_num") %>% mutate(df_num = as.integer(df_num)) %>% group_by(id) %>% summarise( df_found = list(c(df_num)), df_n = map_int(df_found, length) ) df4 A: We can use data.table methods * *Get the datasets in a list and rbind them with rbindlist *Grouped by 'id' get the count of unique 'data' with uniqueN library(data.table) rbindlist(list(x1, x2, idcol = 'data')[, .(count_unique = uniqueN(data)), by = id]
unknown
d3658
train
Solution 1: I don't have an answer using jQuery. But using a plain/vanilla JavaScript wouldn't cause any issue :). Following script allows you to detect the Viewport size (height and width) reliably. https://github.com/tysonmatanich/viewportSize Sample usage: <script type="text/javascript"> var width = viewportSize.getWidth(); var height = viewportSize.getHeight(); </script> I have used it in couple of projects, were i have to re-initialize some widgets based on current Viewport width/height rather than using window width/height (Window width/height calculation isn't consistent in all browsers - some include scroll bar size 16px as a part of window width and some doesn't). Sample Test page: http://tysonmatanich.github.io/viewportSize/ Solution 2: (Just for reference - Not an answer to OP's question, though it is related so I thought that it can remain) Well modernizr has a very good addition Modernizr.Mq. Through which you can cross check which break point range you are in... if(Modernizr.mq("(min-width:320px)")){ //Do job 1 } else if (Modernizr.mq("(min-width:768px)")){ //Do job 2 } or based on height Modernizr.mq("(min-height: 800px)") http://tysonmatanich.github.io/viewportSize/ A: I believe what you are looking for is scrollHeight The scrollHeight property returns the entire height of an element in pixels, including padding, but not the border, scrollbar or margin. You can try this: document.body.scrollHeight
unknown
d3659
train
Fixed it using options prop on Screen. In my Drawer Navigator: <Drawer.Navigator> <Drawer.Screen name="Home" component={HomeScreen} options={{ icon: 'home' }} /> </Drawer.Navigator> and to access it in the custom DrawerContent component: export default function DrawerContent({ state, navigation, ...props }) { const getIcon = (key) => props.descriptors[key].options.icon; return ( <DrawerContentScrollView {...props}> <Drawer.Section> {state.routes.map((route) => ( <DrawerItem key={route.key} label={route.name} icon={({ color, size }) => ( <MaterialCommunityIcons name={getIcon(route.key)} color={color} size={size} /> )} onPress={() => navigation.navigate(route.name)} /> ))} </Drawer.Section> </View> </DrawerContentScrollView> ); }
unknown
d3660
train
Override getValueAt() in your TableModel to return the correct value for cells in the TOTAL row and column. The correct value may be calculated by invoking getValueAt() in a loop, as shown in your TableModelListener example. In this complete example, the value shown in each row of the second column depends on the value chosen in the third column of the same row.
unknown
d3661
train
For my case, I have to remove this dependency from build.scala "com.typesafe" % "play-plugins-inject" % "2.0.2" and remove plugin from play.plugins. 1500:com.typesafe.plugin.inject.ManualInjectionPlugin This plugin brings in play_2.9 which has dependency on ehcache and causes play to initialize play's cache second time while play_2.10 from Play 2.1 has initialized it already.
unknown
d3662
train
try this data = [ele.text for ele in soup.find_all(text = True) if ele.text.strip() != ''] print(data)
unknown
d3663
train
Since the regex engine you are using is .NET, you may use a positive lookbehind based solution: (?<=\A[^&]*)& See the regex demo. Details * *(?<=\A[^&]*) - a location in the string that is immediately preceded with * *\A - start of string *[^&]* - 0 or more chars other than & *& - a & char.
unknown
d3664
train
You are redirecting the output of nslookup and ipconfig to a path without quoting, so maybe your location on drive E:\ contains spaces, which would prevent nslookup to write to correct file. Maybe it would good to provide the actual value of "path" and "path1". If this is not the case, try to open a command prompt as administrator and try to execute the exact same command with the same paths to verify it works. A: .Arguments = "/c" & "nslookup myip.opendns.com. resolver1.opendns.com" & "> " & path shall look more like .Arguments = "/c " & "nslookup myip.opendns.com resolver1.opendns.com " & "> " & path and .Arguments = "/c" & "ipconfig /all" & "> " & path1 shall look more like .Arguments = "/c " & "ipconfig /all " & "> " & path1 Also I would follow the advise above to consider that spaces may be in the path. A: Following the tips from both @AlessandroMandelli and @wech ... I wrote a (way too long) appending section of the program to put quotes into the path, making sure spaces won't screw up the program: 'Appends path1 string with quotes to fix spacing Dim pathIns As String = """" Dim path1F As String = path1.Insert(0, pathIns) path1 = path1F Dim path1FIns As Integer = path1.Length() Dim path1FF As String = path1.Insert(path1FIns, pathIns) path1 = path1FF 'Appends path string... Dim pathF As String = path.Insert(0, pathIns) path = pathF Dim pathFIns As Integer = path.Length() Dim pathFF As String = path.Insert(pathFIns, pathIns) path = pathFF And.. It worked! The program now yields the same results as it would from a path with no quotes! Final product/project can be viewed here
unknown
d3665
train
Think of it as cartoon.kenny[1] = cartoon.stan; They are basically the same thing A: If we bring the whole thing to one common style of using the subscript operator [] (possibly with &) instead of a * and + combination, it will look as follows cartoon.stan[1] = 4; cartoon.kyle[0] = &cartoon.stan[1]; cartoon.kenny = &cartoon.kyle[2]; cartoon.kenny[1] = &cartoon.stan[0]; After the cartoon.kenny = &cartoon.kyle[2]; you can think of kenny as an "array" of int * elements embedded into the kyle array with 2 element offset: kenny[0] is equivalent to kyle[2], kenny[1] is equivalent to kyle[3], kenny[2] is equivalent to kyle[4] and so on. So, when we do cartoon.kenny[1] = &cartoon.stan[0]; it is equivalent to doing cartoon.kyle[3] = &cartoon.stan[0]; That's basically what that last line does. In other words, if we eliminate kenny from the consideration ("kill Kenny"), assuming that the rest of the code (if any) doesn't depend on it, your entire code will be equivalent to cartoon.stan[1] = 4; cartoon.kyle[0] = &cartoon.stan[1]; cartoon.kyle[3] = &cartoon.stan[0]; As for what is the point of all this... I have no idea. A: In cartoon you have: - stan, an array of 4 ints. - kyle, an array of 4 pointers to int. - kenny, a pointer to a pointer to int, that is, let's say, a pointer to an "array of ints". cartoon.stan[1] = 4; sets second element of stan array (an int) to 1. cartoon.kyle[0] = cartoon.stan + 1; sets first element of kyle array (a pointer to int) to point to the second element of stan array (which we have just set to 4). cartoon.kenny = &cartoon.kyle[2]; sets kenny pointer to point to the third element of kyle array. *(cartoon.kenny + 1) = cartoon.stan; sets fourth element of kyle array (a pointer to int) to point to the first element of stan array (which hasn't been initialised yet). More in detail: cartoon.kenny gets kenny pointer's address (third element of kyle array), cartoon.kenny+1 gets the next int after that address (fourth element of kyle array, which happens to be a pointer to int), *(cartoon.kenny + 1) dereferences that pointer, so we can set it, and = cartoon.stan sets it to point to the first element of stan array. A: It is incrementing the pointer at *cartoon.kenny. 'kenny' is a pointer to a pointer, so the first dereference returns a pointer, which is incremented, and a value assigned. So, *(kenny + 1) now points to the beginning of the array 'stan'. A: It sets the last element of Kyle to point to the first element of Stan.
unknown
d3666
train
Instead of url_for('/predict'), drop the leading slash and use url_for('predict'). url_for(...) takes the method name and not the route name. A: I was not importing url_for. from flask import Flask, request, render_template, url_for
unknown
d3667
train
If I'm understanding you correctly, you want to remove the first and last elements of the array if the size of the array is greater than 3. You can do this by using the findAndModify query. In mongo shell you would be using this command: db.collection.findAndModify({ query: { $where: "this.time.length > 3" }, update: { $pop: {time: 1}, $pop: {time: -1} }, new: true }); This would find the document in your collection which matches the $where clause. The $where field allows you to specify any valid javascript method. Please note that it applies the update only to the first matched document. You might want to look at the following docs also: * *http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D for more on the $where clause. *http://www.mongodb.org/display/DOCS/Updating#Updating-%24pop for more on $pop. *http://www.mongodb.org/display/DOCS/findAndModify+Command for more on findAndModify. A: You could update it with { $pop: { time: 1 } } to remove the last one, and { $pop: { time : -1 } } to remove the first one. There is probably a better way to handle it though. A: @javaamtho you cannot test for a size greater than 3 but only if it is exactly 3, for size greater than x number you should use the $inc operator and have a field you either 1 or -1 to in order to keep track when you remove or add items (use a separate field outside the array as below, time_count) { "_id" : ObjectId("4d525ab2924f0000000022ad"), "name" : "hello", "time_count" : 5, "time" : [ { "stamp" : "2010-07-01T12:01:03.75+02:00", "reason" : "new" }, { "stamp" : "2010-07-02T16:03:48.187+03:00", "reason" : "update" }, { "stamp" : "2010-07-02T16:03:48.187+04:00", "reason" : "update" }, { "stamp" : "2010-07-02T16:03:48.187+05:00", "reason" : "update" }, { "stamp" : "2010-07-02T16:03:48.187+06:00", "reason" : "update" } ] } A: If you would like to leave these time elements, you can use aggregate command from mongo 2.2+ to retrieve min and max time elements, unset all time elements, and push min and max versions (with some modifications it could do your job): smax=db.collection.aggregate([{$unwind: "$time"}, {$project: {tstamp:"$time.stamp",treason:"$time.reason"}}, {$group: {_id:"$_id",max:{$max: "$tstamp"}}}, {$sort: {max:1}}]) smin=db.collection.aggregate([{$unwind: "$time"}, {$project: {tstamp:"$time.stamp",treason:"$time.reason"}}, {$group: {_id:"$_id",min:{$min: "$tstamp"}}}, {$sort: {min:1}}]) db.students.update({},{$unset: {"scores": 1}},false,true) smax.result.forEach(function(o) {db.collection.update({_id:o._id},{$push: {"time": {stamp: o.max ,reason: "new"}}},false,true)}) smin.result.forEach(function(o) {db.collection.update({_id:o._id},{$push: {"time": {stamp: o.min ,reason: "update"}}},false,true)}) A: db.collection.findAndModify({ query: {$where: "this.time.length > 3"}, update: {$pop: {time: 1}, $pop{time: -1}}, new: true }); convert to PHP
unknown
d3668
train
I suppose this is more of a general app architectural concern. The simplest answer is you should take the current time in seconds (new Date().getTime()), determine how many seconds there are until the next day, and set a timer for that number. However, as you mentioned, once the app is killed, that timer will no longer be accurate. You should use AppStateIOS to listen for when the app is backgrounded and foregrounded. Upon being sent to the background, clear the timer. Upon being brought to the foreground, run the original calculation again and generate a new timer. Unfortunately there is no equivalent functionality on Android as of yet. A: You can use react-native-midnight which subscribes to native APIs and fires event listeners when the day has changed from either a timezone change or crossing the midnight threshold.
unknown
d3669
train
Ok, based on your response in the comments, I think this is what you are going for. The ChromeDriver object has a Capabilities property you can use to request the name and version. As long as you are working with a ChromeDriver directly and not an IWebDriver that property is accessible like follows: string? versions = driver.Capabilities.GetCapability("browserVersion").ToString(); string? name = driver.Capabilities.GetCapability("browserName").ToString(); I modified your program a little bit based on what it seems like you are trying to do and printed the result to the console: private static ChromeDriver WebInit() { // set up options ChromeOptions options = new ChromeOptions(); options.AddArguments("--start-maximized"); // download latest chromedriver new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser); //this is the code used from the mentioned Github Repository // initialize the driver ChromeDriver driver = new ChromeDriver(options); return driver; } public static void Main() { ChromeDriver driver = WebInit(); // get the capabilities string? versions = driver.Capabilities.GetCapability("browserVersion").ToString(); string? name = driver.Capabilities.GetCapability("browserName").ToString(); Console.WriteLine(versions); Console.WriteLine(name); Console.ReadKey(); } The above example works for me in .Net 6.0 with the following NuGet packages installed: * *Selenium.Support (4.1.1) *Selenium.WebDriver (4.1.1) *WebDriverManager (2.13.0)
unknown
d3670
train
The problem is that LinkedList is not a thread-safe structure. Therefore, it should not be shared and modified by multiple concurrent threads as the changes on queueB might not be properly "communicated" to other threads. Try using a LinkedBlockingQueue instead. Also, use an AtomicLong for count for the same reason: it is shared in between several threads and you want to avoid race conditions. A: The fact that up to six threads may be operating on the queue concurrently means that modifications are not safe.
unknown
d3671
train
if the id of the menu item is set to the fragment id, you could probably use navigation controller to switch the destination. override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.settings -> currentNavController.navigate(R.id.navigation_destination_id) } return true }
unknown
d3672
train
I ran into the same thing a while ago, which was really confusing. You have to set the correct access scope for the virtual machine so that anyone using the VM is able to call the storage API. The documentation shows that the default access scope for storage on a VM is read-only: When you create a new Compute Engine instance, it is automatically configured with the following access scopes: * *Read-only access to Cloud Storage: https://www.googleapis.com/auth/devstorage.read_only All you have to do is change this scope so that you are also able to write to storage buckets from the VM. You can find an overview of different scopes here. To apply the new scope to your VM, you have to first shut it down. Then from your local machine execute the following command: gcloud compute instances set-scopes INSTANCE_NAME \ --scopes=storage-rw \ --zone=ZONE You can do the same thing from the portal if you go to the settings of your VM, scroll all the way down, and choose "Set Access for each API". You have the same options when you create the VM for the first time. Below is an example of how you would do this:
unknown
d3673
train
I was verifying the code changes by navigating to the lambda code editor on the AWS web portal, and it appears this was just a client side issue in the web UI. It took about 5 minutes before the lambda_function.py was updated in the UI (despite refreshing), whereas the other code files did get updated immediately. It is very strange that other files got updated, but not lambda_function.py. This makes me think it is not just a browser caching issue, but maybe a bug. A: I believe you may need to publish the new code changes according to https://docs.aws.amazon.com/cli/latest/reference/lambda/update-function-code.html --publish | --no-publish (boolean) Set to true to publish a new version of the function after updating the code. This has the same effect as calling PublishVersion separately.
unknown
d3674
train
You should initialize socket.io-redis after ready event. Also you should call to client.auth('password1', ()=>{}) function. Check this part of documentation: When connecting to a Redis server that requires authentication, the AUTH command must be sent as the first command after connecting. This can be tricky to coordinate with reconnections, the ready check, etc. To make this easier, client.auth() stashes password and will send it after each connection, including reconnections. callback is invoked only once, after the response to the very first AUTH command sent. NOTE: Your call to client.auth() should not be inside the ready handler. If you are doing this wrong, client will emit an error that looks something like this Error: Ready check failed: ERR operation not permitted. Try this code: var redis = require('redis'); const redisPort = 6379 const redisHostname = 'localhost' const password = 'password1' var p1 = new Promise((resolve, reject)=>{ var client = redis.createClient(redisPort, redisHostname, { auth_pass: 'password1' }); client.auth(password) client.on('ready', ()=>{ resolve(client) }) }) var p2 = new Promise((resolve, reject)=>{ var redisSubscriber = redis.createClient(redisPort, redisHostname, { auth_pass: 'password1' }); redisSubscriber.auth(password) redisSubscriber.on('ready', ()=>{ resolve(redisSubscriber) }) }) Promise.all([p1,p2]).then(([client, redisSubscriber])=>{ console.log('done', client) client.ping((err, data)=>{ console.log('err, data', err, data) }) // Create and use a Socket.IO Redis store var RedisStore = require('socket.io-redis'); io.set('store', new RedisStore({ redisPub: client, redisSub: redisSubscriber, redisClient: client })); })
unknown
d3675
train
All you need to do is reference a different style that includes a slightly bigger font for the size of the date. I'm not exactly sure why yours isn't working using the styles.xml as it seems correct. However I would just simply add it to the XML attributes for the calendar. This will be fine as presumably you're only using one Calendar and therefore it isn't really inefficient. Add this line to the calendar XML: android:dateTextAppearance="@android:style/TextAppearance.Large" Hope this helps you! A: You should change "android:dateTextAppearance", you can check this reference too ;) CalendarView also you can try this Style will save the world!
unknown
d3676
train
With group_by you can group by any criteria given, then assemble all grouped items by taking their common .src_ip from any of them (eg. the first), and .sessions as a mapped array on .session from all of them. Add other parts as you see fit. jq 'group_by(.src_ip) | map({src_ip: .[0].src_ip, sessions: map(.session)})'
unknown
d3677
train
POJO MyForm is populated by Spring framework itself while submitting the form. Spring takes request parameters, convert into correct format and populate fields of your empty POJO but if you call methods annotated by @DateTimeFormat manually then it doesn't work as expected. You have to use java SimpleDateFormat or joda DateTime in controller.
unknown
d3678
train
This is a guess, but your html is not valid and maybe because of that the facebook scraper fail to parse and extract the data from it. I haven't went through all of it, but you don't seem to close all tags. For example the description and keywords meta tags don't end with "/>" or ">". Edit Screen capture of what the debugger shows when I load your html from my server:
unknown
d3679
train
Please check out this tutorial that explains how to Set up continuous integration and deployment to Azure App Service with Jenkins and One of the best method to deploy to Azure Web App (Windows) from Jenkins : https://learn.microsoft.com/en-us/azure/jenkins/java-deploy-webapp-tutorial A: To find the Azure AD user with the object id '03a1b3f9-a6fb-48bd-b016-4e37ec712f14', go to Azure portal, open Cloud Shell and run Get-AzureADUser -ObjectId '03a1b3f9-a6fb-48bd-b016-4e37ec712f14' To diagnose or troubleshoot the issue, go to Azure Portal -> Resource Groups -> my-demo-app -> MY-DEMO-APP -> Access control (IAM) -> Role assignments -> and then search for above found AD User and check if that user has atleast read permission. Hope this helps!
unknown
d3680
train
You are not far from the goal, at least to a certain extent. There's a limit to how many pixels can be transferred over such a request, namely 262144. Your image, when taken over the whole globe (like you are doing), has 3732480000 - over 10000x too many. Still, you can sample a small area and put in the numpy: import ee import numpy as np import matplotlib.pyplot as plt ee.Initialize() #Load a collection TERRA = ee.ImageCollection("MODIS/006/MOD09A1").select(['sur_refl_b02', 'sur_refl_b07',"StateQA"]) TERRA = TERRA.filterDate('2003-01-01', '2019-12-31') #Extract an image TERRA_list = TERRA.toList(TERRA.size()) Terra_img = ee.Image(TERRA_list.get(1)) img = Terra_img.select('sur_refl_b02') sample = img.sampleRectangle() numpy_array = np.array(sample.get('sur_refl_b02').getInfo()) It's an area over Wroclaw, Poland, and looks like this when passed to matplotlib via imshow: What if you really need the whole image? That's where Export.image.toDrive comes into play. Here's how you'd download the image to the Google Drive: bbox = img.getInfo()['properties']['system:footprint']['coordinates'] task = ee.batch.Export.image.toDrive(img, scale=10000, description='MOD09A1', fileFormat='GeoTIFF', region=bbox) task.start() After the task is completed (which you can monitor also from Python), you can download your image from Drive and access it like any other GeoTIFF (see this GIS Stack Exchange post). A: It seems like you want to download data from earth engine to then use them with numpy. You are doing two things wrong here: * *You are treating Google Earth Engine as a download service. This is not the purpose of Earth Engine. If you want to download big amounts of data (like in your case a year of Terra Surface Reflectance) you should download them directly from the service providers. The only thing you should download from Earth Engine are the end-results of your analysis which you conducted within Earth Engine. *.getInfo does not get you the satellite data, it will only get you the metadata of your ImageCollection in the form of a JSON Object. If you want to the actual raster data you would have to export it (which, as said in 1, you shouldn't do for this amount of data).
unknown
d3681
train
It's hard to give a definitive answer for something like this (unless someone from the compiler team drops in :)), but there's a few points you can consider: The performance "bonus" of structs is always a tradeoff. Basically, you get the following: * *Value semantics *Possible stack (maybe even register?) allocation *Avoiding indirection What does this mean in the await case? Well, actually... nothing. There's only a very short time period during which the state machine is on the stack - remember, await effectively does a return, so the method stack dies; the state machine must be preserved somewhere, and that "somewhere" is definitely on the heap. Stack lifetime doesn't fit asynchronous code well :) Apart from this, the state machine violates some good guidelines for defining structs: * *structs should be at most 16-bytes large - the state machine contains two pointers, which on their own fill the 16-byte limit neatly on 64-bit. Apart from that, there's the state itself, so it goes over the "limit". This is not a big deal, since it's quite likely only ever passed by reference, but note how that doesn't quite fit the use case for structs - a struct that's basically a reference type. *structs should be immutable - well, this probably doesn't need much of a comment. It's a state machine. Again, this is not a big deal, since the struct is auto-generated code and private, but... *structs should logically represent a single value. Definitely not the case here, but that already kind of follows from having a mutable state in the first place. *It shouldn't be boxed frequently - not a problem here, since we're using generics everywhere. The state is ultimately somewhere on the heap, but at least it's not being boxed (automatically). Again, the fact that it's only used internally makes this pretty much void. And of course, all this is in a case where there's no closures. When you have locals (or fields) that traverse the awaits, the state is further inflated, limiting the usefulness of using a struct. Given all this, the class approach is definitely cleaner, and I wouldn't expect any noticeable performance increase from using a struct instead. All of the objects involved have similar lifetime, so the only way to improve memory performance would be to make all of them structs (store in some buffer, for example) - which is impossible in the general case, of course. And most cases where you'd use await in the first place (that is, some asynchronous I/O work) already involve other classes - for example, data buffers, strings... It's rather unlikely you would await something that simply returns 42 without doing any heap allocations. In the end, I'd say the only place where you'd really see a real performance difference would be benchmarks. And optimizing for benchmarks is a silly idea, to say the least... A: I didn't have any foreknowledge of this, but since Roslyn is open-source these days, we can go hunting through the code for an explanation. And here, on line 60 of the AsyncRewriter, we find: // The CLR doesn't support adding fields to structs, so in order to enable EnC in an async method we need to generate a class. var typeKind = compilationState.Compilation.Options.EnableEditAndContinue ? TypeKind.Class : TypeKind.Struct; So, whilst there's some appeal to using structs, the big win of allowing Edit and Continue to work within async methods was obviously chosen as the better option.
unknown
d3682
train
This is possible with a javascript onclick or onsubmit event, using GET rather than POST, but it's definitely not best practice. Use a form or AJAX, as recommended by other posters: <input type="text" id="name" /> <button id="submit" onclick="javascript:window.location='http://yoururl.com/?name='+document.getElementById('name').value">Submit</button> A: You are not able to send a form data without using <form>. The only way to do this is to use ajax instead of a classic HTML form. A: You can take inputs from STDIN in PHP's latest versions like: fscanf(STDIN, "%s\n", $value); Here $value will contain the input.
unknown
d3683
train
By default when we use transparent images in our app mostly the transparent part will show its parent. For example if we use transparent images for menus in android. then by default the theme of the device/background will be the parent view for this image. According to me better to change the image and try.
unknown
d3684
train
You may easily get logs of all SQL statements from DataNucleus by turning on the category DataNucleus.Datastore.Native (see http://www.datanucleus.org/products/datanucleus/logging.html) JDO2 InstanceLifecycleListeners would allow you to intercept events, but I don't think the SQL statements would be available there... You can also look to your app server for SQL profiling tools. For example GlassFish allows you to attach SQLTraceListener implementations to your connection pools. See http://docs.oracle.com/cd/E18930_01/html/821-2418/giyck.html#giygg A: Log4j You can use java.util.logging or Log4j with DataNucleus. I'm going to tell about Log4j configuration. log4j.properties # Define the destination and format of our logging log4j.rootCategory=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n # DataNucleus Categories log4j.category.DataNucleus=ALL The last line assigns a level threshold to INFO or ALL in order to see all DataNucleus logs. DataNucleus uses a series of categories, and logs all messages to these categories. See here for more details. You probably need * *log4j.category.DataNucleus.Query - All messages relating to queries *log4j.category.DataNucleus.Datastore - All general datastore messages or *log4j.category.DataNucleus.JDO - All messages general to JDO log4j.category.DataNucleus is a root of all DataNucleus log categories. Add log4j to your CLASSPATH. I use Gradle for dependency management, so here is my build script: build.gradle configurations { all*.exclude group: "commons-logging", module: "commons-logging" } dependencies { // Logging compile 'org.slf4j:slf4j-api:1.7.+' runtime 'org.slf4j:slf4j-jdk14:1.7.+' runtime ('log4j:log4j:1.2.17') { exclude group: "com.sun.jdmk", module: "jmxtools" exclude group: "com.sun.jmx", module: "jmxri" exclude group: "javax.mail", module: "mail" exclude group: "javax.jms", module: "jms" } } To provide a Log4J configuration file when starting up your application set a JVM parameter as -Dlog4j.configuration=file:log4j.properties This may be done for you if you are running within a JavaEE application server. Or if you are using Spring WebMVC, place log4j.properties inside WEB-INF, and add the following listener to your Deployment descriptor. web.xml <!-- The definition of the Log4j Configuration --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param>
unknown
d3685
train
Aside from pointing out that JDK/JRE bundles Sun's SJSXP which works ok at this point, I would recommend AGAINST using Stax ref impl (stax.codehaus.org) -- do NOT use it for anything, ever. It has lots of remaining bugs (although many were fixed, initial versions were horrible), isn't particularly fast, doesn't implement even all mandatory features. Stay clear of it. I am partial to Woodstox, which is by far the most complete implementation for XML features (on par with Xerces, about the only other Java XML parser that can say this), more performant than Sjsxp, and all around solid parser and generator -- this is why most modern Java XML web service frameworks and containers bundle Woodstox. Or, if you want super-high performance, check out Aalto. It is successor to Woodstox, with less features (no DTD handling) but 2x faster for many common cases. And if you ever need non-blocking/async parsing (for NIO based input for example), Aalto is the only known Java XML parser to offer that feature. As to Axiom: it is NOT a parser, but tree model built on top of Stax parser like Woodstox, so they didn't reinvent the wheel. XmlPull predates Stax API by couple of years; basically Stax standardization came about people using XmlPull, liking what they saw, and Sun+BEA wanting to standardize the approach. There was some friction in the process, so in the end XmlPull was not discontinue when Stax was finalized, but one can think of Stax as successor -- XmlPull is still used for mobile devices; I think Android platform includes it. (disclaimers: I am involved in both Aalto and Woodstox projects; as well as provided more than a dozen bug fixes to both SJSXP and Stax RI) A: As of Java 1.6, there is a StaX implementation inside the plain bundled JRE. You can use that. If you don't like the performance, drop in woodstox. Axiom is something else entirely, much more complex. Xmlpull seems to be going by the wayside in favor of one Stax implementation or another.
unknown
d3686
train
I have encountered same problem while working on this. When I think on your options 1- There is no need to re-write whole app * *Create an api endpoint on server side *Create a script(program) on client that will push real paths to server Your files should be accessible over network Here is the script code that I used: Tested with python Python 3.7.4 Prints realpath of all the selected files as a list. source import tkinter as tk from tkinter import filedialog import pathlib root = tk.Tk() root.withdraw() root.attributes("-topmost", True) file_path = filedialog.askopenfilenames() # print(file_path) #debug files = list(file_path) print(files) Then you need to import either a requests and generate a Json request to your server endpoint.Or just call a curl with subprocess. 2- By your definition I assume the intranet network is trusted.So is authentication necessary.And there is a question of How many users will use same file after it is processed in server.If its one then there is no need for a django app. A: Well... I've solved my problem. With much less blood than expected, which I'm happy of. :) First, I installed Electron and one of minimal boilerplates into a new folder in my project. In boilerplate there is a file called main.js (or index.js, depends on boilerplate), which defines Electron application window and its contents. Inside is the line which loads content to Electron BrowserWindow object: mainWindow.loadFile(path.join(__dirname, 'index.html')); Fortunately, BrowserWindow object does have method loadURL, which can be used to load webpage instead of local html file: mainWindow.loadURL('http://127.0.0.1:8000'); It means that all pages rendered by Django will be shown in Electron browser, which runs node.js instead of standard browser javascript engine. Thus, this code in Django page template will work perfectly: <h1 id="holder">DROP FILES HERE</h1> <p id="dropped"></p> <script> const dropZone = document.getElementById('holder'); dropZone.addEventListener('drop', (e) => { e.preventDefault(); e.stopPropagation(); let filesList = '\n'; for (const f of e.dataTransfer.files) filesList += f.path + '\n'; document.getElementById('dropped').innerHTML = `Full file paths: ${filesList}`; }); dropZone.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); }); </script>
unknown
d3687
train
The save method is asynchronous and returns a promise. In your case, newProduct.save() returns a promise which is not being fulfilled and no error is actually thrown: app.post('/products', async (req, res, next) => { try { const newProduct = new Product(req.body); await newProduct.save(); res.redirect(`/products/${newProduct._id}`); } catch (e) { next(e); } }); A: The best solution would be validate req.body with a validator and save newProduct after it is validated. It'd be better to return the newProduct after it is saved rather than redirecting to certain endpoint. If it is not validated you can throw your custom error. I recommend using JOI which is very easy to use.
unknown
d3688
train
You need integrate facebook SDK. facebook developer
unknown
d3689
train
try this @Valid usage show here for nested object in bean class just check once.. hibernate validator
unknown
d3690
train
You can look at Routineer - Scala DSL for declaring HTTP routes: https://github.com/mvv/routineer
unknown
d3691
train
Put the buttons in a custom panel with an image background (example here). In IDE use a regular JPanel and drag the JButtons over it, then change the code from JPanel to ImagePanel (or whatever name you used for it). A: This is a little cheeky, but. * *Start by setting the layout of the base component to BorderLayout. *Drop a JLabel into it. Set the labels icon image to the background image you want to use. *Set the layout manager of the label to what ever you want to use. *Drop your buttons onto it... A: 1.Add the JLabel and in Properties, Set text to null and add the image by selecting it from the icons menu (this image should be in your package). 2.Set the appropriate size of the background and set the layout to NULL Layout. 3.Place the background label as the bottom most layer and keep adding buttons or labels as per your need.
unknown
d3692
train
While it's not a direct answer to your question - I have a workaround for you. If you add your gesture recognizers to your custom annotation view then you can capture both long press and double tap over the annotation view and any associated callout. Some example code I wrote to try this: import UIKit import MapKit class StarAnnotation : NSObject, MKAnnotation { let title: String? let coordinate: CLLocationCoordinate2D init(title: String, coordinate: CLLocationCoordinate2D) { self.title = title self.coordinate = coordinate super.init() } } class StarAnnotationView : MKAnnotationView, UIGestureRecognizerDelegate { override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) self.image = UIImage(named: "star") // Gesture Recogniser (Long Press) let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction:") longPressGR.minimumPressDuration = 1 longPressGR.delegate = self self.addGestureRecognizer(longPressGR) // Gesture Recogniser (Double Tap) let doubleTapGR = UITapGestureRecognizer(target: self, action: "doubleTapAction:") doubleTapGR.numberOfTapsRequired = 2 doubleTapGR.delegate = self self.addGestureRecognizer(doubleTapGR) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func doubleTapAction(recognizer: UITapGestureRecognizer) { if recognizer.numberOfTapsRequired == 2 { print("double tapped") } } func longPressAction(recognizer: UILongPressGestureRecognizer) { print("long pressed") } } class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // set up map view and sample annotation let operaHouseCoord = CLLocationCoordinate2D(latitude: -33.8587, longitude: 151.2148) let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) let operaHouseAnnotation = StarAnnotation(title: "Opera House", coordinate: operaHouseCoord) mapView.region = MKCoordinateRegion(center: operaHouseCoord, span: span) mapView.delegate = self mapView.addAnnotation(operaHouseAnnotation) } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? StarAnnotation { let identifier = "star" if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? StarAnnotationView { dequeuedView.annotation = annotation return dequeuedView } else { let view = StarAnnotationView(annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true return view } } return nil } }
unknown
d3693
train
The basic rule to parse C declarations is "read from right to left and the inside out jumping toward the right when leaving a pair of parenthesis", i.e. start the the most deeply nested pair of parenthesis and then work yourself out looking toward the right. Technically you must know operator associativity, but it works well enough in most situations. Now lets apply this (simplified) rule to your question: double (*b)[n]; ^ b is a double (*b)[n]; ^ pointer to double (*b)[n]; ^^^ and array double (*b)[n]; ^^^^^^ of doubles. double (*c[n])(); ^^^^ c is an array of double (*c[n])(); ^ pointers to double (*c[n])(); ^^ functions double (*c[n])(); ^^^^^^ returning double. double (*d())[n]; ^^^ d is a function double (*d())[n]; ^ returning a pointer to double (*d())[n]; ^^^ an array of double (*d())[n]; ^^^^^^ doubles There's a neat utility found on most *nixes, called cdecl, which takes a C declaration string and turns it into a natural language sentence. A: Let try this way. first, you should be familiar with these three symbols: 1. * -- a pointer. 2. [] -- an array. 3. () -- a function.(notice: not parentheses) we take "double (*d())[n]" as an example. the first step is to find out the identifier in the declaration, an identifier is the name of variable, here it is "d". (i) -- what is "d"? ------------------------------------------------------------------------ look to the right side of the identifier, to see if there is a "[]" or a "()" : ...d[]...: d is an array. ...d()...: d is a function. if neither, look to the left side, to see if there is a "*" : ...*d...: d is a pointer. ------------------------------------------------------------------------ now we've found that d is a function. use x to replace d(), then the declaration becomes "double (*x)[n]" (ii) -- what is "x"? ------------------------------------------------------------------------ repeat (i), we find that x is a pointer. that means, d is a function returning a pointer. ------------------------------------------------------------------------ use y to replace *x, then the declaration becomes "double y[n]" (iii) -- what is "y"? ------------------------------------------------------------------------ repeat (i), we find that y is an array of n elements. that means, d is a function returning a pointer to an array of n elements. ------------------------------------------------------------------------ use z to replace y[n], then the declaration becomes "double z" (iv) -- what is "z"? ------------------------------------------------------------------------ repeat (i), we find that z is a double. that means, d is a function returning a pointer to an array of n double elements. ------------------------------------------------------------------------ let's see another expression: void (*(*f)(int)[n])(char) 1. we find f. 2. f is a pointer. *f -> a void (*a(int)[n])(char) 3. a is a function. a() -> b void (*b[n])(char) --f is a pointer to a function (with an int parameter)-- 4. b is an array. b[] -> c void (*c)(char) --f is a pointer to a function returning an array (of n elements)-- 5. c is a pointer. *c -> d void d(char) --f is a pointer to a function returning an array of n pointers-- 6. d is a function returning void. --f is a pointer to a function returning an array of n pointers to functions (with a char parameter) returning void-- A: double (*b)[n]; b is a pointer to an array of n doubles double (*c[n])(); c is an array of n pointers to functions taking unspecified number of arguments and returning double double (*d())[n]; d is a function taking unspecified number of arguments and returning a pointer to an array of n doubles In general, in order to parse these kind of declarations in your head, take the following approach. Let's see the last declaration, for example double (*d())[n]; what is the first thing that is done to d? It is called with (), therefore it's a function taking unspecified number of arguments and returnig... what's the thing done with the result? It is dereferenced (*), therefore it's a pointer to. The result is then indexed, therefore it's an array of n... what's left? a double, therefore of doubles. Reading the parts in bold, you'll get your answer. Let's see another example void (*(*f)(int)[n])(char) Here, f is first dereferenced, therefore it's a pointer to... it's then called with (int), therefore a function taking int and returning , the result is then indexed with [n], so an array of n. The result is dereferenced again, so pointers to. Then the result is called by (char), so functions taking char and returning (all is left is void) void. So f is a pointer to a function taking int and returning an array of n pointers to functions taking char and returning void. HTH A: There are two great resources to understand "C gibberish": * *http://cdecl.org/ - Online service that translates "C gibberish ↔ English" *The "Clockwise/Spiral Rule" by David Anderson if you want to understand what better what is going on Output of cdecl.org: * *double (*c[n])(): Syntax error (n is not valid here) *double (*c[])(): declare c as array of pointer to function returning double
unknown
d3694
train
In the first code you are replacing the text every time you iterate, the solution is to use append() cur = conn.cursor() conn.text_factory = str cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,)) self.SearchResults.clear() # clear previous text for row in cur: self.SearchResults.append('{0}'.format(str(row[0])))
unknown
d3695
train
You can use a Dictionary or a Hashset to reduce Any and Contains complexity from O(n) to O(1): The idea above can still be used for large lists to replace list/array/IEnumarable<> Contains which is O(n) with Hashset's Contains which is O(1). var entitiesWithPriorityMap = entitiesWithPriority.ToDictionary(e => e.entityName, e => true); var entitiesWithIssueMap = entitiesWithIssue.ToDictionary(e => e.entityName, e => true); var result = allEntities.Select(entityName => new Entity() { Name = entityName, HasPriority = entitiesWithPriorityMap.ContainsKey(entityName), HasIssue = entitiesWithIssueMap.ContainsKey(entityName) }); Note: This works when dealing with Linq2Object nor Linq2Sql (cannot generate SQL out of Contains in this scenario). Hashset version var entitiesWithPriorityMap = new HashSet<Entity>(entitiesWithPriority); var entitiesWithIssueMap = new HashSet<Entity>(entitiesWithIssue); // replace ContainsKey with Contains A: You could join them together: var entities = from name in allEntities join pr in entitiesWithPriority on name equals pr into np from priority in np.DefaultIfEmpty() join iss in entitiesWithIssue on name equals iss into npi from issue in npi.DefaultIfEmpty() select new Entity { Name = name, HasPriority = !string.IsNullOrEmpty(priority), HasIssue = !string.IsNullOrEmpty(issue) }; A: First create a dictionary <string>,<entity> and populate it from all entities with all hasXXX defaults to false After that, lookup is O(1) foreach (var key in EntitiesWithPriority) { dict[key].hasPriority = true } and so on A: If the construction can be List<> instead from an array, we can create a List<> with the following generic type: List<Dictionary<string, dynamic>> To achieve such construction you need to create following method: public List<List<Dictionary<string, dynamic>>> MethodName() { var list = new List<List<Dictionary<string, dynamic>>>(); HasPriority = false; HasIssue = false; foreach (var item in allEntities) { if (entitiesWithPriority.Contains(item.ToString())) HasPriority = true; if (entitiesWithIssue.Contains(item.ToString())) HasIssue = true; list.Add(new List<Dictionary<string, dynamic>>() { (new Dictionary<string, dynamic>() { { "name", item } }), (new Dictionary<string, dynamic>() { { "hasPriority", HasPriority } }), (new Dictionary<string, dynamic>() { { "hasIssue", HasIssue } }) }); } return list; } I'm not sure if all properties in your class are necessary. In case you'd want to add more arrays with conditions you should modify foreach loop.
unknown
d3696
train
There are several issues in this code: * *It returns null when places == 0 -- without shift, the original array needs to be returned *In the given loop implementation the major part of the array may be skipped and instead of replacing the first places elements with 0, actually a few elements in the beginning of the array are set to 0. Also it is better to change the signature of the method to set places before the vararg array. So to address these issues, the following solution is offered: public static int[] shiftWithDrop(int places, int ... array) { if(array == null || places <= 0) { return array; } for (int i = array.length; i-- > 0;) { array[i] = i < places ? 0 : array[i - places]; } return array; } Tests: System.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5))); System.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5}))); System.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5))); System.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5))); Output: [0, 1, 2, 3, 4] [0, 0, 1, 2, 3] [0, 0, 0, 1, 2] [0, 0, 0, 0, 0]
unknown
d3697
train
You need to use Apache mod_rewrite to achieve this. If your server has it enabled, you could do something like this in .htaccess: RewriteEngine on RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /statement.php?company=$1&q=$2 [L] A: You can use $_SERVER['PATH_INFO'] to access anything in the URL docpath after the address of your script. e.g. http://test.com/reports/statement.php/ABC/Q1 ...then in statement.php you would have the string "/ABC/Q1" in $_SERVER['PATH_INFO'] Of course, you'll need to setup your webserver to match the URL and target the correct script based on the HTTP request. A: As stated by others, you have to use url rewriting. Usually a php application that make use of it, it applies the pattern called Front Controller. This means that almost every url is rewritten to point to a single file, where the $_SERVER['PATH_INFO'] is used to decide what to do, usually by matching with patterns you define for your actions, or return a 404 error if the url doesn't match any of the specified patterns. This is called routing and every modern php framework has a component that helps doing this work. A smart move would also be providing a tool to generate urls for your resources instead of handwriting them, so that if you change an url pattern you do not have to rewrite it everywhere. If you need a complex routing system, check out the routing component of some major frameworks out there, e.g. Symfony2, Zend Framework 2, Auraphp. For the simplest php router out there, check instead GluePHP. The codebase is tiny so you can make yourself an idea on how the stuff works, and even implement a small router that fits your needs if you want to.
unknown
d3698
train
Since your end result (per country) is a single field with bands delimited by CRLF, you can make it simple. Add the following Dims; Dim aArray(10, 2) As String Dim iC As Integer Dim i As Integer IC = 0 Then add this inside your loop (change field names as required): Debug.Print rs1!country & vbTab & rs1!band If aArray(iC, 1) <> rs1!country Then iC = iC + 1 If iC > 10 Then MsgBox "There are more than 10 countries! Change the code...", vbOKOnly, "Too many countries" aArray(iC, 1) = rs1!country aArray(iC, 2) = rs1!band Else aArray(iC, 2) = aArray(iC, 2) & vbCrLf & rs1!band End If To see results: For i = 1 To iC MsgBox aArray(i, 1) & vbCrLf & aArray(i, 2) Next i A: Why not creating your temp table by using a simple CrossTab query ? If that suits your needs, it will be much easier.
unknown
d3699
train
Check out hosted background services in .NET Core, sounds like it could work for you. Hosted background services continue running on your server even if the user navigates away from your site. You could have an OrderManager hosted service that guides each order through the process and keeps the order status updated in the database, email the user status updates, or push changes to the front-end.
unknown
d3700
train
SET SERVEROUTPUT ON; DECLARE v_CARE_COUNT NUMBER := 0; v_PHONE VARCHAr2(40) := NULL; BEGIN select count(distinct care_level) into v_CARE_COUNT from Table1 where user_id = '100'; IF(v_CARE_COUNT > 0) THEN select phone into v_PHONE from Table2 where care_level in (select distinct care_level from Table1 where user_id = '100') and rownum = 1; ELSE select phone into v_PHONE from Table2 where care_level = 'default'; END IF; DBMS_OUTPUT.PUT_LINE('PHONE is <'||v_PHONE||'>'); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Exception : '||SQLERRM); END; / EDIT: ( AS SIngle SQL) SELECT PHONE FROM TABLE2 WHERE CARE_LEVEL in ( SELECT CARE_LEVEL FROM TABLE1 WHERE USER_ID='100' UNION SELECT CARE_LEVEL FROM TABLE1 WHERE CARE_LEVEL='default' AND NOT EXISTS (SELECT 'X' FROM TABLE1 WHERE USER_ID='100') ) AND ROWNUM = 1; A: The 'else if' syntax is wrong. In Oracle you need to use 'ELSIF' and complete the whole conditional statement with an 'END IF'. The SQL statements within should also be followed with a ; Try: IF ((select count(distinct care_level) from Table1 where user_id = '100') > 0) THEN select phone from Table2 where care_level in (select distinct care_level from Table1 where user_id = '100') and rownum = 1 order by care_level asc; ELSIF ((select count(distinct care_level) from Table1 where user_id = '100') = 0) THEN select phone from Table2 where care_level = 'default'; END IF
unknown