_id
stringlengths
2
6
text
stringlengths
4
46k
title
stringclasses
1 value
d10601
What you are talking about is a WebView in android: public class WebActivity extends Activity { WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("http://51.254.93.66/Shikfa/"); } } And then your main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> It should show all your directories like it does on your website.
d10602
check this out http://developer.android.com/reference/android/media/MediaMetadataRetriever.html but it is on API LEVEL 10 Thank you. I have done using the thread,not the great solution but it works public class IcyStreamMeta { protected URL streamUrl; private Map<String, String> metadata; private boolean isError; public IcyStreamMeta(URL streamUrl) { setStreamUrl(streamUrl); isError = false; } /** * Get artist using stream's title * * @return String * @throws IOException */ public String getArtist() throws IOException { Map<String, String> data = getMetadata(); if (!data.containsKey("StreamTitle")) return ""; String streamTitle = data.get("StreamTitle"); String title = streamTitle.substring(0, streamTitle.indexOf("-")); return title.trim(); } /** * Get title using stream's title * * @return String * @throws IOException */ public String getTitle() throws IOException { Map<String, String> data = getMetadata(); if (!data.containsKey("StreamTitle")) return ""; String streamTitle = data.get("StreamTitle"); String artist = streamTitle.substring(streamTitle.indexOf("-")+1); return artist.trim(); } public Map<String, String> getMetadata() throws IOException { if (metadata == null) { refreshMeta(); } return metadata; } public void refreshMeta() throws IOException { retreiveMetadata(); } private void retreiveMetadata() throws IOException { URLConnection con = streamUrl.openConnection(); con.setRequestProperty("Icy-MetaData", "1"); con.setRequestProperty("Connection", "close"); con.setRequestProperty("Accept", null); con.connect(); int metaDataOffset = 0; Map<String, List<String>> headers = con.getHeaderFields(); InputStream stream = con.getInputStream(); if (headers.containsKey("icy-metaint")) { // Headers are sent via HTTP metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0)); } else { // Headers are sent within a stream StringBuilder strHeaders = new StringBuilder(); char c; while ((c = (char)stream.read()) != -1) { strHeaders.append(c); if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) { // end of headers break; } } // Match headers to get metadata offset within a stream Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n"); Matcher m = p.matcher(strHeaders.toString()); if (m.find()) { metaDataOffset = Integer.parseInt(m.group(2)); } } // In case no data was sent if (metaDataOffset == 0) { isError = true; return; } // Read metadata int b; int count = 0; int metaDataLength = 4080; // 4080 is the max length boolean inData = false; StringBuilder metaData = new StringBuilder(); // Stream position should be either at the beginning or right after headers while ((b = stream.read()) != -1) { count++; // Length of the metadata if (count == metaDataOffset + 1) { metaDataLength = b * 16; } if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) { inData = true; } else { inData = false; } if (inData) { if (b != 0) { metaData.append((char)b); } } if (count > (metaDataOffset + metaDataLength)) { break; } } // Set the data metadata = IcyStreamMeta.parseMetadata(metaData.toString()); // Close stream.close(); } public boolean isError() { return isError; } public URL getStreamUrl() { return streamUrl; } public void setStreamUrl(URL streamUrl) { this.metadata = null; this.streamUrl = streamUrl; this.isError = false; } public static Map<String, String> parseMetadata(String metaString) { Map<String, String> metadata = new HashMap(); String[] metaParts = metaString.split(";"); Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$"); Matcher m; for (int i = 0; i < metaParts.length; i++) { m = p.matcher(metaParts[i]); if (m.find()) { metadata.put((String)m.group(1), (String)m.group(2)); } } return metadata; } } make thread call each 10 sec public void startThread(){ timer = new Timer(); timer.schedule(new TimerTask() { public void run() { URL url; Message msg = handler.obtainMessage(); try { url = new URL(URL); IcyStreamMeta icy = new IcyStreamMeta(url); Log.d("SONG",icy.getTitle()); msg.obj = icy.getTitle(); Log.d("ARTITSi",icy.getArtist()); handler.sendMessage(msg); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, 0, 10000); }
d10603
If the push notifications work directly through Urban Airship and not through PlayerDuel, You probably didn't specify the right urban airship details in PlayerDuel's developers website. Make sure you put Urban Airship's Master Secret and not the App Secret in PlayerDuel's website. A: I have used App Secrete as Urban Airship Key: . This is wrong. When i change it value as App Key . It works fine.
d10604
:PRIVATE_FORMAT_PKCS8); $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_PKCS8); file_put_contents("privateKey.pem",$privatekey); file_put_contents("publicKey.pem", $publickey); The java source code to read those keys: import java.io.*; import java.security.*; import java.security.spec.*; public class PublicKeyReader { public static PublicKey get(String filename) throws Exception { File f = new File(filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int)f.length()]; dis.readFully(keyBytes); dis.close(); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } public static void main (String [] args) throws Exception { PublicKeyReader publicKeyReader = new PublicKeyReader(); PublicKey publicKey = publicKeyReader.get("key/testPub.pem"); System.out.println(publicKey); } } It produces java.security.InvalidKeyException: invalid key format. Need help on this. Thanks in advance. A: First of all, as noted in the comments, there is no such thing as a PKCS#8 public key. That means that the PHP library doesn't know what it is talking about. Instead, what you seem to get, if neubert is correct, is a structure defined for X.509 certificates called X509EncodedKeySpec. And in the Java code, you are indeed trying to use that to read in the public key. However, what you forget is that X509EncodedKeySpec is a binary format, specified in ASN.1 DER. What you receive is a PEM encoded key that uses ASCII armor. In other words, the binary has been encoded to base64 and a header and footer line has been added. This is done to make it compatible with text interfaces such as mail (Privacy Enhanced Mail or PEM). So what you do is to remove the armor. You can best do this using a PEM reader such as the one provided by Bouncy Castle. PemReader reader = new PemReader(new FileReader("spki.pem")); PemObject readPemObject = reader.readPemObject(); String type = readPemObject.getType(); byte[] subjectPublicKey = readPemObject.getContent(); System.out.println(type); X509EncodedKeySpec spec = new X509EncodedKeySpec(subjectPublicKey); KeyFactory kf = KeyFactory.getInstance("RSA"); RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(spec); System.out.println(pubKey); which prints PUBLIC KEY followed by Sun RSA public key, 1024 bits params: null modulus: 119445732379544598056145200053932732877863846799652384989588303737527328743970559883211146487286317168142202446955508902936035124709397221178664495721428029984726868375359168203283442617134197706515425366188396513684446494070223079865755643116690165578452542158755074958452695530623055205290232290667934914919 public exponent: 65537 For the skeptics - hi neubert ;) - here is the definition of SubjectPublicKeyInfo from the X.509 specification: SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING } where subjectPublicKey contains the encoded public key in PKCS#1 format - in the case of an RSA public key, of course. And here is the decoded version of neubert's key so you can compare. The parsed key in Java is the same key.
d10605
http://forums.xamarin.com/discussion/7327/system-net-webexception-error-nameresolutionfailure Owen's solution works for me: "For me, in release mode, I checked the box marked Internet in the Required permissions section of the AndroidManifest.xml file found under the Properties folder. Debug mode doesn't need this checked but Release mode does - which you need if sending the APK by email for installation - which works great by the way. In case anyone is interested, you also have to sign your app and produce the private key following these instructions here: http://developer.xamarin.com/guides/android/deployment,testing,_and_metrics/publishing_an_application/part_2-_publishing_an_application_on_google_play/"
d10606
We have already fixed the issue for versions >= 9.1.0. Please try to install version 9.1.0 (or higher) with c8y install command. If administration/tfasettings is still missing use npm cache clean --force and then once again try to install version 9.1.0 (or higher) with c8y install command. Best regards Dawid
d10607
A simple sample based on your code, it refresh the DataGrid every 1 second. * *In class Tabs, start a new thread by StartMockValue to mock Time value. *In StartRefreshDataGrid, start a new thread to determine whether to update the DataGrid *If the Time is different from DisplayTime, then set UserTab -> DisplayTime to notify property changed. *Finally, the DataGrid updated by new data. Tabs.xaml <Window x:Class="TestWpfApp.Tabs" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <StackPanel> <DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" Height="350" EnableRowVirtualization="False"> <DataGrid.Columns> <DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" /> <DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status"/> <!--NOTE: bind 'DisplayTime' instead of 'Time'--> <DataGridTextColumn Header="Time" Binding="{Binding DisplayTimeString}" IsReadOnly="True"/> <DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" /> </DataGrid.Columns> </DataGrid> </StackPanel> </Window> Tabs.xaml.cs using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace TestWpfApp { public partial class Tabs : Window { public Tabs() { InitializeComponent(); this.Users = new List<UserTab>(); UserTab user = new UserTab(); this.Users = user.GetUsers(); dgSimple.ItemsSource = this.Users; this.StartMockValue(); this.StartRefreshDataGrid(); } private List<UserTab> Users; private void StartMockValue() { // NOTE: this is a thread to mock the business logic, it change 'Time' value. Task.Run(() => { var rando = new Random(); while (true) { foreach (var user in this.Users) { if (rando.Next(0, 3) == 1) { user.Time = user.Time + 1; } } Thread.Sleep(1000); } }); } public void StartRefreshDataGrid() { // NOTE: this is a thread to update data grid. Task.Run(() => { while (true) { foreach (var user in this.Users) { // NOTE: update if the time changed. if (user.DisplayTime != user.Time) { user.DisplayTime = user.Time; } } // NOTE: refresh the grid every seconds. Thread.Sleep(1000); } }); } } } UserTab.cs using System; using System.Collections.Generic; using System.ComponentModel; namespace TestWpfApp { public class UserTab : INotifyPropertyChanged { public int Id { get; set; } public string AgentName { get; set; } public string Extension { get; set; } public string Name { get; set; } public DateTime Birthday { get; set; } public string RowDetail { get; set; } public int ActiveParticipants { get; set; } public int HeldParticipants { get; set; } public int Duration { get; set; } public string CallStatus { get; set; } public string QueueName { get; set; } // NOTE: this is the 'real time', some business thread will update the value. public int Time { get; set; } private int displayTime; // NOTE: this is the 'displayed time' in the DataGrid. public int DisplayTime { get => displayTime; set { displayTime = value; this.OnPropertyChange(nameof(this.DisplayTimeString)); } } public string DisplayTimeString => $"{displayTime / 60 / 60}:{displayTime / 60 % 60}:{displayTime % 60}"; public string CallStatusColor { get; set; } public bool isRowDetail { get; set; } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChange(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public List<UserTab> GetUsers() { var maxSeconds = 24 * 60 * 60; var random = new Random(); List<UserTab> users = new List<UserTab>(); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) }); users.Add(new UserTab() { CallStatusColor = "#d70d0d", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) }); users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) }); users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) }); users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) }); users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) }); users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) }); users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) }); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) }); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) }); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) }); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) }); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) }); users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) }); return users; } } }
d10608
Issue is solved. Added script to ~/.bashrc: if [ "$TERM" = "xterm" ]; then setxkbmap -layout "us" fi
d10609
Absolutey-positioned elements are no longer part of the layout. They have their own layout context. Therefore they cannot know how big their parent element is. You need to use JavaScript to solve this or consider why you need absolute positioning at all. You can use: .yellowDiv { background-color:#ffff00; height:100%; }
d10610
You should put your RewriteRule before Wordpress Dispatcher: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /sitegroup/ RewriteRule ^pages/GA/GA_Be\.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenforum-ideengarten [R=301,L,NE] RewriteRule ^pages/GA/GA_Bg\.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#gartenplanung-landsc‌​haftsplanung [R=301,L,NE] RewriteRule ^pages/GA/GA_En\.shtml$ http://www.example.com/sitegroup/garten-und-landschaftsbau/#erdsondenbohrung-erd‌​waerme [R=301,L,NE] </IfModule> # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /sitegroup/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /sitegroup/index.php [L] </IfModule> # END WordPress Otherwise the request will first be handled by the Dispatcher and never reach your rule.
d10611
Yes your analysis is right. The code snippet is egregious. The correct way in React to initialize any code when DOM elements are finally available is via a callback ref. const initImageHelper = useCallback( (element) => { if (element) { const croppieInstance = new Croppie(element, settings); croppieInstance.bind({ url: image }); setCroppie(croppieInstance); } }, [image] ); {image !== "" && ( <Grid item container justify="center" xs={12}> <div id="image-helper" ref={initImageHelper}></div> </Grid> )}
d10612
After seeing your database design, I would suggest 2 things based on your queries. i) You are using LIKE queries to match strings, so create a INDEX on your GENOTYPE column, that will give performance boost. ii) Try using MyIsam engine, and a FULL TEXT engine on GENOTYPE column , based on what kind of matches you are doing on your column strings. Are your queries like: a) SELECT Gene FROM genotypegene WHERE Genotype like 'YYY%' (starts with ) or b) SELECT Gene FROM genotypegene WHERE Genotype like '%YY%' (contains ) Please share an exact query, that would help more.
d10613
Why jdbc odbc driver written as jdbc.odbc.JdbcOdbcDriver or sun.jadbc.odbc.JdbcOdbc Driver? Because (presumably) there are two different JDBC->ODBC driver classes, and those are their respective fully qualified class names. (Your question is a bit like asking "why are tyres called Michelin and Goodyear?") In which file the name is stored? That entirely depends on the design of your application and/or the framework it is using for persistence. eg. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") In that example, the class name is hard-wired into the source code. Why? You'd need to ask the person who wrote it!! And What are the functions of jdbcodbc driver and odbc driver? A plain ODBC driver provides client-side ODBC APIs that an application can use to make calls to a database. The driver implements that functionality by interfacing with the vendor-specific native database protocols and / or APIs. Thus, the driver is hiding the database-specific stuff behind a database independent facade. A plain JDBC driver does the same thing except that it is providing JDBC APIs. A JDBC-ODBC driver is actually a "bridge" between the JDBC and ODBC APIs. The application makes JDBC calls that are mapped to ODBC class by the driver. This driver then calls a plain ODBC driver which talks to the actual database. (You would use this if you had a database that had only ODBC drivers, and you wanted to access it from an application implemented to use JDBC.) For more information on JDBC and ODBC, refer to the respective Wikipedia pages, etcetera. A: When you use Class.forName(), you create a new class with the given fully qualified name. Since you connect to a DB, you must use the DB driver specific to the type of connection you use. After that I assume you will use DriverManager to create a connection to that resource. The DriverManager will look for classes that can use the connection string you pass to it.
d10614
Let me see if i understand. You want to store data in session, like a shopping cart? If you want to store in session an entire object you can set it in a usebean. <jsp:useBean id="objectname" scope="session" class="com.mypackage.myclass"/> This way you can call the object and it's methods wherever the usebean is. I hope this could help.
d10615
You need to do a couple of changes. First your EmployeeClass should have a DateClass attribute instead of int[] and the setDateOfHire() method must call the setDate() method that is available in the DateClass that has 3 parameters: public class EmployeeClass { private DateClass dateOfHire; public void setDateOfHire(int[] dateOfHire) { this.dateOfHire.setDate(dateOfHire[0], dateOfHire[1], dateOfHire[2]); } public int[] getDateOfHire() { return dateOfHire.getDate(); } } This would work, but I would suggest you review your class design. Having int arrays defining dates is a really bad practice. A: You're declaring an array of integer primitives private int[] dateOfHire; To declare an array of DateClass simply use private DateClass[] dateOfHire The primitive or class defined before the [] is what determines the type of array that is initialized You can use this as a reference A: You will need to create a DateClass object to use its methods. Consider changing your EmployeeClass like so: public class EmployeeClass { private int[] dateOfHire; // not sure of the purpose of this array private DateClass dateClassObject; // your variable name is up to you public EmployeeClass () { // Constructor for this class dateClassObject = new DateClass(); // created a new DateClass in the constructor } public void setDateOfHire(int[] dateOfHire) { // this dateOfHire array is the array that is passed in when // method is called. Do not confuse it the array declared as a property. int day = dateOfHire[0] // assuming the day is in index 0 of the array int month = dateOfHire[1] // assuming the month is in index 1 of the array int year = dateOfHire[2] // assuming the year is in index 2 of the array dateClassObject.setDate(month, day, year); // changed to dateClassObject. Also changed setDate to pass correct parameters } public int[] getDateOfHire() { // changed String[] to int[] because returned value of getDate() is a int array. return dateClassObject.getDate(); // changed to dateClassObject. Removed the parameter. } } A: In setDateOfHire just set the value instead of calling a method on it: public void setDateOfHire(int[] dateOfHire) { this.dateOfHire = dateOfHire; } Compare it with the way you implements the setters in the DateClass.
d10616
You're adding HTML so you supply the string to the html property, instead of text in the object initialiser: 'html': '<i class="fa fa-edit fa-fw"> </i>'
d10617
You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method: Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest)); There is also an async version if you are using async/await Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest)); A: The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work. Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument. Defining an Action avoids this problem because it specifies a method call that won't be made immediately. However, a more colloquial way to specify this in NUnit is by using a lambda directly... Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException); A: Wrap method you are testing into an Action Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest); Assert.That(parseFromCsv, Throws.ArgumentException) And when testing for common exceptions, such as ArgumentException, always test for exception message as well. Because common exception can occur in some other places and test will pass for a wrong reason. I prefer to use FluentAssertions, which I found little bid more readable. Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest); parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");
d10618
In fact setting the rules iptables -A DOCKER -p tcp -m tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53 iptables -A DOCKER -p udp -m udp --dport 53 -j DNAT --to-destination 172.17.0.1:53 does it. When I first tried that, I simply missed to see, that my request would have come from "outside" the server to work, not from inside to the loopback device. Still not a pretty solution but it does the job. I'm looking forward to see better solutions from you guys. (Bounty stands!)
d10619
Use this format: "dd/mm/yyyy hh:mm:ss.000"
d10620
I think that your code is correct, but maybe the question that you are trying to solve is not clear in the sense of the output that you expect. In the example of a cloud of homogeneously distributed unlabelled 3D points, there is no unique way to perform a dichotomy, separating the points with a unique, "ideal" surface. You can do this for the individual Cartesian components of the set of points though, and this is what your code achieves. The first plane, shown in red color in the panel on the left in the figure below, separates the points in a linearly optimal way by a plane that only considers the x-coordinate of the points as a function of their position, leading to a function of the type x=f(y,z). The second plane (green, on the right) is the result of a linear fit of the y-component of the points, y=g(x,z); and the third (shown in blue, in the middle) is a linear fit of the z-component of the points in the set z=h(x,y). The three planes are certainly different, because they represent fits to different values. Hence, I don't think that there is anything wrong with your code and with your result. Unlike the case described here, it is often possible to define meaningful (hyper-)planes separating different types of points, (like points with a certain value, e.g., temperature; or points with different attributes like "yellow" and "purple" points). It then depends on the distribution of these points in space whether they are linearly separable or not. In the latter case there are often solutions, too, but they are more complicated. For more information on such cases you may want to read about Support Vector Machines (SVM). Several R packages provide algorithms for SVMs such as, e.g., e1071 or the popular caret library.
d10621
It seems you are not retaining imgArray. Are you? Try, imgArray = [[NSMutableArray alloc] initWithCapacity:10] if not. A: just do imgArray = [[NSMutableArray arrayWithCapacity:10] retain]; all class methods if return an object is returned with retain count 1 and object already in autorelease pool so if want to use that object beyond the current working block the you should always retain that object because then reference is lost outside the block.
d10622
I think you're looking for IList<T>. Sample pasted from the MSDN site: T this[ int index ] { get; set; } EDIT MORE: This is the entire class I just Reflected to show you exactly how the interface is described in the framework: [TypeDependency("System.SZArrayHelper")] public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable { // Methods int IndexOf(T item); void Insert(int index, T item); void RemoveAt(int index); // Properties T this[int index] { get; set; } } A: I am not aware of such an interface in the BCL. A: There is no interface that only implements an indexer (generic or otherwise). The closest you can get is use some of the collection interfaces, such as IList.
d10623
Welp, after many hours, I was able to deduce that the error was caused by the documentSetDirectory computed variable. Apparently, the compiler was not happy about converting the result of a try statement into an optional. Instead, I had to wrap the statement in a do catch block. The following code fixed my problem: fileprivate static var documentSetDirectory: URL { let directory = libraryDirectory.appendingPathComponent("MemberDocumentSets"); do { try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: nil); } catch { /* * Do nothing. So why have a catch block at all? Because: for some reason * this prevents the compiler from spitting up. Apparently it didn't like * converting the `try` to an optional here. Weirdly, I'm still doing the * optional conversion elsewhere in this same class without issue (see * computed variables below). * * ¯\_(ツ)_/¯ */ } return directory; } fileprivate static var imageDirectory: URL { let directory = documentSetDirectory.appendingPathComponent("Images"); try? FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: nil); return directory; } Evidently, this must be a bug with the compiler. I created an empty project and copied the original code, but it compiled without issue and I was unable to find any project setting differences that caused the same error. In any case, I'm glad to have found a solution, and hopefully it'll save some time for a few poor souls in the future.
d10624
You are not checking the return value of your scanf, otherwise you would know that it returns 0, as in 'no elements read'. Your scanf expects you to write exactly what you are putting in there, so, if you entered Enter 3 Ints and 1 Char:2 3 4 c, it would probably work. What you want, however, is this: printf("Enter 3 Ints and 1 Char: "); if (scanf("%d %d %d %c", &a, &b, &c, &d) != 4) printf("Invalid input detected\n"); else printf("The numbers are:\n%d\n %d\n %d\n %c\n", a, b, c, d); The first line will print the prompt to the console, the second will read the values into variables. There is no need to create separate pointer variables for this purpose.
d10625
There are aws sdks available for different platform. You need to implement one of them according to your backend technology and expose your api and test it out in the post man. Please go through this link docs.aws.amazon.com/cognito-user-identity-pools/latest/… There are sdks links at the bottom.
d10626
It is a better approach that you would use the terminal to create your project (and then open them in Visual Studio). It is far more convenient for the Monogame community to release NuGet templates of the projects rather than releasing plugins for Visual Studio, and therefore it is safe to assume that Monogame won't be releasing such plugins for Visual Studio anytime soon. Make sure you have dotnet-sdk installed and the Monogame tools are installed by doing all the steps mentioned here, Including the last two scripts dotnet tool install --global dotnet-mgcb-editor mgcb-editor --register and dotnet new --install MonoGame.Templates.CSharp Now use the command dotnet new to view all the templates. You will probably see an output such as Templates Short Name Language Tags ------------------------------------------------------ ------------------- ------------ ---------------------- ... ... MonoGame Android Application mgandroid [C#] MonoGame MonoGame Cross-Platform Desktop Application (OpenGL) mgdesktopgl [C#] MonoGame MonoGame iPhone/iPad Application mgios [C#] MonoGame MonoGame Windows Universal Application (CoreApp) mguwpcore [C#] MonoGame MonoGame Windows Universal Application (XAML) mguwpxaml [C#] MonoGame MonoGame Windows Desktop Application (Windows DirectX) mgwindowsdx [C#] MonoGame MonoGame NetStandard Library mgnetstandard [C#] MonoGame MonoGame Pipeline Extension mgpipeline [C#] MonoGame MonoGame Shared Library Project mgshared [C#] MonoGame ... ... Select the project you want to create, for example dotnet new mgwindowsdx -o MyGame This will create a folder "MyGame" and put the code for your game. You can open the .csproj file using Visual Studio.
d10627
I would still use IIntroPart (or have a look to CustomizableIntroPart): The intro part is a visual component within the workbench responsible for introducing the product to new users. The intro part is typically shown the first time a product is started up. The intro part implementation is contributed to the workbench via the org.eclipse.ui.intro extension point. (See this thread as an example). There can be several intro part implementations, and associations between intro part implementations and products. The workbench will only make use of the intro part implementation for the current product (as given by Platform.getProduct(). There is at most one intro part instance in the entire workbench, and it resides in exactly one workbench window at a time. See "[Eclipse Intro] Make my own welcome page." as an example. If you don't use it, at least have a look at the code of IIntroPart to see how it
d10628
Basically if you're not planning to expose the usage of the enum, for e.g. Direction then you could do it right in the class which is using it. I mean that you could make it private, such as: 1 As inner type (direct usage) public class Foo { private Direction directionType = Direction.UNKNOWN; // some code private enum Direction { INPUT, OUTPUT, UNKNOWN } } 2 As an external type Write enums w/ logic (if there is some) in the separate *.java files. This is absolutely fine approach. Example below is the classical one from the Oracle Guide: public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java Planet <earth_weight>"); System.exit(-1); } double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } } Summary It really depends on the context and the architecture decision. Basically grouping enums in the one java file is not the best solution especially when your application begins 'to grow'. The code will be hard to read for other developers that will work on it. I suggest to use the approach #1 or #2 A: The general practice that I have seen is to have a package for all the enums and each enum is in its own java file with all the associated methods for that enum. If all you're going to have is just a bunch of enums with no methods operating on the contents of the enum, I guess it then just boils down to a matter of choice. Imagine the common scenario where each enum has several methods associated with the constants it holds. You can see that having several enums in a single class can very easily make the code clunky. But on the other hand, if you are just going to have a collection of enums, it might even be desirable to put them all together in one place for the sake of brevity. There would be no difference as far as performance and portability are concerned - you just need to think whether the code becomes clunky or not. A: Same as for any other class or interface. The fact that it's an enumeration doesn't change the basic nature of the question.
d10629
Try putting that code inside onCreate, before the setContentView : @Override protected void onCreate(@Nullable Bundle savedInstanceState) { String SavedLocaleLang = preferences.getString("LocalLang", null); Locale locale = new Locale(SavedLocaleLang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getResources().updateConfiguration(config, getResources().getDisplayMetrics()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
d10630
Check for imprecise external abort, which does not cause exception immediately.
d10631
Looking at the JSON-C docs it doesn't appear to have an easy way to drill down into the structure. You'll have to do it yourself. Something like this: struct json_object *json_object_get_with_keys( struct json_object *obj, const char *keys[] ) { while( keys[0] != NULL ) { if( !json_object_object_get_ex(obj, keys[0], &obj) ) { fprintf(stderr, "Can't find key %s\n", keys[0]); return NULL; } keys++; } return obj; } Pass it a null terminated array of keys and it will drill down (or return null). const char *keys[] = {"scores", "math", "highest", NULL}; struct json_object *obj = json_object_get_with_keys(top, keys); if( obj != NULL ) { printf("%s\n", json_object_to_json_string(obj)); } Instead, use JSON-Glib. It has JSONPath which will be more familiar, you can use $.scores.english.highest. JsonNode *result_node = json_path_query( "$.scores.english.highest", json_parser_get_root(parser), &error ); if( error != NULL ) { fprintf(stderr, "%s", error->message); exit(1); } /* It returns a node containing an array. Why doesn't it just return an array? */ JsonArray *results = json_node_get_array(result_node); if( json_array_get_length( results ) == 1 ) { printf("highest: %ld\n", json_array_get_int_element(results, 0)); } else { fprintf(stderr, "Couldn't find it\n"); } It's a little awkward to use, but you can make that easier with some wrapper functions to take care of the scaffolding and error handling.
d10632
You could register a custom JacksonModule with a mapper for Boolean type: private val YNToBooleanDeserializer = object : JsonDeserializer<Boolean>() { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Boolean { return p.readValueAs(String::class.java) == "t" } } to register, use: csvObjectMapper.registerModule(SimpleModule().addDeserializer(Boolean::class.java, YNToBooleanDeserializer))
d10633
Please check below code : void main() => runApp(MyApp()); class MyApp extends StatelessWidget { var scrollController = ScrollController(); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Home()); } } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { return Scaffold( body: DefaultTabController( length: 2, child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return [ SliverAppBar( expandedHeight: 200.0, floating: true, pinned: true, snap: true, actionsIconTheme: IconThemeData(opacity: 0.0), flexibleSpace: Stack( children: <Widget>[ Positioned.fill( child: Image.network( "https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350", fit: BoxFit.cover, )) ], ), ), SliverPadding( padding: new EdgeInsets.all(16.0), sliver: new SliverList( delegate: new SliverChildListDelegate([ TabBar( labelColor: Colors.black87, unselectedLabelColor: Colors.grey, tabs: [ new Tab(icon: new Icon(Icons.info), text: "Tab 1"), new Tab( icon: new Icon(Icons.lightbulb_outline), text: "Tab 2"), ], ), ]), ), ), ]; }, body: Center( child: Text("Sample text"), ), ), )); } }
d10634
You can change the href attribute of your link tag when click on the button So using your example $('li').on('click', function() { $('link').attr('href','new_file_path_here'); }); This is a basic example, you can give your link tag an id and target it that way Also see How do I switch my CSS stylesheet using jQuery?
d10635
It looks like you are linking against the opencv libs for Visual Studio 2010. You will have to compile the opencv library for Visual Studio 2012 yourself as the pre-built ones are for Visual Studio 2010. The information on how to do that can be found under Installation by Making Your Own Libraries from the Source Files.
d10636
Copying data from the redux store to one's component state is an anti-pattern Instead, you should modify your redux store, for example using an object to store data, so you'll be able to store datas for multiples seasons : sportsData: { '1617': { ... }, '1718': { ... }, } This way you'll be able to fetch both seasons in the same time : componentDidMount() { const seasons = ['1718', '1617']; const promises = seasons.map(fetchGames); Promise.all(promises).catch(…); } And connect them both : // you can use props here too const mapStateToProps = (reduxState, props) => ({ // hardcoded like you did oldGames: reduxState.GamesReducer.sportsData['1617'], // or using some props value, why not newGames: reduxState.GamesReducer.sportsData[props.newSeason], }; Or connect the store as usual and go for the keys: const mapStateToProps = (reduxState, props) => ({ games: reduxState.GamesReducer.sportsData, }; … render() { const oldGame = this.props.games[1718]; const newGame = this.props.games[1718]; … } Redux is you single source of truth, always find a way to put everything you need in Redux instead of copying data in components
d10637
First off, don't use $Matches for anything user-defined - it's an automatic variable. With that out of the way: since Select-String may return multiple lines, you should sort them by length and test the length of the longest one: $FileContent = Get-Content "YourFile.txt" $LongestMatch = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches |Sort-Object {$_.Line.Length} |Select-Object -Last 1 if($LongestMatch.Line.Length -gt 30){ # We found a match in a string longer than 30 chars! # run plink here! } A: This may be too simplistic. I feel like there is something I must have missed in the question. $FileContent = Get-Content "YourFile.txt" $Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches if ($Matches -eq 30) { & "d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm% }
d10638
The 64-bit GDB is perfectly capable of debugging both 64 and 32-bit programs. You don't need to invoke 32-bit GDB.
d10639
If you override loadView(), it is up to you to create and set the controllers "root" view. If you add this to your code: override func loadView() { title = "My Pictures" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPicture)) // add these three lines let newView = UIView() newView.backgroundColor = .white view = newView view.addSubview(table) // ... rest of your original code You should be able to navigate to your controller. That said --- unless you have a specific reason to override loadView(), you probably shouldn't. All the code in your example would normally go in viewDidLoad(). Edit - for some clarification... I think Apple's documentation is a bit ambiguous... As I understand it, any view controller that is a descendant of UIViewController created via code only (UIViewController, UITableViewController, UICollectionViewController, etc) generates its own "root" view unless we override loadView() in which case it is up to us to instantiate and provide that root view. So, why would we want to provide that view? We may want to provide a custom UIView subclass. For example, if I have a "Gradient" view that sets its base layer class to a CAGradientLayer - so I don't have to add and manage a sublayer. I can override loadView() and set the root view of my controller to that Gradient view. I've put up a complete example on GitHub. The only Storyboard in the project is the required LaunchScreen --- everything else is done via code only. It starts with 3 buttons in a navigation controller: * *The first button pushes to a simple UIViewController with a label *The second button pushes to a UITableViewController, where selecting a row pushes to a "Detail" UIViewController *The third button pushes to a simple UIViewController with a label and a gradient background The third example is the only one where I override loadView() to use my custom Gradient view. All the others handle all the setup in viewDidLoad() Here's the link to the project: https://github.com/DonMag/CodeOnly A: As DonMag said above, I need to give view a value here as it is nil by default(without using interface builder). And here is a reference I found could explain when to use viewDidLoad or loadView, in my case I used the 2nd way to create all the views programatically. Reference: https://stackoverflow.com/a/3423960/10158398 When you load your view from a NIB and want to perform further customization after launch, use viewDidLoad. If you want to create your view programtically (not using Interface Builder), use loadView. Update: Per DonMag's example. It is clearly that we could use both of way to set the view, either in viewDidLoad or in loadView. And the best practice to use loadView is when we need to use some custom UIView as root view. Meantime, I find a good article about this topic. It is an old one, though I think the concepts will not change. http://roopc.net/posts/2015/loadview-vs-viewdidload/ To conclude, we can set up the view hierarchy in either loadView or viewDidLoad, as long as we’re aware of when which method gets called. The most important thing to remember is that if you override loadView, you should set the view property, while if you override viewDidLoad, you should only read the view property, which should have been already set.
d10640
I believe you're asking StackOverflow to help you solve the knapsack problem. If you manage to find a polynomial solution, you can go claim a million dollars reward for solving P=NP. Good luck !
d10641
If you want to simply import Goofus back into Gallant (which will be the same as a patch), simply download an archive (zip or tarball) of Goofus, and uncompress it somewhere, then use it as working tree for a one-time import: cd /path/to/Gallant git --work-tree=/path/to/Unzipped/Goofus add . git commit -m "Goofus import" git push The git add part will detect any modified, added or removed files from Goofus, and add them in the Gallant repo.
d10642
TL;DR you have to use MATCH_PARENT for the ImageView width: navBarBackground.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resources.getDimensionPixelSize(resourceId))); By using navBarBackground.getWidth() you set the width of the ImageButton to zero, so all you see is the window background. This happens because the ImageView is not yet completely laid out when you evaluate the width in onCreate(). (see also for example this blog post on The Life Cycle of a View in Android) Useful tool for debugging layouts: Layout Inspector
d10643
A bit late but I think give an answer is interesting for futur SO users. So there is multiple way to sync your code to this and so you should add a custom waiter. window.onbeforeunload = function(event) { document.body.fade(); while ((new Date()).getTime() < (new Date()).getTime()) + (1 *1000)); } I guess you could also try with promises: function sleep(time) { return new Promise((resolve) => { setTimeout(() => { return resolve(null); }, time); }); } window.onbeforeunload = async function(event) { document.body.fade(); await sleep(1 * 1000); }
d10644
The code is invalid. The type of 5/2 + p is int *, while %d requires an int. Kindly give the step by step explanation of this program. 5/2 + p = // 5/2 is equal to 2 2 + p = // p has type int 2 * sizeof(int) + (char*)p = // p is 5 2 * sizeof(int) + 5 = // sizeof(int) if 4 on your platform 2 * 4 + 5 = 13
d10645
It works if you give the ChordSymbol some length of time. The analysis weights the components by time, so a time of zero (default for ChordSymbols) will give you nonsense. d = harmony.ChordSymbol('D') d.quarterLength = 2 s = stream.Stream([d]) s.analyze('key') A: It looks like music21 Analyze is not working ok with ChordSymbol. As an alternative, you can manually set all the chord's notes, and analyze that. The code: string = 'D, Em, F#m, G, A, Bm' s = stream.Stream() for d in string.split(','): print(harmony.ChordSymbol(d).pitchedCommonName) for p in harmony.ChordSymbol(d).pitches: n = note.Note() n.pitch = p s.append(n) key = s.analyze('key') print(key) returns a D major key, as expected.
d10646
To answer your last questions, your empirical case seems to prove they're not uncompressed once loaded. To convert them into uncompressed data, you can draw them (once) in a CGBitmapContext and get a CGImage out of it. It should be well enough uncompressed. Off my head, this should do it: CGImageRef Inflate(CGImageRef compressedImage) { size_t width = CGImageGetWidth(compressedImage); size_t height = CGImageGetHeight(compressedImage); CGContextRef context = CGBitmapContextCreate( NULL, width, height, CGImageGetBitsPerComponent(compressedImage), CGImageGetBytesPerRow(compressedImage), CGImageGetColorSpace(compressedImage), CGImageGetBitmapInfo(compressedImage) ); CGContextDrawImage(context, CGRectMake(0, 0, width, height), compressedImage); CGImageRef result = CGBitmapContextCreateImage(context); CFRelease(context); return result; } Don't forget to release the CGImage you get once you're done with it. A: This question totally saved my day! thanks!! I was having this problem although I wasn't sure where the problem was. Speed up UIImage creation from SpriteSheet I would like to add that there is another way to load the image directly decompressed, qithout having to write to a context. NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:(id)kCGImageSourceShouldCache]; NSData *imageData = [NSData dataWithContentsOfFile:@"path/to/image.png"]]; CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)(imageData), NULL); CGImageRef atlasCGI = CGImageSourceCreateImageAtIndex(source, 0, (__bridge CFDictionaryRef)dict); CFRelease(source); I believe it is a little bit faster this way. Hope it helps!
d10647
In general, ClickOnce can't be used to install services. There is typically a lack of permissions, but also the location is incorrect, etc. For details, see MSDN on Choosing Between ClickOnce and Windows Installer for more details. If you want to install a service, you should do a traditional installation.
d10648
Try this one var descriptionValue = currentRecord.getCurrentSublistValue({ sublistId: item, fieldId: "custitem_celigo_sfnc_salesforce_id", line:line })
d10649
As soon as you need to address a customer by Last Name, First Name you're screwed. Sorting becomes a problem, etc. It's very little extra effort to ask for each separately even if you don't think it's useful now. But to go back and do it is very problematic. Data atomization is important.
d10650
It's similar code, but using the class NSMutableRequest. You can set the httpbody and other parameters to communicate with the server. check the documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html to post something, just put setHTTPMethod:@"POST"and assign the data to post using setHTTPBody:
d10651
Of course you can, you need to use the selected attribute on the <option> you want to show. First remove the selected attribute from the first <option>: <option value="" disabled>Select your breakast</option> Then in the foreach loop you need an if condition: $results123 = $optionquery1->fetch(); $selectedrecipe = $results123['id']; foreach($breakfast as $breakfast): ?> <option value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option> <?php endforeach;} ?> Notice I have removed the while loop since we are sure Mysql will return only one record (WHERE ID = <ID>).
d10652
what i recommend is to have the values you should have, then generate the output (check underscore.js) and each time you click a sort, then generate it again and replace it. what i mean, is that you havethe primivitve data: var list = [{name: 'Argentina Wine Awards', medal: 'silver', ... }, {}, ...]; then, when is clicked a sort link, you sort the list array by the correct property and generate a new html (using underscore templates) and replace the old html with the new one.
d10653
try this using the ? operator: <option *ngFor="let industrySegment of industrialDropdown?.IndustrySegments" value="{{ industrySegment }}">{{ industrySegment }}</option> industrialDropdown is not present when template is rendered
d10654
I would replace http://localhost:xxxxx/ with the actual internal IP address of the server (probably something like http://192.168.x.x:xxxxx/) - just make sure your server and mobile device are connected to the same network through wi-fi not gsm network. Also make sure you updated the domain white list. more info how to do that can be found here http://docs.phonegap.com/en/2.2.0/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide hope this will help, good luck!
d10655
NO, it's not possible. Angular is a FRONT-END framework A: Strictly speaking, It is not recommended but I would say it is possible. Basically, everyone will say that it is just "FrontEnd" web framwork. But I see that it also can be a multi-platform framework for frontend and backend as well. The main Angular core team didn't define this framework as one "Frontend" framework. Rather, it says one framework across all platform. It means it can be transformed anything. They think bigger than non-angular developers. I see the bigger picture and future with Angular. Of course, this is just mainly used for the mobile and desktop for now. Many developers have a skeptical idea of this. I would agree. For example, Ionic/Nativescript. They adopted Angular as a core framework. Yes, this is for mobile(Frontend right?). However, What about Nest.js. Cool right? This is totally server-side web framework for "Backend". The fact is that this framework heavily referenced "Angular framework" such as Angular-like Dependency Injection system. They even mentioned "The architecture is heavily inspired by Angular." Let's say you are a pioneer and you can make it possible. I highly recommend to play with the Angular platform source codebase. Git clone and modify something and build it(it takes some time but it should work at your local computer). If you see the github codebase, this is huge and actually have capability or "potential" to serve as a backend. Of course, it depends on a situation. So ask yourself What kind of your expectation from it and what the purpose is. Angular is just javascript(transpiled by Typscript) program. After having transpiled javascript static files, it requires a http server to serve the files. Luckily, Angular Frmaework has its own local server( called ng serve yes we know this one which is a cute http/https server. Thus, technically speaking, Angular is "Framework" not library. Framework includes many tools and even app servers in it. I would say that it's possible and it can even directly communicate with other Angular applications with websocket and webRTC as well. Don't make me wrong. Once again, It is only possible with the embedded Angular Serve module(ng serve) if you don't want to install other 3rd party http server. These days, What a Javascript/Typescript world. Javascript/Typescript can do everything. Angular is a part of it and it is the most advanced web framework among others. Check out the following github codes. Hope you like my answer. Take care. angular-cli/packages/angular_devkit/core/node/ architect-command.ts angular devkit dev-server Anything is possible
d10656
$!N;$b1 at the line before last first appends, then branches (as it is now the final line), wheras $b1;$!N doesn't branch, appends, doesn't enter the block. following is $!b2 which isn't taken, followed by d deleting the pattern. (and ending the script, as there is no more input) – Hasturkun
d10657
componentDidMount(){ this.dateString = this.props.navigation.getParam('dateString', moment()); } Code B: state = { dateString: moment() } componentDidMount(){ const dateString = this.props.navigation.getParam('dateString', moment()); this.setState({ dateString }) } dateString is a parameter passed from previous screen. I've console.log in render() and found that they appeared to be exactly the same number of times? I was expecting Code B to render one extra time since it uses setState? Which way of above is a better approach? A: Not sure if this is the case in this your specific case, but: React may batch multiple setState calls together. So even if you have multiple async setState calls, there might only one (re-)render. So you shouldn’t rely on the number of calls to render A: Check the value of this.props.navigation.getParam('dateString', moment()) in render and componentDidmount(). If both values are same it wont trigger a re-render as react re-render the components only if state change there if you made it PureComponent. In this jsfiddle you can try running the code by changing Pure and normal component and can see the difference. A: Try to put in the Code B the state inside constructor() method like this: constructor(){ super(); this.state = { dateString: moment() } } I don't usually use to put state floating in the class, I always put him in the constructor.
d10658
Since b = True, zs.extend([b for i in range(k)]) is effectively zs.extend([True for i in range(k)]) or zs.extend([True, True, ..., True (k times)]). Update. I'm assuming that the intended (indented) code is the following: def uncompress(xs): zs = [] b = True for k in xs: zs.extend([b for i in range(k)]) b = not b return zs Then if xs is, say, [2, 1, 3], then: * *after the first for-loop execution (so called "iteration"), zs = [] + [True, True] = [True, True] and b becomes False, *then zs = [True, True] + [False] = [True, True, False] and b becomes True, *finally zs = [True, True, False, True, True, True] and b becomes False. So if xs == [s, t, u, v, ...] then zs is True s times, False t times, True u times, False v times and so on.
d10659
A load balancer front end can have more than one certificate attached. Create a new managed certificate and attach it to the front end. Once you have more than one certificate attached, you can then remove the one you no longer want to use without downtime.
d10660
Try this may be it will helps you : $cd = date('Y-m-d'); $this->db->where("date_format(STR_TO_DATE(vd, '%d/%m/%Y'),'%Y-%m-%d') >",$cd); $query =$this->db->get('warranty'); You need to change date format if you use date_format in your query you are changing in same format may be that is the reason it is not working. try to change and compare in Y-m-d format. A: Can you check this query manually. Then try to add it in CodeIgniter $cd = date('d/m/Y');//current date select * FROM warranty WHERE DATE_FORMAT(STR_TO_DATE(vd, '%d/%m/%Y'), '%Y-%m-%d') > DATE_FORMAT(STR_TO_DATE($cd, '%d/%m/%Y'), '%Y-%m-%d') A: In your code you are using two function to restructure the date format. * *date_format *STR_TO_DATE Use STR_TO_DATE $now = date('d/m/Y'); //current date $userdate = '2009-05-18 22:23:00'; //which get from user inputs $dateModified = STR_TO_DATE($userdate,'%d/%m/%Y'); //output is 2009-05-18 So in function $this->db->where('order_date >=', $dateModified); $this->db->where('order_date <=', $now); $query =$this->db->get('warranty'); or $this->db->where('order_date BETWEEN '.$dateModified.' and '.$now); This function will give you result of userSearch input and date to now. This function simply act like between in MySQL A: **Hope this may help you...** $cd = date('d/m/Y'); $data['project'] = $this->common_model->selectRecord("SELECT * from project where project_date = '.$cd.'"); in my project this is working .. A: Try this: $cd = date('d.m.Y');//current date $this->db->where("STR_TO_DATE(vd, '%d.%m.%Y') >",$cd); $query =$this->db->get('warranty'); To be sure that it comes out in the format you desire, use DATE_FORMAT: $cd = date('d.m.Y');//current date $this->db->where("DATE_FORMAT(STR_TO_DATE(vd, '%d.%m.%Y'),'%d.%m.%Y') >",$cd); $query =$this->db->get('warranty'); A: Have you tried CAST ? SELECT * FROM warranty WHERE CAST(vd AS DATE) ....; Have you tried DATE ? SELECT * FROM warranty WHERE DATE(vd) ....; A: Change this $this->db->where("date_format(STR_TO_DATE(vd, '%d/%m/%Y'),'%d/%m/%Y') >",$cd); To $this->db->where("STR_TO_DATE(vd, '%d/%m/%Y') > NOW()");
d10661
From looking at the toy code, my first thought is just to put the f/f2 code into the actual object's constructor and do away with the free functions entirely. But assuming that isn't an option, it's mostly a matter of style/preference. Here are a few considerations: The first is easier to read (in my opinion) because it's obvious that the pointer is an output value. When you pass a (nonconst) pointer as a parameter, it's hard to tell at a glance whether it's input, output or both. Another reason to prefer the first is if you subscribe to the school of thought that says objects should be made immutable whenever possible in order to simplify reasoning about the code and to preclude thread safety problems. If you're attempting that, then the only real choice is for f() to create the object, configure it, and return const Foo* (again, assuming you can't just move the code to the constructor). A reason to prefer the second is that it allows you to configure objects that were created elsewhere, and the objects can be either dynamic or automatic. Though this can actually be a point against this approach depending on context--sometimes it's best to know that objects of a certain type will always be created and initialized in one spot. A: If the allocation function f() does the same thing as new, then just call new. You can do whatever initialisation in the object's construction. As a general rule, try to avoid passing around raw pointers, if possible. However that may not be possible if the object must outlive the function that creates it. For a simple case, like you have shown, you might do something like this. void DoStuff(MyObj &obj) { // whatever } int Func() { MyObj o(someVal); DoStuff(o); // etc } A: f2 is better only because the ownership of the int is crystal clear, and because you can allocate it however you want. That's reason enough to pick it.
d10662
log* n is the iterated logarithm, which for large n is defined as log* n = 1 + log*(log n) Therefore, log*(log n) = (log* n) - 1, since log* is the number of times you need to apply log to the value before it reaches some fixed constant (usually 1). Doing another log first just removes one step from the process. Therefore, log(log* n) will be much smaller than log* (log n) = log* n - 1 since log x < x - 1 for any reasonably large x. Another, more intuitive way to see this: the log* function is significantly better at compressing large numbers than the log function is. Therefore, if you wanted to take a large number and make it smaller, you'd get way more efficiency by computing log* n first to contract n as much as you can, then use log on that (log (log* n)) to pull down what's left. Hope this helps!
d10663
Well, I fanally found a solution. Since this is for local and presentation use only, I could bypass some securities. Basically, doing what we would normally NOT do in a website but all this WITHOUT modifying your webserver config or touching any .htaccess file. Basically, no security restrictions, just a plain old hack that poses no security breaches for your browser or your server. To be noted: * *2 different websites exist (so 2 different folders at very different locations), 1 for developpement and serious releases, one for internal and/or presentation purposes. *Every file is local abd inside the presentation folder. *No PHP code can be ran from a "file:///" link. *Access to the mysql database is done through PHP and server is on Apach24 *Reading video locally from a "file:///" link are WAY faster than from an "http://" link *Searching needs to be done in MySQL database frm a "http://" link and results need to be displayed on a webpage opened from a "file:///" link. *No changes must be made in the Browser's configuration so disabling CORS is not a solution. *Bypassing cors with methods proposed by many site won't work because of security reasons or because CORS bypass does not accept "file:///" links PHP can write files on the server which is where I decided to bypass CORS. Since XML requests through AJAX can be done on the same origin domain an thus, purely in javascript. If a file exists which contains no PHP code AND resides on the same domaine i/e "file:///", the contents can the be read wothout any problems. So I simply do the following in my db.php file: $s_mode = ""; $s_text = ""; $sres = ""; if (isset($_REQUEST["srch"])) {$s_text=$_REQUEST["srch"];} if (isset($_REQUEST["mode"])) {$s_mode=$_REQUEST["mode"];} if ($s_mode == "s") { $sres = SearchDB($s_text); WriteFile("D:/whatever/my_path/dbres.html",$sres); } // Writes the contents of the search in a specified file function WriteFile($faddress,$fcontents) { $ifile = fopen($faddress,"w"); fwrite($ifile,$fcontents); fclose($ifile); } Now using a normal AJAX request, I do 2 things. I opted to use an iframe with a "display:none" style to not bother seeing another tab openup. * *Do the actual request which opens the "cross-doamin" link in the iframe WHICH executes my db.php code. I basically open "http://127.0.0.1/whatever/db.php?param1=data&parma2=data" inside my iframe. *Once my search is done and I have the results, my db.php will save an html file with the results as it's contents in my "file:///" direct location's path so: "D:/whatever/my_path/dbres.html". I added a new function in my servcom.js. So my new file's contents looks like this: // Show page info in another page element or window with parameters (for local use only) function ServInfoLocal(dest_frame,web_page,params="",form_id="") { var sparams = params; var swpage = web_page; var iweb = document.getElementById(dest_frame); var moreparams = ""; // If we entered extra parameters including form fields, // add the the "&" before the form field list if (sparams != "") {moreparams = "&";} // Get form field values if a form id is specified if (form_id != "") { var efrm = document.getElementById(form_id); sparams += moreparams+GetDivFields(form_id); } // If destination frame does not exist, exit if (typeof(iweb) == "!undefined" || iweb == null) {return;} // Add the question mark if there is any parameters to pass if (sparams != "") {sparams = "?"+sparams;} // Show results in iframe iweb.src = swpage+sparams; } // AJAX simple HTTP GET request function ServInfo(pop_field_id,web_page,params="",form_id="",append_data_to_output = "",exec_string = "",dont_show_results = "") { var sparams = params; var swpage = web_page; var eobj = document.getElementById(pop_field_id); var moreparams = ""; // If we entered extra parameters including form fields, // add the the "&" before the form field list if (sparams != "") {moreparams = "&";} // Get form field values if a form id is specified if (form_id != "") { var efrm = document.getElementById(form_id); sparams += moreparams+GetDivFields(form_id); } // If HTML element to populate does not exist, exit if (typeof(eobj) == "!undefined" || eobj == null) {return;} if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // IE6- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Do not show any results if requested if (dont_show_results == "") { if (append_data_to_output == "y") { document.getElementById(pop_field_id).innerHTML += this.responseText; } if (append_data_to_output == "") { document.getElementById(pop_field_id).innerHTML = this.responseText; } } // Execute a string if a user defined one if (exec_string != "") { eval(exec_string); } } }; // Add the question mark if there is any parameters to pass if (sparams != "") {swpage += "?";} xmlhttp.open("GET",swpage+sparams,true); xmlhttp.send(); } // Build a parameter string with div fields of type text, hidden or password function GetDivFields(div_id) { var ediv = document.getElementById(div_id); var elem = ediv.children; var retval = ""; var ssep = ""; for (var i = 0; i < elem.length; i++) { if (elem[i].type == "text" || elem[i].type == "hidden" || elem[i].type == "password") { retval += ssep+elem[i].name+"="+pURL(elem[i].value); ssep = "&"; } if (elem[i].type == "checkbox") { if (elem[i].checked == true) { retval += ssep+elem[i].name+"="+elem[i].value; ssep = "&"; } } } return retval; } Now, my dbres.html file will contain just the div elements and all the information I need to show up in my "file:///" page from which the search request came from. So I simply have this inside my page: <div id="search-form" style="color:white;font-weight:bold;"> <input id="srch" name="srch" type="text"> &nbsp;<button class="bbut" onclick="ServInfoLocal('iweb','http://127.0.0.1/whatever/html/db.php','mode=s','search-form');">Search</button> <button class="bbut" onclick="ServInfo('search-results','dbres.html');">Click here</button> </div> <div id="search-results">Results here</div> <iframe id="iweb" style="display:none;" src=""></iframe> For now I have 2 buttons, one for the search and one to show the results from my newly created file. Now, I can show my local videos which will load in my video container with "file:///" source directly without passing through http. I'll make my results display automatic which I will be able to do myself from here on. So, if someone on planet earth wants to be able to do cross-domain searches in a MySQL database from a local file ran directly from the Windows explorer, there's not too many solutions, actually, I found none so here is at least one for who would ever need this solution. For the curious ones out there, my next step will be to loop my folder until my dbres file is present using another js function. Once my file has been fetched, call another php file which wil destroy the created file and I'll be ready for another database request from my webpage situated in a "file:///" location.
d10664
Have a look at this - I use the selector [name=Total] because it makes more sense than [id^=Total] I delegate the change to the tbody: document.getElementById("tb").addEventListener("change", function(e) { const tgt = e.target; const parent = tgt.closest("tr"); const up = +parent.querySelector(".UnitPrice").value || 0 const qty = +parent.querySelector(".Quantity").value || 0 parent.querySelector("[name=Total]").value = (up * qty).toFixed(2); const grandTotal = [...document.querySelectorAll("[name=Total]")] // all total .map(ele => +ele.value) // get each value and convert to number .reduce((a, b) => a + b); // sum them document.getElementById("GrandTotal").value = grandTotal; // assign to a field }) <table> <tbody id="tb"> <tr id="One"> <td style="font-family: papyrus;font-weight: bold;">1</td> <td width="20%"><input type="text" id="BookTitle" name="BookTitle" size="30"></td> <td width="17%"><input type="text" id="Author" name="Author" size="10"></td> <td width="20%"> <select id="Category" name="Category"> <option value="Please choose the categoty...">Please choose the Category...</option> <option value="Business">Business</option> <option value="Fiction">Fiction</option> <option value="Mathematics">Mathematics</option> <option value="Technology">Technology</option> </select> </td> <td width="13%"><input type="text" class="UnitPrice" id="UnitPrice1" name="Unit Price" step="0.01" value="0.00" placeholder="0.00"></td> <td width="13%"><input type="text" class="Quantity" id="Quantity1" name="Quantity" value="0" min="0"></td> <td width="13%"><input type="text" id="Total1" name="Total" value="0.00" readonly></td> </tr> <tr id="Two"> <td style="font-family: papyrus;font-weight: bold;">1</td> <td width="20%"><input type="text" id="BookTitle" name="BookTitle" size="30"></td> <td width="17%"><input type="text" id="Author" name="Author" size="10"></td> <td width="20%"> <select id="Category" name="Category"> <option value="Please choose the categoty...">Please choose the Category...</option> <option value="Business">Business</option> <option value="Fiction">Fiction</option> <option value="Mathematics">Mathematics</option> <option value="Technology">Technology</option> </select> </td> <td width="13%"><input type="text" class="UnitPrice" id="UnitPrice2" name="Unit Price" step="0.01" value="0.00" placeholder="0.00" onkeypress="return forNumberOnly(event)"></td> <td width="13%"><input type="text" class="Quantity" id="Quantity2" name="Quantity" value="0" min="0" onkeypress="return forNumberOnly(event)"></td> <td width="13%"><input type="text" id="Total2" name="Total" value="0.00" readonly></td> </tr> </tbody> </table> <input type="text" readonly id="GrandTotal" />
d10665
Using html2canvas could help you, it converts an element into a canvas, and then you just need to add its data as a url into an a element function download(canvas, filename) { const data = canvas.toDataURL("image/png;base64"); const donwloadLink = document.querySelector("#download"); donwloadLink.download = filename; donwloadLink.href = data; } html2canvas(document.querySelector(".card")).then((canvas) => { // document.body.appendChild(canvas); download(canvas, "asd"); }); Check a full example here https://codepen.io/koseare/pen/NWpMjeP A: Try with html2canvas; <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="all"> <h2>Sample text</h2> <table width="1080px" height="1920px" style="border-collapse: collapse"> <tbody> <tr> <td colspan="2"> <img src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png" width="600px" /> </td> <td>Sample text</td> </tr> <tr style="background: #b6ff00"> <td>Sample text</td> <td>Sample text</td> <td>Sample text</td> </tr> </tbody> </table> </div> <br /> <input type="button" id="btn" value="Download" /> <script> document.getElementById("btn").addEventListener( "click", function () { var text = document.getElementById("all").value; var filename = "output.txt"; download(filename, function makeScreenshot() { html2canvas(document.getElementById("screenshot"), {scale: 1}).then(canvas => { document.body.appendChild(canvas); }); }); }, false ); </script> </body> </html>
d10666
Unfortunately there's nothing to specifically do here other than continue to open VS Code from the activated conda environment. Conda simply wants to own the environment you work from and those settings need to propagate into the one VS Code works from to make conda work.
d10667
The shift could be caused by the hidden this pointer. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/ From the code you have pasted here void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo) I can see the callback function is a member of class CCameraInstance I'm not sure whether you are defining the function as a static function or a normal one. But in theory it should be a static function to avoid the this pointer. Using a C++ class member function as a C callback function However, I had a problem with C++/CLI even if i have define the member function as static. The this pointer/Handle still exist. I think you can try to define your function as void CCameraInstance::VideoCallback(CCameraInstance* test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo) and have try. If you are using C++/CLI it would be void CCameraInstance::VideoCallback(CCameraInstance^ test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
d10668
You can do the following: var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); // clone $scope.column.push(newObj); Or if you want the drop target to only have a single object you must provide it in the form of an array: var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); $scope.column = [newObj]; var myApp = angular.module('myApp', ['ui.sortable']); myApp.controller('MainCtrl', function($scope) { $scope.mainInputs = []; $scope.column = []; var mainInputs = function() { return [{ type: 'radio', text: 'Radio group', content_to_drop: { type: 'radio', contents: [{ text: 'radio 1', value: '1' }, { text: 'radio 2', value: '2' }, { text: 'radio 3', value: '3' }] } }, { type: 'checkbox', text: 'Checkbox Input', content_to_drop: { type: 'checkbox', contents: [{ text: 'checkbox 1', value: '1' }, { text: 'checkbox 2', value: '2' }, { text: 'checkbox 3', value: '3' }] } }]; }; $scope.mainInputs = mainInputs(); $scope.sortableSection = { connectWith: ".connected-apps-container", update: function(event, ui) { if ( // ensure we are in the first update() callback !ui.item.sortable.received && // check that it's an actual moving between the two lists ui.item.sortable.source[0] !== ui.item.sortable.droptarget[0]) { ui.item.sortable.cancel(); // cancel drag and drop var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); $scope.column.push(newObj); // Or for a single object in the drop target, it must be provided as an Array: //$scope.column = [newObj]; } } }; }); <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div ng-app="myApp"> <div ng-controller="MainCtrl"> <div class="col-lg-2 col-md-2 col-sm-3 panel panel-default svd_toolbox"> <div ui-sortable="sortableSection" ng-model="mainInputs" class="first"> <div ng-repeat="(i, input) in mainInputs | orderBy: input.type"> <div class="alert alert-success rounded gradient">{{ input.text }}</div> </div> </div> </div> <div class="co-lg-10 well well-sm"> <div ui-sortable="sortableSection" ng-model="column" class="connected-apps-container" style="min-height: 40px;"> place your elements here </div> </div> <pre>{{ column | json }}</pre> </div> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-sortable/0.17.0/sortable.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
d10669
I can see no reason in if (dialogResult == DialogResult.OK) check, since the dialog has the only OK button: if (order .GetPatientNumber(int.Parse(textPatientID.Text), Program.branch_id) .HasValue) { MessageBox.Show( "PATIENT HAS ORDER TODAY", "DUPLICATE ORDER", MessageBoxButtons.OK, MessageBoxIcon.Stop); Close(); }
d10670
# apt-get install curl ca-certificates gnupg # curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - #vim /etc/apt/sources.list.d/pgdg.list ####### ADD #deb http://apt.postgresql.org/pub/repos/apt/ buster-pgdg main # apt-get update # apt-get install pgadmin4 pgadmin4-apache2 It should now be successfully installed. A: The problem is that lsb_release -cs is not returning the codename for Deepin linux, instead is returning n/a. Try with that dpkg --status tzdata|grep Provides|cut -f2 -d'-' to retrive the codename. If you want a oneliner like the one you posted, here you have: sudo sh -c 'curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add && echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(dpkg --status tzdata|grep Provides|cut -f2 -d'-') pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' A: I am using Linux mint, issue has been fixed using the below command. $ sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add $ sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/focal pgadmin4 main" \ > /etc/apt/sources.list.d/pgadmin4.list && apt update' $ sudo apt update And then, if you want desktop $ sudo apt install pgadmin4-desktop OR the web version: $ sudo apt install pgadmin4-web $ sudo /usr/pgadmin4/bin/setup-web.sh A: For Ubuntu 22.10 and other versions that complain about apt-key being deprecated, use this: curl -fsS https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo gpg --dearmor -o /usr/share/keyrings/packages-pgadmin-org.gpg sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/jammy pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' Note that "jammy" is being used here in the ftp link. You may browse through the other versions and pick the one that matches your Ubuntu installation's version sudo apt install pgadmin4 This installs both web and desktop versions. A: I experienced this error trying to upgrade my pgadmin4 to version 6. There was a problem with the certificates on my system I think, the solution was updating ca-certificates, if it's not installed you should probably install it, but that may be very unlikely that it's not installed though as it should already be there, but either way just run the command: sudo apt install ca-certificates A: I had the same problem with Debian 11, however exploring options I found this answer enter link description here and fixed the problem by installing lsb-release A: I am facing those errors after running this command. sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' What I have to do now? Ign:14 http://apt.postgresql.org/pub/repos/apt vera-pgdg InRelease Err:16 http://apt.postgresql.org/pub/repos/apt vera-pgdg Release 404 Not Found [IP: 217.196.149.55 80] Ign:17 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/vera pgadmin4 InRelease Get:18 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB] Err:19 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/vera pgadmin4 Release 404 Not Found [IP: 87.238.57.227 443] Get:20 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [107 kB] Hit:15 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease Reading package lists... Done W: https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/Release.gpg: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details. E: The repository 'http://apt.postgresql.org/pub/repos/apt vera-pgdg Release' does not have a Release file. N: Updating from such a repository can't be done securely, and is therefore disabled by default. N: See apt-secure(8) manpage for repository creation and user configuration details. E: The repository 'https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/vera pgadmin4 Release' does not have a Release file. N: Updating from such a repository can't be done securely, and is therefore disabled by default. N: See apt-secure(8) manpage for repository creation and user configuration details. W: https://packagecloud.io/slacktechnologies/slack/debian/dists/jessie/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.
d10671
I think the easiest way to do this would be to use find along with ls -t (sort files by time). something along these lines should do the trick (deletes oldest avi file under specified directory) find / -name "*.avi" | xargs ls -t | tail -n 1 | xargs rm step by step.... find / -name "*.avi" - find all avi files recursively starting at the root directory xargs ls -t - sort all files found by modification time, from newest to oldest. tail -n 1 - grab the last file in the list (oldest) xargs rm - and remove it A: Here's another Python formulation, which a bit old-school compared to some others, but is easy to modify, and handles the case of no matching files without raising an exception. import os def find_oldest_file(dirname="..", extension=".avi"): oldest_file, oldest_time = None, None for dirpath, dirs, files in os.walk(dirname): for filename in files: file_path = os.path.join(dirpath, filename) file_time = os.stat(file_path).st_mtime if file_path.endswith(extension) and (file_time<oldest_time or oldest_time is None): oldest_file, oldest_time = file_path, file_time return oldest_file, oldest_time print find_oldest_file() A: Hm. Nadia's answer is closer to what you meant to ask; however, for finding the (single) oldest file in a tree, try this: import os def oldest_file_in_tree(rootfolder, extension=".avi"): return min( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime) With a little modification, you can get the n oldest files (similar to Nadia's answer): import os, heapq def oldest_files_in_tree(rootfolder, count=1, extension=".avi"): return heapq.nsmallest(count, (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime) Note that using the .endswith method allows calls as: oldest_files_in_tree("/home/user", 20, (".avi", ".mov")) to select more than one extension. Finally, should you want the complete list of files, ordered by modification time, in order to delete as many as required to free space, here's some code: import os def files_to_delete(rootfolder, extension=".avi"): return sorted( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime), reverse=True) and note that the reverse=True brings the oldest files at the end of the list, so that for the next file to delete, you just do a file_list.pop(). By the way, for a complete solution to your issue, since you are running on Linux, where the os.statvfs is available, you can do: import os def free_space_up_to(free_bytes_required, rootfolder, extension=".avi"): file_list= files_to_delete(rootfolder, extension) while file_list: statv= os.statvfs(rootfolder) if statv.f_bfree*statv.f_bsize >= free_bytes_required: break os.remove(file_list.pop()) statvfs.f_bfree are the device free blocks and statvfs.f_bsize is the block size. We take the rootfolder statvfs, so mind any symbolic links pointing to other devices, where we could delete many files without actually freeing up space in this device. UPDATE (copying a comment by Juan): Depending on the OS and filesystem implementation, you may want to multiply f_bfree by f_frsize rather than f_bsize. In some implementations, the latter is the preferred I/O request size. For example, on a FreeBSD 9 system I just tested, f_frsize was 4096 and f_bsize was 16384. POSIX says the block count fields are "in units of f_frsize" ( see http://pubs.opengroup.org/onlinepubs/9699919799//basedefs/sys_statvfs.h.html ) A: Check out the linux command find. Alternatively, this post pipes together ls and tail to delete the oldest file in a directory. That could be done in a loop while there isn't enough free space. For reference, here's the shell code that does it (follow the link for more alternatives and a discussion): ls -t -r -1 /path/to/files | head --lines 1 | xargs rm A: To do it in Python, you can use os.walk(path) to iterate recursively over the files, and the st_size and st_mtime attributes of os.stat(filename) to get the file sizes and modification times. A: You can use stat and fnmatch modules together to find the files ST_MTIME refere to the last modification time. You can choose another value if you want import os, stat, fnmatch file_list = [] for filename in os.listdir('.'): if fnmatch.fnmatch(filename, '*.avi'): file_list.append((os.stat(filename)[stat.ST_MTIME], filename)) Then you can order the list by time and delete according to it. file_list.sort(key=lambda a: a[0]) A: The os module provides the functions that you need to get directory listings and file info in Python. I've found os.walk to be especially useful for walking directories recursively, and os.stat will give you detailed info (including modification time) on each entry. You may be able to do this easier with a simple shell command. Whether that works better for you or not depends on what you want to do with the results. A: Using standard library's pathlib: from pathlib import Path def creation_time(path: Path): return path.stat().st_ctime working_dir = Path() avi_files = working_dir.glob("**/*.avi") sorted_avi_files = sorted(avi_files, key=creation_time) print(sorted_avi_files[0]) Or if you like one-liners: min(Path().glob("**/*.avi"), key=lambda p: p.stat().st_ctime)
d10672
function cmp($a, $b) { if($a["date"] == $b["date"]) return 0; return($a["date"] > $b["date"]) ? 1 : -1; } usort($array, "cmp"); A: There is a couple of PHP functions that sort arrays - you can see the overview here: http://php.net/manual/en/array.sorting.php As you want to neither by key nor value, but by some custom logic of yours, you need to use one of the functions starting with u. Ouf of those 3 functions, 2 can be used to sort by value: usort and uasort. The difference between them is that while the first one doesn't preserve the key-value associations, the second one does, which makes uasort the function you need. uasort takes 2 parameters - an array to be sorted and a callback, that for 2 given elements should return -1, 0 or 1 if the first element is smaller, equal or larger than the second. In your case, this will work: print_r($arr); uasort($arr, function($e1, $e2) { if ($e1['date'] == $e2['date']) { return 0; } return ($e1['date'] < $e2['date']) ? -1 : 1; }); print_r($arr); Notice: make sure you don't assign the result of uasort to your $arr - the return value of this function is not the sorted array, but a boolean saying if sorting succeeded.
d10673
tibco/tra/domain/[ENV_NAME]/datafiles/[my app]_root is actually right place where all Global variables values and package code are stored after package deployment. I am guessing you are looking to the wrong package or something wrong with the deployment. All global variables should be stored in [my app]_root\defaultVars\defaultVars.substvar or subfolders [my app]_root\defaultVars\[folder_name]\defaultVars.substvar the variable can be deployment settable and service settable. Please see more details here https://community.tibco.com/questions/difference-between-global-variables-earservice-and-service-instance-levels Also there are several ways global variables can be overridden. Please see https://support.tibco.com/s/article/Tibco-KnowledgeArticle-Article-47854 1). In Designer -> Global Variables panel, click the pencil icon (Open Advanced Editor) at top right, select the global variable and right click ->  “Override Variable”. 2). Use the Project -> “Save as” option to save as a new project. Global variables will then be editable. 3). Go to Tester -> "Advanced" test settings with the "-p PATH/properties.cfg" argument, with PATH being the absolute path and properties the file that override global variables. 4).Change the variable in TIBCO administrator GUI during deployment. 5). Manually edit the bwengine.tra.
d10674
The group aes() solves the problem. Therefore I had to group them with the group = column code.
d10675
It should work if you include your file from the plugins main file, just make sure it is included correctly. include plugin_dir_path( __FILE__ ) . 'includes/file.php; This would include a file in an includes folder in your custom plugin folder, and would include an file named: "file.php". If you want to know if its been loaded correctly, just add an die() statement in the included file: die('my include file has been loaded correctly'); Just remove the die() statement after you have an confirmation that its working :) Lastly you need to copy your callback function code and paste it in your included file. If your hook still does not work, then it might be something wrong with your callback function. The documentation for the filter hook you are using: https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
d10676
This line looks very suspicious: new WKList(Integer.parseInt(line.split(",")[0]), Integer.parseInt(line.split(",")[1])),line.split(",")[2] } Your WKList class takes a String as a first parameter followed by 2 Integers So my expectation is that you should change it to something like: new WKList(line.split(",")[0], Integer.parseInt(line.split(",")[1]), Integer.parseInt(line.split(",")[2])) Also your code assumes the following CSV file structure: Work Registration - External,3423,115 If you need to include use the following file format: RA,8,Dec 30, 2021,Work Registration - External,3423,233 we need to know what is the "required format" of the JSON. In the meantime you can get familiarized with the following material: * *Apache Groovy - Parsing and producing JSON *Apache Groovy - Why and How You Should Use It A: This would work for csv file line RA,8,"Dec 30, 2021",Work Registration - External,3423,233 import groovy.json.* class WKList {String wkname; int Wkid ;int numId} List<WKList> WKDetList = new ArrayList<>(); def lines =new File("Sample2.csv").readLines() def content = [:] def articles = [] def article = [:] for (int i=1;i<lines.size();i++) { String[] splitData = lines[i].split(','); content.put('Place', splitData[0]) content.put('Serial', splitData[1]) content.put('SerialDate', splitData[2]) article.put('wkname', splitData[3]) article.put('wkid', splitData[4]) article.put('numId', splitData[5]) articles.add(article) content.put('WKList', articles) } sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(content).toPrettyString(), '') sampler.setPostBodyRaw(true) log.info(JsonOutput.prettyPrint(JsonOutput.toJson(content)))
d10677
No idea why it cannot find your library. From what I remember of JNI, it does not appear that you've done the JNI setup for calling a native routine, but the error message just says it cannot find it. You might try figuring out if the library load statement worked. A DLL is a library following certain rules and conventions; I am not aware of any great difference between a "Visual Basic DLL" and any other kind. At some level they need to be the same, because Windows programs don't distinguish among DLLs written with different languages, afaik, and I've done VB enough to know that I haven't seen documentation that says "this can be used from VB but not from other languages" etc. Getting JNI/JNA stuff to work is tricky and tedious. The normal stuff that a language runtime tells you, especially a Java runtime, are not there for you in this case. You must painstakingly go through every line of whatever documentation you have, every parameter you are passing, every use of value versus reference, etc. I once got things to work with the GitHub library here. Good luck. A: I have not found an answer how to call VB DLLs directly from Java but after some days of research I found out that you are able to call VB DLLs with the help of a C++ wrapper. It may be possible to call VB DLL methods with JNI but there is no documentation on how to do it. You find a lot about how to create C++ libraries that are able to communicate with JNI in the JNI specifications from Oracle. In this special case (control Office Applications with Java) I suggest to write the code to access the Office Application in C++ and create a DLL. The basic approach on creating a C++ DLL that may interact with JNI is: * *Think of names for the methods you want to create in C++ and a .dll-name [NAME].dll *Create a Java class for the DLL, loading the library: static{ System.loadLibrary([NAME].dll); } The Native Library path has to be set (in Eclipse, right-click on the folder containing your class and click Build-Path). *Include the method names public native void [methodname]();. *Compile the .java file using javac.exe (or let for example Eclipse do the work). *Create a C++ header-file using javah.exe with -jni parameter. *Create a new project in Visual Studio (Visual C++ MFC DLL). *Copy the created header-file (your Java Project), the jni.h (JDK) and the jni_md.h (JDK) *Include all three header-files in your Visual C++-project header-file [Project-Name].h *Include the created header-file and the jni.h-file in [Project-name].cpp. *Write desired code in your [Project-name].cpp. *Build the DLL, put it inside your defined path for Native Libraries (see italic in 2.). *Run and be happy! Sorry for any mistakes! An example with Visual Basic-DLL and JNI can be found 1HERE and somewhere else, google "classle" and "JNI" (can't post 2 links).
d10678
Consulting the javadoc for FileInputStream (I'm assuming since you're reading from file): Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned. The key here is that the method only blocks until some data is available. The returned value gives you how many bytes was actually read. The reason you may be reading less than 128 bytes could be due to a slow drive/implementation-defined behavior. For a proper read sequence, you should check that read() does not equal -1 (End of stream) and write to a buffer until the correct amount of data has been read. Example of a proper implementation of your code: InputStream is; // = something... int read; int read_total; byte[] buf = new byte[128]; // Infinite loop while(true){ read_total = 0; // Repeatedly perform reads until break or end of stream, offsetting at last read position in array while((read = is.read(buf, read_total, buf.length - offset)) != -1){ // Gets the amount read and adds it to a read_total variable. read_total = read_total + read; // Break if it read_total is buffer length (128) if(read_total == buf.length){ break; } } if(read_total != buf.length){ // Incomplete read before 128 bytes }else{ process_data(buf); } } Edit: Don't try to use available() as an indicator of data availability (sounds weird I know), again the javadoc: Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. Returns 0 when the file position is beyond EOF. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks. The key there is estimate, don't work with estimates. A: Since the accepted answer was provided a new option has become available. Starting with Java 9, the InputStream class has two methods named readNBytes that eliminate the need for the programmer to write a read loop, for example your method could look like public static void some_method( ) throws IOException { InputStream is = new FileInputStream(args[1]); byte[] buff = new byte[128]; while (true) { int numRead = is.readNBytes(buff, 0, buff.length); if (numRead == 0) { break; } // The last read before end-of-stream may read fewer than 128 bytes. process_data(buff, numRead); } } or the slightly simpler public static void some_method( ) throws IOException { InputStream is = new FileInputStream(args[1]); while (true) { byte[] buff = is.readNBytes(128); if (buff.length == 0) { break; } // The last read before end-of-stream may read fewer than 128 bytes. process_data(buff); } }
d10679
Your red circle (the one with the color you called blue ;) ) has bounds that extend into negative coordinate ranges in both x- and y-directions (it has center (50, 50) and radius 200). Hence it extends beyond the bounds of the pane. If you want to make sure the pane doesn't paint outside of its bounds, you can set a clip that is bound to its size: Rectangle clip = new Rectangle(0, 0, 0, 0); clip.widthProperty().bind(pane.widthProperty()); clip.heightProperty().bind(pane.heightProperty()); pane.setClip(clip); To update the circles, you just have to make them instance variables instead of local to the start method, and update their centers and radii: import java.util.Scanner; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.TextAlignment; import javafx.stage.Stage; public class Shapes extends Application { private Label label0, label1, label2, label3, label4; private TextField tField; private Circle circle1 ; private Circle circle2 ; @Override public void start(Stage stage) { createTextField(); VBox root = new VBox(); root.setSpacing(10); Pane pane = new Pane(); Color blue = new Color(1, 0, 0, 1); Color red = new Color(0, 0, 1, 1); circle1 = createCircle(50, 50, 50, red); circle2 = createCircle(50, 50, 200, blue); pane.getChildren().addAll(circle1, circle2); // If desired: // Rectangle clip = new Rectangle(0, 0, 0, 0); // clip.widthProperty().bind(pane.widthProperty()); // clip.heightProperty().bind(pane.heightProperty()); // pane.setClip(clip); root.getChildren().addAll(label0, label1, label2, tField, label3, label4, pane); Scene scene = new Scene(root, 1000, 1000); stage.setTitle("Spatial Relations Demo by"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } public void createTextField() { label0 = new Label(); label0.setText("Spatial Relations Demo"); label1 = new Label(); label1.setText(" "); label1.setTextAlignment(TextAlignment.CENTER); label2 = new Label(); label2.setText("Input Circles: x1 y1 r1 x2 y2 r2 "); label2.setTextAlignment(TextAlignment.CENTER); label3 = new Label(); label3.setTextAlignment(TextAlignment.CENTER); label4 = new Label(); label4.setTextAlignment(TextAlignment.CENTER); tField = new TextField(); tField.setOnAction(new TextFieldHandler()); } public class TextFieldHandler implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { String str = tField.getText(); int x1, y1, r1, x2, y2, r2; Scanner scanner = new Scanner(str); x1 = scanner.nextInt(); y1 = scanner.nextInt(); r1 = scanner.nextInt(); x2 = scanner.nextInt(); y2 = scanner.nextInt(); r2 = scanner.nextInt(); circle1.setCenterX(x1); circle1.setCenterY(y1); circle1.setRadius(r1); circle2.setCenterX(x2); circle2.setCenterY(y2); circle2.setRadius(r2); tField.setText(""); String str1 = String.format("Input is: " + x1 + " " + y1 + " " + r1 + " " + x2 + " " + y2 + " " + r2); label3.setText(str1); double d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); if ((x1 == x2) & (y1 == y2) & (r1 == r2)) label4.setText(" The circles are equal."); else if (d >= (r1 + r2)) label4.setText(" The circle interiors are disjoint."); else if (d <= (r2 - r1)) label4.setText(" Circle1 is inside Circle2."); else if (d <= (r1 - r2)) label4.setText(" Circle2 is inside Circle1."); else label4.setText(" The circles overlap."); scanner.close(); } } public Circle createCircle(int x, int y, int r, Color color) { Circle circle = new Circle(); circle.setRadius(r); circle.setCenterX(x); circle.setCenterY(y); circle.setStroke(color); circle.setFill(null); return circle; } }
d10680
There is a tool called Material Design Background Generator that can do that for you. It's an online tool, check out this link: http://www.stringsistemas.com/materialgenerator.html After a few random generations you can get some awesome patterns but you can't choose the palette colors unfortunately but it seems like the developer is open for suggestions.
d10681
You can check the MSAL For Angular document for how to authenticate user and acquire access token . And this code sample is for Angular 9 . If you want to directly call Microsfot Graph in Angular application , you can directly acquire Microsoft Graph's scopes as the document show , MSAL will help acquiring access token for Microsoft Graph . If you want to call Microsoft Graph from web api application , propagate the delegated user identity and permissions , you can use OAuth 2.0 On-Behalf-Of flow and follow the code sample as your shown , and use fiddler or developer tools to trace the requests and troubleshoot the 401 problem .
d10682
In theory, it's completely invalid (undefined behavior) to access memory like this without some synchronization. In practice, it's moderately safe as long as: * *Only one thread is writing and the others are all reading. *You don't care if the readers don't see some of the changes made until sometime later (possibly much later than the actual time they're written. *You don't care if the readers see out-of-order changes, i.e. they see some changes that were made later without seeing other changes that were made earlier. Issues 2 and 3 are a non-issue on x86, but can occur on nearly every other real-world multi-core/SMP machine. You could mitigate them with some machine-specific asm (or compiler intrinsics) to insert memory barriers at appropriate points. A: The boolean array elements are can be set/read with an atomic operation, there is not need for a mutex. You need a mutex to protect a structure to make sure that it stays consistent. Since your booleans are independent there is no problem.
d10683
Your relationship in your models are wrong. Services has a "Type", so the Foreign Key goes from ServiceType to Service. You don't need to reference Services inside ServiceType You should create your model like this: Services public class Services { [Key] public int ServicesID { get; set; } [DisplayName("Register Date")] public DateTime RegisterDate { get; set; } public string ApplicationUserID { get; set; } [ForeignKey("ServiceType")] public int ServiceTypeID { get; set; } public virtual ServiceType ServiceType { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } } ServiceType public class ServiceType { [Key] public int ServiceTypeID { get; set; } public string NAME { get; set; } } I would also do the same with the ApplicationUserID property, but since you didn't post about it I let it as is. Also, it would be better if you drop your database and let Entity Framework create it again for you. Because you had a wrong model relationship things got "messy".
d10684
you need to escape the following characters: ( ) < > | ; & * \ ~ " ' 'escaping' means putting a backslash ( \ ) before the offending character. space is escaped by using %s adb shell input text \! There is no keycode for !.
d10685
Sometimes CPython documentation needs to be used in conjunction with the C documentation, since CPython builds on C. In this case, you might find what you need in http://linux.die.net/man/2/getrusage - or perhaps the getrusage doc for some other *ix variant. HTH
d10686
I am assuming you are not using Json.NET. If this the case, then you should try it. It has the following features: * *LINQ to JSON *The JsonSerializer for quickly converting your .NET objects to JSON and back again *Json.NET can optionally produce well formatted, indented JSON for debugging or display Look how fast Json.NET compared to JavaScriptSerializer:http://i.stack.imgur.com/T77y2.png Example code for load json file in C#: JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json")); // read JSON directly from a file using (StreamReader file = File.OpenText(@"c:\videogames.json")) using (JsonTextReader reader = new JsonTextReader(file)) { JObject o2 = (JObject)JToken.ReadFrom(reader); }
d10687
There are multiple reasons for emails treated as spam. Usually it relates to the server sending the mail, apart from content or headers of the mail itself. E.g. the DNS might be not configured correctly, there are some tools in the web that might support you troubleshoot, unfortunately I don't find the tool I used some years ago. Google might bring you up some tools for checking the DNS configuration. There was already some discussion on stackoverflow about this topic, please check this thread to avoid a duplicate discussion. I recommend using a library like PHPMailer for handling mails.
d10688
I'm not really sure about your goal ? Are you trying to run a server from a client web browser ? I'm not sure this is possible for many reason (as security for example)... I think you need to read this ! If you're just trying to run a node server on your localhost (127.0.0.1), you need to install nodejs on your computer Node.js, then you need to save your nodejs example in javascript file (named "myServer.js" for example) and run node in CLI using: node path/to/myServer.js And about: Uncaught ReferenceError: require is not defined you should see #19059580 Best regards, Tristan A: You could use something like electron. It basically gives you node.js and chromium and enables you to build cross-platform desktop apps.
d10689
The meaning of the following error: pygame.error: cannot convert without pygame.display initialized is that you are trying to use a method of pygame.display (the convert method) without initializing pygame first. To fix this, simply move pygame.init() to below the import statements. Code import pygame import random from os import path pygame.init() pygame.mixer.init() img_dir = path.join(path.dirname(__file__), 'PNG') background = pygame.image.load(path.join(img_dir, 'Space-Background.png')).convert() background_rect = background.get_rect() WIDTH = 480 HEIGHT = 600 FPS = 60 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("My Game") clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 40)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centrex, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((30, 40)) self.image.fill(RED) self.rect = self.image.get_rect() self.rect.x = random.randrange(0, WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) def update(self): self.rect.y += self.speedy if self.rect.top > HEIGHT + 10: self.rect.x = random.randrange(0, WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((10, 20)) self.image.fill(YELLOW) self.rect = self.image.get_rect() self.rect.bottom = y self.rect.centrex = x self.speedy = -10 def update(self): self.rect.y += self.speedy if self.rect.bottom < 0: self.kill() # player_img = pygame.image.load(path.join(img_dir,"spaceShips_003.png")).convert() # bullet_img = pygame.image.load(path.join(img_dir,"spaceMissile_006.png")).convert() # mob_img = pygame.image.load(path.join(img_dir,"SpaceMeteor_004.png")).convert() all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) all_sprites.add(player) running = True while running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() all_sprites.update() hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: m = Mob() all_sprites.add(m) hits = pygame.sprite.spritecollide(player, mobs, False) if hits: running = False screen.fill(BLACK) # screen.split(background.background_rect) all_sprites.draw(screen) pygame.display.flip() pygame.quit()
d10690
The main issue with i is that your callbacks close over the variable i, not its value as of when the function was created. So they all see i = 5. I'm not quite understanding why you're repeating the get five times, but if you want to, you have to give the callbacks something else to close over (or use res.push(...) rather than res[i] = ..., but I assume you have a reason for the latter). You can do that using a builder: // PARTIAL solution, see below var fun1 = function () { var control = $.Deferred(); for (i=0;i<5;i++) { $.get("URL", buildHandler(i)); } function buildHandler(index) { return function(data){ res[index]=data; console.log ("index is: " + index + "and res is: " + res); }; } }; Another way to do a builder is to use Function#bind (ES5+, but easily polyfilled), but you'd create more functions than you need; the above is more efficient in this case (not that it likely matters). Then, to have fun1 return something useful, you have it return a promise (you seem to be on your way to that, based on your control variable), and then fulfill the promise when all of the gets are done ($.when is useful for that): var fun1 = function () { var control = $.Deferred(); var promises = []; for (i=0;i<5;i++) { promises.push($.get("URL", buildHandler(i))); } $.when.apply($, promises).then(function() { control.resolve(); // Or .resolveWith(), passing in something useful }); return control.promise(); function buildHandler(index) { return function(data){ res[index]=data; console.log ("index is: " + index + "and res is: " + res); }; } }; All of this assumes res is in scope for this code; you haven't shown where it comes from.
d10691
The problem was image was not ready at windows on load event, verified by checking the innerHTML of the image, while if I try to do the same thing in onClick event, the image is successfully loaded into canvas.
d10692
If you use Prototype, jQuery, Mootools or YUI you should find a X-Requested-With:XMLHttpRequest header which will do the trick for you. It should be possible to insert whatever header you like with other libraries. At the lowest level, given a XMLHttpRequest or XMLHTTP object, you can set this header with the setRequestHeader method as follows: xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); A: After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.
d10693
A common approach is to use custom rake tasks and schedule them using whenever. There is even a nice Railscast, although it is a bit old.
d10694
Just sample a circle: allocate offset array var angle = 2 * Math.PI / n; for(var i = 0; i < n; ++i) offsets[i] = {x: r * Math.cos(i * angle), y: r * Math.sin(i * angle)};
d10695
While newer versions of EF Core do support some filtering via adding Where clauses, it's best to think of entities as a "complete" or "complete-able" representation of your data state. You either use the complete state of data, or you project to get the details you want. For example, if you just want the last modified date for each member: var lastModifiedDetails = context.Members .Select(m => new { m.MemberId, LastModifiedDate = m.Histories.OrderByDescending(h => h.LastModifiedDate) .Select(h => h.LastModifiedDate) .FirstOrDefault() }).ToList(); This would give you a collection containing the MemberId and it's LastModifiedDate. Alternatively, if you want the complete member and a quick reference to the last modified date: var memberDetails = context.Members .Select(m => new { Member = m, LastModifiedHistory = m.Histories.OrderByDescending(h => h.LastModifiedDate) .FirstOrDefault() }).ToList(); Here instead of trying to get the last modified date or the latest history through a Member entity, you get a set of anonymous types that project down that detail. You iterate through that collection and can get the applicable history and/or modified date for the associated Member.
d10696
While running Windows 10 Pro, I recently had the same issue after uninstalling Anaconda3 with Anaconda's uninstaller. Try deleting the Anaconda3 folder from the following directory to remove the related shortcuts. "C:\ProgramData\Microsoft\Windows\Start Menu\Programs" Note: This fix assumes Anaconda3 was previously installed using default directories.
d10697
histogram takes two parameters, positionCounts of type int[] and x of type int. In walkRandomly, you call histogram twice: once with an argument positionCounts of type int[] and once with an argument x of type int. That’s why the compiler complains that the method ”cannot be applied to given types”: the method histogram(int[], int) can’t be applied to (called with) the given types, i.e., histogram(int[]) and histogram(int). I’m not sure what you’re trying to do with this code, but I’d guess that you want remove the first call and change the second call (inside of the while loop) to histogram(positionCounts, x). (You’ve edited your code, so my answer doesn’t make much sense.)
d10698
I don't know if it's the best way to do this but what I do is instead of: application = service.Application("chatserver") internet.TCPServer(1025, factory).setServiceParent(application) you can do: from twisted.internet import reactor reactor.listenTCP(1025, factory) reactor.run() Sumarized if you want to have the two options (twistd and python): if __name__ == '__main__': from twisted.internet import reactor reactor.listenTCP(1025, factory) reactor.run() else: application = service.Application("chatserver") internet.TCPServer(1025, factory).setServiceParent(application) Hope it helps! A: On windows you can create .bat file with your command in it, use full paths, then just click on it to start up. For example I use: runfileserver.bat: C:\program_files\python26\Scripts\twistd.py -y C:\source\python\twisted\fileserver.tac A: Maybe one of run or runApp in twisted.scripts.twistd modules will work for you. Please let me know if it does, it will be nice to know! A: Don't confuse "Twisted" with "twistd". When you use "twistd", you are running the program with Python. "twistd" is a Python program that, among other things, can load an application from a .tac file (as you're doing here). The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting %PATH% to include the directory containing the "twistd" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path. If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "twistd". A: I haven't used twisted myself. However, you may try seeing if the twistd is a python file itself. I would take a guess that it is simply managing loading the appropriate twisted libraries from the correct path. A: I am successfully using the simple Twisted Web server on Windows for Flask web sites. Are others also successfully using Twisted on Windows, to validate that configuration? new_app.py if __name__ == "__main__": reactor_args = {} def run_twisted_wsgi(): from twisted.internet import reactor from twisted.web.server import Site from twisted.web.wsgi import WSGIResource resource = WSGIResource(reactor, reactor.getThreadPool(), app) site = Site(resource) reactor.listenTCP(5000, site) reactor.run(**reactor_args) if app.debug: # Disable twisted signal handlers in development only. reactor_args['installSignalHandlers'] = 0 # Turn on auto reload. import werkzeug.serving run_twisted_wsgi = werkzeug.serving.run_with_reloader(run_twisted_wsgi) run_twisted_wsgi() old_app.py if __name__ == "__main__": app.run()
d10699
Your cookie jar is likely not writable by the server user in your production environment. Libcurl can't throw an error about this, so you're getting a 403 when your second request fires. If you have command line access, run chmod 777 on your script's directory to test it. If it works, fix up your webserver permissions and undo the 777 permissions.
d10700
I fixed it by using peerDependencies + moving those dependenecies into devDependencies. My assumption is that node will scan for dependencies in this order: * *dependencies in my shared component lib's package.json *dependencies in my React app therefore I had to move the react routing libs into devDependencies so that I could still run my storybook server locally and still have the shared component node_module load properly in production in my react app. Here's my package.json "name": "mypackage", "version": "0.6.3", "dependencies": { ... }, "peerDependencies": { "react": "^16.13.1", "styled-components": "^4.4.1", "react-dom": "^16.12.0", "react-router": "^5.2.0", "react-router-dom": "^5.2.0" }, "scripts": { "start": "start-storybook -p 9009", "eslint": "eslint --ignore-path .gitignore ./", "eslint:fix": "eslint --fix --ignore-path .gitignore ./", "prettier": "prettier -c ./", "prettier:fix": "prettier --write ./" }, ... "devDependencies": { ... "react": "^16.13.1", "styled-components": "^4.4.1", "react-dom": "^16.12.0", "react-router": "^5.2.0", "react-router-dom": "^5.2.0" }, "husky": { "hooks": { "pre-commit": "pretty-quick --staged", "pre-push": "npm run eslint" } } }