Id
int64
34.6M
60.5M
Title
stringlengths
15
150
Body
stringlengths
33
36.7k
Tags
stringlengths
3
112
CreationDate
stringdate
2016-01-01 00:21:59
2020-02-29 17:55:56
Y
stringclasses
3 values
59,035,060
Can I create a mySQL DatabaBase from Java code?
<p>I'm learning about JDBC.</p> <p>Can I create a mysql database from a java code?</p> <p>How can I make the connection?</p> <p>Thanks.</p>
<java><mysql><database>
2019-11-25 15:23:50
LQ_CLOSE
59,035,353
Please suggest javascript code for converting distinguished name into canonical name?Please refer the details below
This is distinguished name "CN=Peterson\,Misha,OU=Users,OU=Bright,OU=APAC,DC=xyz,DC=ang,DC=com". I need to convert this into"xyz.ang.com/APAC/Bright/Users/Peterson,Misha",i.e., Canonical name.
<javascript><active-directory>
2019-11-25 15:39:16
LQ_EDIT
59,036,609
Python- get last letter of a string
I am relatively new in python. I wanted to know if is there any possibility for me to get only the **E:** from the string below: p="\\.\E:"
<python><python-3.x><text>
2019-11-25 16:53:06
LQ_EDIT
59,037,458
How to get a approximate equation for reverse look up
Is there any method or way to get the approximate equation(x = g(y)) for doing a reverse lookup from Y to X. Following is the simple y = f(x) and it's plot. ``` import numpy as np import matplotlib.pyplot as plt formula = "2*x**6 + x**5 -3*x**4 + 7*x**3 + 9*x**2 + x + 6" x = np.arange(1, 10) y = eval(formula) plt.plot(x, y) plt.xlabel('X') plt.ylabel('Y') plt.show() ``` [Attaching the simple graph here][1] [1]: https://i.stack.imgur.com/xIXXx.png Can you please suggest me any possible way in R or Python to get reverse lookup function(From Y to X) with a minimal margin of error.
<python><r><algebra><polynomial-math>
2019-11-25 17:47:08
LQ_EDIT
59,038,938
How to get local time from web server?
I set up an ajax server with this settings ``` let express = require('express'); let server = express(); server.use('/MyWebApp', express.static(__dirname + '/public')); server.get('/MyWebApp/dateService', function(request, response){ response.send({'dateTime' : new Date()}); }); server.listen(2019); console.log('server running on port 2019 ...') ```` I want to get the local time and have this function in my html ``` function getDateTime(){ $.get({ url: "http://localhost:2019/MyWebApp/dateService", dataType: "json", success: function(result){ document.getElementById("timer").innerHTML = result; } }); } ``` But when I click the button, it doesn't work and I don't know why? ``` <div id="timer">Random Text</div> <input type="button" value="Server-Request" onclick="getDateTime()"/> ```
<javascript><html><node.js><ajax><server>
2019-11-25 19:36:30
LQ_EDIT
59,040,634
Can I give a class name as an XML element?
<p>I'm looking to use XML to fill in some definitions of objects. I really want the file to be able to give a class name in a property itself:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Object&gt; &lt;Name&gt;Something&lt;/Name&gt; &lt;ObjClass&gt;SomeClass&lt;/ObjClass&gt; &lt;/Object&gt; </code></pre> <p>where <code>SomeClass</code> is the name of a class defined in code somewhere else that gets instantiated when the file is deserialized (or the class is static, I haven't decided). Is that possible?</p>
<c#><xml>
2019-11-25 21:52:13
LQ_CLOSE
59,040,875
.NET / C# - Get the next semi-week end date
<p>I have the following code, which simulates a week start on Saturday and then divides the week in 2 parts, returning Tuesday if the given date is Sat-Tue, else it returns Fri, however, I feel i'm doing something wrong, and that the code could be simplified, but I can't figure out how.</p> <pre><code>private static DateTime SemiWeeklyEndDate(DateTime date) { if (((7 + (date.DayOfWeek - DayOfWeek.Saturday)) % 7) &lt;= ((7 + (DayOfWeek.Tuesday - DayOfWeek.Saturday)) % 7)) return date.AddDays((((int)DayOfWeek.Tuesday - (int)date.DayOfWeek + 7) % 7)); return date.AddDays((((int)DayOfWeek.Friday - (int)date.DayOfWeek + 7) % 7)); } </code></pre>
<c#><.net><datetime>
2019-11-25 22:14:14
LQ_CLOSE
59,040,987
How to skip the first two lines of a file and read those lines that are multiple of 5
<p>I have a file and I want to skip the first two lines and read those lines that are multiple of 5</p> <p>line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10</p> <p>output: line 3 line 8 .. . .</p>
<python><file>
2019-11-25 22:24:42
LQ_CLOSE
59,044,957
Keep ratio of DIV or img
<p>I want to keep the ratio of DIV For example I use google map</p> <p><code>&lt;div id="map" style="background-color: grey;width:100%;"&gt; Map here &lt;/div&gt;</code></p> <p>It adjust the width to window or <code>col-*</code> for <code>bootstrap</code>.</p> <p>it changes according to window size. </p> <p>But now I want to keep the width:height ratio = 1 : 1</p> <p>How should I do??</p> <p>Same situation happens to <code>img</code> </p> <p>I want to keep this img square</p> <p><code>&lt;img class="img-fluid" style="width:100%;"&gt;</code></p>
<jquery><css><twitter-bootstrap>
2019-11-26 06:28:25
LQ_CLOSE
59,048,447
Objecy.keys().map() VS Array.map()
<p>can you give me an argument why approach A is better than approach B.</p> <p>Approach A:</p> <pre><code>const transformCompanyOptions = (companies: Array&lt;{id: string, name: string}&gt;, selectedId: string) =&gt; { return companies.map(key =&gt; { return { value: key.id, label: key.name, checked: key.id === selectedId } }) }; </code></pre> <p>Approach B:</p> <pre><code>const transformCompanyOptions = (companies: Array&lt;{id: string, name: string}&gt;, selectedId: string) =&gt; { const ret = Object.keys(companies).map((key) =&gt; { const newCompany = {}; newCompany['value'] = companies[key].id; newCompany['label'] = companies[key].name; if (companies[key].id === selectedId) { newCompany['checked'] = true; } return newCompany; }); return ret; }; </code></pre> <p><strong>Thank you</strong></p>
<javascript><arrays><object><javascript-objects>
2019-11-26 10:10:29
LQ_CLOSE
59,050,799
Duplicate elements of array in the same array
<p>I got this array of objects</p> <pre><code>let item = [ { a: 1 }, { b: 2 } ] </code></pre> <p>and would like to duplicate array's elements to the same array. Output should be:</p> <pre><code>[ { a: 1 }, { b: 2 }, { a: 1 }, { b: 2 } ] </code></pre> <p>Can you help?</p>
<javascript><arrays><object><javascript-objects>
2019-11-26 12:16:21
LQ_CLOSE
59,051,360
Learning scripting/programming (beginning)
<p>What I am asking can be a bit silly and weird by anyway, I decided to ask you.</p> <p>I am working as network security administrator and have knowledge and experience on cyber security as well. 2 month ago I Started my master degree on Cyber Security and now really want to continue my career on Cyber. Along with network and cyber skills I though having some programming languages in pocket will really benefit me. Shell scripting and Python are the only ones which really catch my interest. </p> <p>I started with bash scripting and just wrote couple of little scripts. I wonder do you know any source which can I use for exercising. I am usually used to learn when I am actually searching and doing something. Therefore if for instance there is any page where I can find tasks for bash scripts with what I can practice and try do find solution, myself.</p> <p>Thanks in advance!</p>
<bash><shell>
2019-11-26 12:49:22
LQ_CLOSE
59,052,654
onBackPressed finish() not working in android studio
I used below code to close activity after back button pressed. ``` @Override public void onBackPressed() { super.onBackPressed(); finish(); } ``` after 5 time pressed it worked how to solve it
<android>
2019-11-26 14:02:06
LQ_EDIT
59,053,204
How can I check if a an array of strings is empty in MongoDB with java?
Imagine I have a DB with documents with the format: ``` { "id": "12345", "adress": "adress1,adress2,adress3" } ``` I have tried, after query the DB and get the document of the id I want, to turn *adress* into a list and get list.isEmpty(), but it's not empty. Can it be done using MongoDB?
<java><mongodb>
2019-11-26 14:31:16
LQ_EDIT
59,053,960
Escaping @ in Blazor
<p>I want to display image from icon library in Blazor component. </p> <p>The path is:</p> <p><em>wwwroot/lib/@icon/open-iconic/icons/account-login.svg</em></p> <p>But <strong>@</strong> is a special character in Blazor.</p>
<escaping><blazor>
2019-11-26 15:14:23
HQ
59,054,873
Quickest and best way to determine Angular/AngularJS version a site is using?
<p>At work, I've inherited over 30 web sites/applications built using C#, ASP.NET, MVC and AngularJS/Angular. The sites were built and updated between 2010 and 2018. Some have been built and updated more recently than others. What is the quickest and best way to determine decisively what version of AngularJS or Angular each site is using?</p> <p>For the record, I don't have any Angular experience yet, other than a few modifications to some of these sites. My background is in C#, ASP.NET, MVC, React, JS, PHP, VB6 etc. The technologies and design decisions used for these sites were an interesting choice, which wasn't mine to make, so please don't get too excited about them. What I find will determine which version of Angular I will focus on learning initially.</p>
<c#><angularjs><angular><asp.net-mvc>
2019-11-26 16:01:02
LQ_CLOSE
59,055,019
How to make a .py file not human readable?
<p>I have a script in .py format and random forest in pickle format and i should deliver it to a customer . He should not be able to read both. </p>
<python><machine-learning><random-forest>
2019-11-26 16:08:43
LQ_CLOSE
59,055,231
Convert number to a binary code in JavaScript?
<p>What function or method converts number (2354) to binary code (001011001010)? Thanks</p>
<javascript><binary><numbers>
2019-11-26 16:19:55
LQ_CLOSE
59,056,385
Cannot connect to Elasticsearch from Go server running in Docker
<p>I have set up an environment today that runs a <code>golang:1.13-alpine</code> image, along with the latest images for Elasticsearch and Kibana.</p> <p>Elasticsearch and Kibana are running fine when accessing from my local machine, but I cannot connect to Elasticsearch through the Go server. I have put this together from guides I have found and followed. </p> <p>I am still a bit green using Docker. I have an idea that I am pointing at the wrong ip address in the container, but I am unsure how to fix it. Hope someone can guide me in the right direction.</p> <p><strong>docker-compose.yml:</strong></p> <pre><code>version: "3.7" services: web: image: go-docker-webserver build: . ports: - "8080:8080" elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.4.2 environment: node.name: elasticsearch cluster.initial_master_nodes: elasticsearch cluster.name: docker-cluster bootstrap.memory_lock: "true" ES_JAVA_OPTS: -Xms256m -Xmx256m ulimits: memlock: soft: -1 hard: -1 ports: - "9200:9200" kibana: image: docker.elastic.co/kibana/kibana:7.4.2 ports: - "5601:5601" links: - elasticsearch </code></pre> <p><strong>Dockefile:</strong></p> <pre><code>FROM golang:1.13-alpine as builder RUN apk add --no-cache --virtual .build-deps \ bash \ gcc \ git \ musl-dev RUN mkdir build COPY . /build WORKDIR /build RUN go get RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o webserver . RUN adduser -S -D -H -h /build webserver USER webserver FROM scratch COPY --from=builder /build/webserver /app/ WORKDIR /app EXPOSE 8080 EXPOSE 9200 CMD ["./webserver"] </code></pre> <p><strong>main.go</strong>:</p> <pre><code>func webserver(logger *log.Logger) *http.Server { router := http.NewServeMux() router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { es, err := elasticsearch.NewDefaultClient() if err != nil { log.Fatalf("Error creating the client: %s", err) } res, err := es.Info() if err != nil { log.Fatalf("Error getting response: %s", err) } log.Println(res) }) return &amp;http.Server{ Addr: listenAddr, Handler: router, ErrorLog: logger, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 15 * time.Second, } } </code></pre> <p>When I boot the server, everything is running fine and I can access Kibana and query the data that I have indexed, but as soon as I hit <code>localhost:8080</code> in Postman, the server dies and outputs: </p> <pre><code>web_1 | 2019/11/26 16:40:40 Error getting response: dial tcp 127.0.0.1:9200: connect: connection refused go-api_web_1 exited with code 1 </code></pre>
<docker><go><elasticsearch><kibana>
2019-11-26 17:26:42
LQ_CLOSE
59,056,952
TS1128: Declaration or statement expected (end of file)
<p>folks. Working on a TypeScript/React project (just getting used to it, haven't written React in a year, etc.), and having an issue.</p> <p>When I wrote this component, I followed some docs that I found, but I'm getting a TS1128 (Declaration or statement expected) error at the end of this file, and I can't figure out why:</p> <pre><code>import * as React from 'react'; import Count from './CountDisplay'; interface State { count: number; } class Counter extends React.Component&lt;{}, State&gt; { state: State = {count: 0}; increment() { this.setState({ count: (this.state.count + 1) }); } decrement() { this.setState({ count: (this.state.count - 1) }); } render(): JSX.Element { return ( &lt;div&gt; &lt;Count count={this.state.count}/&gt; &lt;button onClick={this.increment}&gt;Increment&lt;/button&gt; &lt;button onClick={this.decrement}&gt;Decrement&lt;/button&gt; &lt;/div&gt; ); } } export default Counter; </code></pre> <p>Dunno why I keep getting an error, because the code looks fine (or so I thought), but I could be wrong.</p> <p>Below is my TSConfig.json, because I figured maybe it's relevant to the issue:</p> <pre><code>{ "compilerOptions": { "outDir": "./dist", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es6", "jsx": "react" } } </code></pre> <p>Any help would be great appreciated, I've been beating my head against this for a short while now, sorta stuck.</p>
<reactjs><typescript>
2019-11-26 18:05:06
HQ
59,057,311
Symfony 4 | Custom configuration file
I have been searching for a little while but I cannot find anything useful (or at least I think so). My goal is to add to a new symfony 4.4 project an extra config file to define some behavior of the system, it could be anything, like, pancakes.yaml: ```yaml pancakes: enablePancakes: false ``` I wish to know how can I load that config file, find a way to read its parameters and values to change some custom behavior the system might have but honestly I think I'm not smart enough to undestand what the documentation says. For now it could be anything, like printing the config file values, idk, for now I only need to know how to load it. Any tip or help would be a great help for me, I'm kinda lost here
<php><symfony><yaml><symfony-config-component>
2019-11-26 18:28:01
LQ_EDIT
59,058,242
How to add the output of each html page into multiple files in python?
I created a code that would generate each html page as output to save in different files by iteration of for loop. import requests import urllib.request def crawlpages(): for i in range(1451720, 1451730): link = "https://www.mmo-champion.com/members/" + str(i) content = urllib.request.urlopen(link) mydata = content.read() with open('Newfile.html%s' %i,'wb') as file: file.write(mydata) crawlpages()
<python>
2019-11-26 19:36:31
LQ_EDIT
59,060,689
SQL Table to nested xml file
Action Action2 Name Action3 Batch add PL Steve add 1 add PL Steve add 3 add PL Steve add 4 add PL Steve add 5 add PL Steve add 1 add PL Steve add 3 add PL Steve add 4 add PL Steve add 5 [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/QKikY.png
<sql><sql-server><tsql><xquery>
2019-11-26 23:07:01
LQ_EDIT
59,062,480
C#: I'm looking for a way to create new "primitive" types with additional constraints which are visible at coding time to users of the type
Suppose I have an entity in my universe of discourse called a `Widget`. Widgets are passed around between multiple distributed applications. All systems communicate through a messaging system. The messaging system passes a "common data model" (CDM) instance of the `Widget` around, where all applications translate to and from the CDM, and the communication follows the event-carried-state-transfer pattern.<sup>[1]</sup> Suppose the `Widget` has an attribute called a `WidgetCode`. This attribute is defined (by the system of record) to be an alphanumeric value of length exactly 8, and is exposed in the Common data model. I might implement that in the CDM as follows: ``` lang-cs class Widget { private string _WidgetCode; public string WidgetCode { get => _WidgetCode; set { if (value.Length != 8) throw new InvalidCastException(); _WidgetCode = value; } } } ``` This is OK, but not ideal. The constraint on length is not declarative, therefore it is not visible at design time to a consumer of this class. It will only be found if, at runtime, someone happens to try to write in a value which is not 8 characters long. There may also be other entities which have a `WidgetCode` as an attribute. For example, a `Sale` may contain the `WidgetCode` of the `Widget` which was sold <sup>[2]</sup>. So the data element `WidgetCode` appears in multiple places. So it would make sense to say "You know what, this `WidgetCode` thing is actually a type in its own right. In the context of the CDM it's a primitive<sup>[3]</sup>: ``` lang-cs struct WidgetCode { ... } class Widget { public WidgetCode widgetCode { get; set; } // ... } class Sale { // ... public WidgetCode widgetCode { get; set; } } ``` Now the length constraint on the WidgetCode type can be implemented by the type itself, but it's still going to be a runtime constraint, not a declarative constraint which is visible to the developer at coding-time. Is there any elegant way in C# to create a new "primitive", with constraints which are "declarative" and go beyond those inherent constraints provided by language primitives? --- [1] https://martinfowler.com/articles/201701-event-driven.html [2] I recognize that this is more like a DTO that exposes the structure of, for example, a table in a SQL database. I am not describing a `Sale` class which contains an instance of a `Widget` class like you might expect in, say, an ORM. But remember, what I'm describing is the *content of a message* representing a new sale. In other words, someone created a Sale in some system, and we want to send that data to another system in order to say "Hello other system, here is a Sale which was just created". When we do that, we're clearly cannot pass the lazily-loaded object graph as the message body. [3] Obviously there would be a naming problem here given conventional capitalization guidelines, so you'll have to excuse the camelCase name.
<c#><types><dto>
2019-11-27 03:16:34
LQ_EDIT
59,067,724
Trying to show the size taken up by a specific directory, I'm my case, the HOME directory
<p>I've tried </p> <pre><code>df -H $HOME </code></pre> <p>But I just get</p> <pre><code>Filesystem Size Used Avail Use% Mounted on /dev/mmcblk0p2 31G 7.9G 21G 28% / </code></pre> <p>This is not correct as the total used size of my home directory is only 800MB</p>
<linux><bash><shell><sh>
2019-11-27 10:10:43
LQ_CLOSE
59,068,384
setModal in Java
public DatePicker(JFrame parent) { d = new JDialog(); d.setModal(true); String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" }; JPanel p1 = new JPanel(new GridLayout(7, 7)); p1.setPreferredSize(new Dimension(430, 120)); What is the purpose of `d.setModal(true);` Have tried to search [Here](www.stackoverflow.com) with no convincing answer
<java><swing><jdialog>
2019-11-27 10:45:51
LQ_EDIT
59,070,001
I have published an Android app on app store but whenever I search it by name or package name i can't find it even in the long list of apps
<p>But I can only find it when I click on the button <strong>"View Apps on Playstore"</strong> .What seems to be the problem. It's been almost two days since my app is published.</p>
<android><google-play>
2019-11-27 12:14:05
LQ_CLOSE
59,071,404
Error: Could not find or load main class - Whenever i make a new java file
im currently working on a group project, we are using Eclipse to make a java program and using e-git (eclipse extension) to work together. For some reason today, whenever im trying to make an new java file in the package it will give me the error Error: Could not find or load main class projectPackage.filename, i have no idea what is causing the error as it was fine yesterday.
<java><eclipse>
2019-11-27 13:32:16
LQ_EDIT
59,071,799
psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost"
<p>Got Error while doing docker-compose up.</p> <pre><code>conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5433? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5433? </code></pre> <p>docker-compose.yml:-</p> <pre><code>version: '3' services: dcs_web: build: . depends_on: - db ports: - "5000:5000" db: image: postgres:latest volumes: - db-data:/var/lib/postgresql/data ports: - "5433:5433" environment: - 'POSTGRES_DB:dcmDB' - 'POSTGRES_USER:postgres' - 'POSTGRES_PASSWORD:admin' volumes: db-data: </code></pre> <p>In App config.ini:</p> <pre><code>[DEFAULT] DB_NAME = user DB_PASSWORD = admin DB_USER = postgres DB_HOST = localhost DB_PORT = 5433 DEBUG = True </code></pre> <p>I have gone throught '/var/lib/postgresql/data' location 'listen adress = *' is there . Dont know how to deal with this.</p>
<python><docker><flask><docker-compose><psycopg2>
2019-11-27 13:55:01
LQ_CLOSE
59,072,147
How to write this decorator?
<p>HELP Please . How Write This Decorator (Take a validator if the validator return "True" send args to func :</p> <pre><code>#define decorator here ... def validator(x): return x&gt;=0 @decorator(validator) def f(x): return x**0.5 print(f(4)) #should print 2 print(f(-4)) #should print error </code></pre>
<python>
2019-11-27 14:15:30
LQ_CLOSE
59,072,266
How do I set the starting position of my turtle of my turtle in python to the bottom left of my screen?
Greetings people of Stackoverflow! Currently, I am working on a project that involves turtles. And I have been trying to find a way to make the turtle start at the bottom left of my screen, as opposed to the coordinates (0,0). #My Code import turtle turtle.setworldcoordinates(-1, -1, 20, 20) turtle.fd(250) turtle.rt(90) turtle.fd(250) When I tried looking for solutions, I came across a thread from [Stack][1] that suggested multiple ways to solve the problem, such as the `turtle.setworldcoordinates(-1, -1, 20, 20)` references in my code. If anyone has an idea or a soltion, could they please let me know ASAP. Thanks Kermit [1]: https://stackoverflow.com/questions/14713037/python-turtle-set-start-position
<python><python-3.x><turtle-graphics>
2019-11-27 14:21:49
LQ_EDIT
59,072,669
Can you use python to solve a quadratic without teaching it the quadratic formula?
<pre><code>def f(x): f(x) = x^2 + 2*x + 1 for x in range(-100, 100): if f(x) == 0: print(x) </code></pre> <p>Something like this? I get the error "cannot assign to function call" though</p>
<python>
2019-11-27 14:41:44
LQ_CLOSE
59,072,783
Java- I'm unable to execute my if-else statement
I've been figuring out my code for hours and I can't find any solution for my code The game GUI shouldn't be display anymore when I have clicked on either my Water , Fire Or Nature button,because every button will add 1 to store into my gamePlayed and the maximum would only store up to 5 times,I really cant figure it this out please help me ! Really appreciate that. public class Game { private JPanel Game; private JButton Water; private JButton Nature; private JButton Fire; private int myChoice; private int computerChoice; int gamePlayed = 0; //store the times of game played public Game() { JFrame frame = new JFrame("The Elements"); frame.setContentPane(this.Game); frame.setMinimumSize(new Dimension(500, 500)); frame.pack(); frame.setVisible(true); if (gamePlayed <= 5) { //if the times of game played is less than 5 times , execute the following code Water.addActionListener(new ActionListener() { @Override //Water counter Fire , Nature counter water public void actionPerformed(ActionEvent e) { int select; select = JOptionPane.showConfirmDialog(null, "You're using the power of water", "Water", JOptionPane.YES_NO_OPTION); if (select == JOptionPane.YES_OPTION) { myChoice = 0; computerChoice = computerPlays(); conditionsDisplayResults(myChoice, computerChoice); gamePlayed+=1;//add 1 time of played game when the yes option clicked } } }); Fire.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int select = JOptionPane.showConfirmDialog(null, "You're using the power of fire", "Fire", JOptionPane.YES_NO_OPTION); if (select == JOptionPane.YES_OPTION) { myChoice = 1; computerChoice = computerPlays(); conditionsDisplayResults(myChoice, computerChoice); gamePlayed+=1;//add 1 time of played game when the yes option clicked } } }); Nature.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int select = JOptionPane.showConfirmDialog(null, "You're using the power of nature", "Nature", JOptionPane.YES_NO_OPTION); if (select == JOptionPane.YES_OPTION) { myChoice = 2; computerChoice = computerPlays(); conditionsDisplayResults(myChoice, computerChoice); gamePlayed+=1;//add 1 time of played game when the yes option clicked } } }); else{ //else which when the times of game played is more than 5 times , execute the following code GameResult(); MainMenu mainMenu = new MainMenu(); } }
<java><swing><user-interface>
2019-11-27 14:48:44
LQ_EDIT
59,074,098
Which one is the fastest beween Set and Maps in Java?
<p>Which structure should I use if I need to have several operations of add and remove items into my collection? I need to have the quickest result, and obviously the most efficent one</p>
<java><performance>
2019-11-27 15:59:57
LQ_CLOSE
59,074,782
How to create a editable data-table (with pagination) without using Angular material?
<p>I want to create an editable table in Angular but without using Angular material. The table should also have pagination.</p>
<angular>
2019-11-27 16:38:56
LQ_CLOSE
59,074,879
Express server not listening to specific port 3000 on localhost
<p>app.listen(port, (err) => { if (err) return console.log(err); console.log('Server running on port ' + port); })</p>
<javascript><node.js><express>
2019-11-27 16:44:27
LQ_CLOSE
59,076,282
nodejs push is not a function
<p>I have difficulty making a collection of a class</p> <p>Match example</p> <p>and matches</p> <p>matches is a collection of match</p> <p>my class match:</p> <pre><code>const uuid = require("uuid"); // Match class is a single game Match structure class Match { constructor(players) { this.id = uuid.v4().toString(); this.players = players; } // Match rest methods... // I.E: isMatchEnded, isMatchStarted ... } module.exports = Match; </code></pre> <p>my class Matches</p> <pre><code>class Matches { constructor() { this.matches = {}; } addMatch(match) { this.matches.push(match); } // Matches rest methods... } module.exports = Matches; </code></pre> <p>my main:</p> <pre><code> const matches = new Matches(); const queue = new Queue(); queue.addPlayer(new Player(1,'spt',970)); queue.addPlayer(new Player(2,'test2',1000)); queue.addPlayer(new Player(3,'test3',1050)); queue.addPlayer(new Player(4,'test4',70)); const playerOne = queue.players.find((playerOne) =&gt; playerOne.mmr === 970); const players = queue.searching(playerOne); if(players){ const match = new Match(players); matches.addMatch(match); } console.log(matches); </code></pre> <p>But I am getting this error:</p> <pre><code>Matches.js:7 this.matches.push(match); ^ TypeError: this.matches.push is not a function </code></pre>
<javascript><node.js>
2019-11-27 18:16:36
LQ_CLOSE
59,076,876
How to get input field values based on classes
<p>i have a form where i am showing input fields using loop. all fields have classes. Basically there are 3 fields. 1 - quantity 2 - price 3 - total</p> <p>as the input fields are in loop. so here is the problem that i want to show total from the quantity*price == total but i want to calculate total on click.</p> <p>please help</p>
<javascript><jquery><html>
2019-11-27 18:57:49
LQ_CLOSE
59,077,060
Populate a table from a list using multiple criteria
<p>I need to populate a table using 2 criteria to match the information. the source data is</p> <pre><code> A B C Month Segment Value 01/08/18 Alfa 236.200 01/08/18 Bravo 39.700 01/09/18 Alfa 8.400 01/09/18 Delta 48.200 01/10/18 Bravo 31.700 01/11/18 Foxtrot 53.200 01/11/18 Foxtrot 35.100... </code></pre> <p>And the table is</p> <pre><code> G H I 01/08/18 01/09/18 01/10/18... Alfa Bravo Delta </code></pre> <p>I have an idea to use Index and Match but i cant make it work. I appreciate your help.</p>
<excel><excel-formula><excel-2016>
2019-11-27 19:12:10
LQ_CLOSE
59,077,895
c++ vector isn't showing any values i inserted
<p>So I am trying to convert string to int and then store the int into vector. But when I do that and i create a for loop to display what I have stored in the vector, all i get is 0000. here is my code:</p> <pre><code>#include&lt;iostream&gt; #include&lt;sstream&gt; #include&lt;vector&gt; using namespace std; int main() { std::string str = "&lt;4: 3 2 1&gt;"; vector&lt;int&gt; vect; char c; int found; size_t i = 0; for ( ; i &lt; str.length(); i++ ) { if ( isdigit(str[i]) ) { c=str[i]; found = c-'0'; cout&lt;&lt;found&lt;&lt;endl; vect.push_back(found); } } for(int j=0;j&lt;vect.size();j++) { cout&lt;&lt;vect[i]; } return 0; } </code></pre>
<c++><vector>
2019-11-27 20:21:41
LQ_CLOSE
59,078,263
How to do this question in R without using loop?
<p>Let's say I have a dataframe like this:</p> <pre><code>df=data.frame("A"=factor(c(1,2,1,4,2)), "date"=factor(c("1999","2000","1999","2001","2001")), "value"=c(10,20,30,40,50)) </code></pre> <p>I need to sum the values in the column "value" if they have the same "A" and "date". So what I need is a dataframe like this:</p> <pre><code>dfnew=data.frame("A"=factor(c(1,2,1,4,2)), "date"=factor(c("1999","2000","1999","2001","2001")), "value"=c(10,20,30,40,50), "sum"=c(40,20,40,40,50)) </code></pre> <p>I can do it with a loop, but it is very slow since my dataset is big. Is there any way to do it faster?</p>
<r><dataframe>
2019-11-27 20:52:40
LQ_CLOSE
59,078,862
How can I turn off a liquid valve when a flame goes out?
<p>I'm trying to make my family's life easier and cheaper. I'm heating my barn with a waste oil drip heater. I want to be able to automatically turn off the oil feed valve in case the burner goes out which would cause the barn to fill up with oil and possibly cause a fire.The oil tank will be under about 10 pounds of pressure with a 60 of used oil. Normally it would be attended, but just a few minute error can cause a disaster. I can imagine this could be started out with a hot water heater or dryer flame sensor. But, I don't know where to go from there.</p>
<heat>
2019-11-27 21:44:15
LQ_CLOSE
59,079,241
Euclidean GCD function returns type None instead of int
<p>I'm getting back into mathematics, algorithms, and data structures. Today, I spent time studying up on the Euclidean algorithm and greatest common divisors. </p> <p>Below, I implemented a function to demonstrate what I learned: </p> <pre><code>from math import floor def euclidian(a: int, b: int): # a = b * q + r _q: int = int(floor(a / b)) print(f"Quotient: {_q}") r: int = a % b print(f"Remainder: {r}") a = b print(f"A = B({a})") b = r print(f"B = R({b})") if a != 0 and b != 0: euclidian(a, b) # a = 0; gcd(0, b) = b elif a == 0: print(f"Returning value a({b}) | type: {type(b)}") return b # b = 0; gcd(a, 0) = a elif b == 0: print(f"Returning value a({a}) | type: {type(a)}") return a a: int = 270 b: int = 192 gcd: int = euclidian(a, b) print(f"GCD type: {type(gcd)}") print(f"GCD({a}, {b}) = {gcd}") </code></pre> <p>This recursive function goes through a couple iterations, and ends up returning these results: </p> <pre><code>Quotient: 6 Remainder: 0 A = B(6) B = R(0) Returning value a(6) | type: &lt;class 'int'&gt; GCD type: &lt;class 'NoneType'&gt; GCD(270, 192) = None </code></pre> <p>It's getting later in the day, so perhaps I just need a cup of tea to wake myself up. But I can't seem to wrap my head around why the variable <code>gcd</code> is <code>None</code> and not the integer value of <code>a</code>. What am I missing? </p> <p>Thanks.</p>
<python><python-3.x><algorithm><math>
2019-11-27 22:23:05
LQ_CLOSE
59,081,402
Microservices Java
<p>I am learning about microservices using Java technology (Spring Boot) , I can not find a good book or tutorials. I want to learn about microservices in details.If any one can guide in this it will be great.</p>
<java><spring-boot><microservices>
2019-11-28 03:39:59
LQ_CLOSE
59,082,162
How to intergrate JIRA with our own AngularJS application
I want to integrate JIRA with my own application. So that I can perform operation like, - Create a ticket - Delete a ticket
<angularjs><jira>
2019-11-28 05:17:24
LQ_EDIT
59,082,457
I need the time difference between two times in Hours in sqlserver
I need the time difference between two times in Hours. I am having the start time and end time as shown below: start time | End Time 23:00:00 | 19:00:00 23:00:00 | 07:00:00 I need the output for first row as 20,for second row 8.
<sql><sql-server><time>
2019-11-28 05:47:36
LQ_EDIT
59,084,100
Making changes with ifconfig persistent
<p>can anyone tell me on how to make the following commandline changes persistent? (Like via /etc/network/interfaces or /etc/dhcpcd.conf)</p> <pre><code>route del default ifconfig eth0 add 172.25.1.1 netmask 255.240.0.0 ifconfig eth0:0 netmask 255.240.0.0 route del default route add default gw 172.25.0.1 </code></pre> <p>I need to make these changes to make this RPI use a Router as a default gateway a room next to ours. For more info: We don't have direct access to this Router, as in we can't make any changes to it by ourselves.</p> <p>Am thankful for any insightful responses.</p>
<linux><raspberry-pi3><router><gateway><dhcp>
2019-11-28 07:58:27
LQ_CLOSE
59,084,137
Script dont fuction properly
I have an script that reads the file and compares the string by a pattern, if it returns false it will delete the line on the .txt file. This is my code ``` const readline = require('readline'); const lineReplace = require('line-replace') const fs = require('fs'); const inputFileName = './outputfinal.txt'; const readInterface = readline.createInterface({ input: fs.createReadStream(inputFileName), }); let testResults = []; readInterface.on('line', line => { testResult = test(line); console.log(`Test result (line #${testResults.length+1}): `, testResult); testResults.push({ input: line, testResult } ); if (testResult == false){ console.log(`Line #${testResults.length} will get deleted from this list`); lineReplace({ file: './outputfinal.txt', line: testResults.length, text: '', addNewLine: false, callback: onReplace }); function onReplace({file, line, text, replacedText}) { }; }; }); // You can do whatever with the test results here. //readInterface.on('close', () => { // console.log("Test results:", testResults); //}); function test(str){ let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // email regex str = str.split(","); // string should be of length 3 with str[1] number of length 7 if(str && str.length === 3 && Number(str[1]) && str[1] ) { let temp = str[0].split("-"); // check for 85aecb80-ac00-40e3-813c-5ad62ee93f42 separately. if(temp && temp.length === 5 && /[a-zA-Z\d]{8}/.test(temp[0]) && /[a-zA-Z\d]{4}/.test(temp[1]) && /[a-zA-Z\d]{4}/.test(temp[2]) && /[a-zA-Z\d]{4}/.test(temp[3]) && /[a-zA-Z\d]{12}/.test(temp[4])){ // email regex if(regex.test(str[2])) { return true; } else { return false; } } else { return false } } else { return false; } } ``` But isn't working, returns error no such file or directory, I dont think that is the correct way to do a line remover script
<javascript><node.js><regex>
2019-11-28 08:00:46
LQ_EDIT
59,086,051
Java HasgMap gives wrong values for the given key
I am using a Map<Integer,Map<String,List<Employee>>>. After populating the map , if i immediately retrieve some values with key(String). The returned List<Employee> is correct. After some iteration the values are changing. After first time populating data into the map, i have not used map.put anywhere. Only i am using map.get()
<java><hashmap><hash-collision>
2019-11-28 09:55:12
LQ_EDIT
59,087,910
Put last element of each column in quotation marks
<p>I am trying to put every last element of each column of a csv into quotation marks by using regex in Visual Studio Code. I am matching the string using <code>[^,;]+$</code> and trying to replace it by using <code>"$1"</code>. After replacing, the strings are not in order anymore and some vanish. Can anybody help me out here?</p> <p>My csv is shaped like this: </p> <pre><code>SOME_ID,SOME_ID2,SOME_ID3,NUM,CODE 1234,100,1723,1,403 1235,101,1723,2,486 1236,101,1723,3,5822 </code></pre>
<regex><csv><perl><replace>
2019-11-28 11:32:03
LQ_CLOSE
59,090,356
is there any way with which we can print the following pattern?
class pattern { public static void main() { int i,j,p=1; for(i=1;i<=5;i++) { for(j=1;j<=i; j++) { System.out.print(p+" "); p=p+2; } if(i>=2) p=p-2; System.out.println (); } } } i want the below written output 1 3 5 5 7 9 7 9 11 13 9 11 13 15 17 but the output obtained by the above written code is given below 1 3 5 5 7 9 9 11 13 15 15 17 19 21 23 i want last digit of second row to be displayed at the starting of third row and last two digits of third row to be displayed in the beginning of the fourth row and so on.
<java>
2019-11-28 13:49:06
LQ_EDIT
59,090,539
Javascript Value To PHP variable
javascript code <script type="text/javascript"> $("#test").click(function() { getQuerystring(this); return false; }); function getQuerystring(el) { console.log(el.href); var getUrlParameter = function(sParam) { var sPageURL = el.href.split('?')[1], sURLVariables = sPageURL.split('&'), sParameterName; for (var i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); } } }; var blog = getUrlParameter('c'); //document.getElementById('detail').innerHTML = blog; document.cookie = "blog = " + blog; } </script> html code <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="border: dashed; size: auto;"> <a name="divtest" href="#detail?c=active" id="test">testing</a> </div> <div id="detail" style="border: 2px; size: auto;"> <?php $chk = $_COOKIE['blog']; echo $chk; ?> </div> the javascript code should set the cookie. and then php get the values saved in the cookie. i basically wants to send value from javascript to php on same page. but it seems to be an error" Notice: Undefined index: blog in C:\wamp64\www\test\ajax.php on line 40".i hae searched alot but didnt find proper solution.kindly help me correcting my code. i will be thankful to you.
<javascript><php><html>
2019-11-28 13:57:45
LQ_EDIT
59,093,592
sorry if this question is so simple. how to produce output string and numbering from the same statement in python?eg. "output_CH = 0.7 and CH_healthy"
if input_CH in range (185, 211): if input_CH >= 185 and input_CH < 190: output_CH = (1/5 * input_CH) - 37 elif input_CH >= 190 and input_CH <= 200: output_CH = 1 else: output_CH = (-1/10 * input_CH) + 21 output_CH = "CH_healthy"
<python><python-3.x>
2019-11-28 17:06:04
LQ_EDIT
59,096,332
here iOS SDK creating draggable marker
I want to create draggable marker but it doesn't work. What I have missing? ''' let marker = NMAMapMarker(geoCoordinates: coordinates, image: markerImage!) marker.isDraggable = true mapView.add(mapObject: maker) mapView.respond(to: .markerDragBegan) { (drag, map, marker) -> Bool in return true } '''
<ios><here-api>
2019-11-28 21:28:07
LQ_EDIT
59,096,452
Swift How to decode JSON without knowing the key name?
<p>I have json that looks something like this:</p> <pre><code>"events": { "1": { "id": 1, "name": "something" }, "2": { "id": 2, "name": "something2" },... } </code></pre> <p>Is there any way to decode this type of JSON where I dont know the name of the key?</p>
<json><swift><decode><decoding>
2019-11-28 21:41:00
LQ_CLOSE
59,096,612
Java- How do I store my numbers in my int?
I'm a beginner still trying to learn java , I have no clue what have I did wrong on my code because they seem logically correct, really appreciate if someone can give me a hand ! Thanks very much ! What I'm trying to do is create an int and when everytime I clicked yes in my confirmation dialog the int will increase by 1 and the whole program should stop executing when the number that store into that int reached to 5. //This is the main game public class Game { private JPanel Game; private JButton Water; private JButton Nature; private JButton Fire; private JLabel countDownLabel; private JLabel computerScore; private int myChoice; private int computerChoice; int gamePlayed = 0; //store the times of game played public Game() { JFrame frame = new JFrame("The Elements"); frame.setContentPane(this.Game); frame.setMinimumSize(new Dimension(500, 500)); frame.pack(); frame.setVisible(true); //if the times of game played is less than 5 times , execute the following code if (gamePlayed <= 5) { Water.addActionListener( new ActionListener() { @Override //Water counter Fire , Nature counter water public void actionPerformed( ActionEvent e ) { int select; select = JOptionPane.showConfirmDialog( null, "You're using the power of water", "Water", JOptionPane.YES_NO_OPTION ); if ( select == JOptionPane.YES_OPTION ) { myChoice = 0; computerChoice = computerPlays(); conditionsDisplayResults( myChoice, computerChoice ); gamePlayed = gamePlayed + 1;//add 1 time of played game when the yes option clicked } } } ); Fire.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { int select = JOptionPane.showConfirmDialog( null, "You're using the power of fire", "Fire", JOptionPane.YES_NO_OPTION ); if ( select == JOptionPane.YES_OPTION ) { myChoice = 1; computerChoice = computerPlays(); conditionsDisplayResults( myChoice, computerChoice ); gamePlayed += 1;//add 1 time of played game when the yes option clicked } } } ); Nature.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { int select = JOptionPane.showConfirmDialog( null, "You're using the power of nature", "Nature", JOptionPane.YES_NO_OPTION ); if ( select == JOptionPane.YES_OPTION ) { myChoice = 2; computerChoice = computerPlays(); conditionsDisplayResults( myChoice, computerChoice ); gamePlayed += 1;//add 1 time of played game when the yes option clicked } } } ); } else{ //else which when the times of game played is more than 5 times , execute the following code GameResult(); MainMenu mainMenu = new MainMenu(); } }
<java>
2019-11-28 22:02:50
LQ_EDIT
59,096,714
Calling Angular application not from the root path
<p>I created a simple Angular app with some routes inside. Now I am calling it from my browser:</p> <pre><code>http://127.0.0.1:8000/products_whatever </code></pre> <p>For this to work, to my understanding the following is needed:</p> <ol> <li>Web server should be configured to return <code>index.html</code> on request to any relative URL. Index.html, i.e. my Angular app will inspect that local path, figure out if it is valid or not and decide what to do. Is that right?</li> <li>What is the exact mechanism that is used to pass that local relative path to <code>index.html</code>? Is that some special HTTP header?</li> </ol>
<angular>
2019-11-28 22:15:30
LQ_CLOSE
59,097,365
warning: dereferencing 'void *' pointer error
With a C program written for solving a heat problem I am getting following error: [enter image description here][1] The program was meant for this: [enter image description here][2] Here is my code: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <unistd.h> #include <mpi.h> #define COLS 1000 #define ROWS 1000 #define WHITE "15 15 15 " #define RED "15 00 00 " #define ORANGE "15 05 00 " #define YELLOW "15 10 00 " #define LTGREEN "00 13 00 " #define GREEN "05 10 00 " #define LTBLUE "00 05 10 " #define BLUE "00 00 10 " #define DARKTEAL "00 05 05 " #define BROWN "03 03 00 " #define BLACK "00 00 00 " void copyNewToOld(float grid_a[ROWS][COLS], float grid_b[ROWS][COLS], int x_lower, int x_upper) { int x, y; for (x = x_lower; x < x_upper; ++x) { for (y = 0; y < COLS; ++y) { grid_b[x][y] = grid_a[x][y]; } } } void calculateNew( float grid_a[ROWS][COLS], float grid_b[ROWS][COLS], int x_lower, int x_upper ) { // Adjust bounds if (x_lower == 0) x_lower = 1; if (x_upper == ROWS) x_upper = ROWS - 1; int x, y; for (x = x_lower; x < x_upper - 1; ++x) { for (y = 1; y < COLS - 1; ++y) { grid_a[x][y] = 0.25 * (grid_b[x-1][y] + grid_b[x+1][y] + grid_b[x][y-1] + grid_b[x][y+1]); } } } void printGridtoFile(FILE* fp, float grid[ROWS][COLS], int x_lower, int x_upper) { int x, y; for (x = x_lower; x < x_upper; ++x) { for (y = 0; y < COLS; ++y) { if (grid[x][y] > 250) { fprintf(fp, "%s ", RED ); } else if (grid[x][y] > 180) { fprintf(fp, "%s ", ORANGE ); } else if (grid[x][y] > 120) { fprintf(fp, "%s ", YELLOW ); } else if (grid[x][y] > 80) { fprintf(fp, "%s ", LTGREEN ); } else if (grid[x][y] > 60) { fprintf(fp, "%s ", GREEN ); } else if (grid[x][y] > 50) { fprintf(fp, "%s ", LTBLUE ); } else if (grid[x][y] > 40) { fprintf(fp, "%s ", BLUE ); } else if (grid[x][y] > 30) { fprintf(fp, "%s ", DARKTEAL ); } else if (grid[x][y] > 20) { fprintf(fp, "%s ", BROWN ); } else { fprintf(fp, "%s ", BLACK ); } } fprintf(fp, "\n"); } } int main(int argc, char **argv) { int h, w, cycles, heat; float grid_a[ROWS][COLS]; float grid_b[ROWS][COLS]; if (argc != 2) { printf("Usage: ./program <number of timestamps>\n"); exit(0); } cycles = atoi(argv[1]); MPI_Init(NULL, NULL); int mpi_size; MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); int mpi_rank; MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); int x_lower = mpi_rank * ROWS / mpi_size; int x_upper = (mpi_rank+1) * ROWS / mpi_size; /*fprintf(stderr, "CPU=%d/%d x_lower=%d x_upper=%d\n", mpi_rank, mpi_size, x_lower, x_upper);*/ for (h = x_lower; h < x_upper; ++h) { for (w = 0; w < COLS; ++w) { grid_a[w][h] = 20; } } for (heat = 299; heat < 700; ++heat) { grid_a[0][heat] = 300; } for (cycles; cycles > 0; --cycles) { /*fprintf(stderr, "[%d] Cycle=%d\n", mpi_rank, cycles);*/ copyNewToOld(grid_a, grid_b, x_lower, x_upper); if (mpi_rank != 0) MPI_Sendrecv( grid_a[x_lower-1], // sendbuf COLS, // sendcount MPI_FLOAT, // sendtype mpi_rank-1, // dest 0, // sendtag grid_b[x_lower-1], // recvbuf COLS, // recvcount MPI_FLOAT, // recvtype mpi_rank-1, // source 0, // recvtag MPI_COMM_WORLD, // communicator MPI_STATUS_IGNORE // status ); if (mpi_rank+1 != mpi_size) MPI_Sendrecv( grid_a[x_upper+1], // sendbuf COLS, // sendcount MPI_FLOAT, // sendtype mpi_rank+1, // dest 0, // sendtag grid_b[x_upper+1], // recvbuf COLS, // recvcount MPI_FLOAT, // recvtype mpi_rank+1, // source 0, // recvtag MPI_COMM_WORLD, // communicator MPI_STATUS_IGNORE // status ); calculateNew(grid_a, grid_b, x_lower, x_upper); } FILE* fp; if (mpi_rank == 0) { fp = fopen("c.pnm", "w"); fprintf(fp, "P3\n%d %d\n15\n", COLS, ROWS); fclose(fp); } char dummy = 1; if (mpi_rank != 0) MPI_Recv( &dummy, // buf 1, // count MPI_BYTE, // type mpi_rank-1, // source 0, // tag MPI_COMM_WORLD, // communicator MPI_STATUS_IGNORE // status ); /*fprintf(stderr, "[%d] Open file\n", mpi_rank);*/ fp = fopen("c.pnm", "a"); if (!fp) *NULL; /*fprintf(stderr, "[%d] Start printing\n", mpi_rank);*/ printGridtoFile(fp, grid_a, x_lower, x_upper); /*fprintf(stderr, "[%d] Done printing\n", mpi_rank);*/ fclose(fp); if (1) MPI_Send( &dummy, // buf 1, // count MPI_BYTE, // type (mpi_rank+1) % mpi_size, // source 0, // tag MPI_COMM_WORLD // communicator ); if (mpi_rank == 0) { MPI_Recv( &fp, // buf 1, // count MPI_UNSIGNED_LONG, // type mpi_size-1, // source 0, // tag MPI_COMM_WORLD, // communicator MPI_STATUS_IGNORE // status ); system("convert c.pnm c.png"); } MPI_Finalize(); return 0; } <!-- end snippet --> Any help with this issue would be great I'm fairly new to C. Hoping to use this code and for mpirun on Bridges supercomputer with multiple varied processes. [1]: https://i.stack.imgur.com/jwFzG.jpg [2]: https://i.stack.imgur.com/84U5G.png
<c><pointers>
2019-11-29 00:07:42
LQ_EDIT
59,097,798
Python - Breaking a Word into a given list of "syllables"
I'm trying to write a function in Python that will return True or False based on string matching to see if a given list of "syllables" mixed and matched can form a word. The two inputs would be the word and the list of syllables. Some examples: **Inputs**: “hello” , [”hel”, ”hol”, ”llo”, ”he”] **Output**: True , **Inputs** ”world” , [”woo”, ”wor”, ”rld”, ”or”] **Output**False
<python><string><algorithm>
2019-11-29 01:34:00
LQ_EDIT
59,099,581
Wake up the bot on a hi and should start with same functionality
Any one kindly can tell how to wake up the bot on Hi.Actually I am in a dialog named as product issue having a prompt of adaptive card , i just want after clicking on that adaptive card it go to main dialog show functionality with which my bot have began.
<c#><botframework><azure-bot-service><adaptive-cards>
2019-11-29 06:12:56
LQ_EDIT
59,100,713
how to retrieve the id just created in the database in laravel?
<p>how do I retrieve the id that was just created in the database, when I press the save button, the data is created, and I want to retrieve the id from that data</p> <p>this my controller code</p> <pre><code>$cart= new cart; $cart-&gt;user_id = $request-&gt;user_id; $cart&gt;vendor_name = $request-&gt;vendor_name; $cart-&gt;save(); </code></pre> <p>I want to retrieve the id of the data just created</p>
<laravel><laravel-5><eloquent>
2019-11-29 07:46:09
LQ_CLOSE
59,101,007
How to get control info of Notepad write by python language
I have code bellow copy from website : https://pywinauto.github.io/ : ``` from pywinauto.application import Application app = Application().start("notepad.exe") app.UntitledNotepad.menu_select("Help->About Notepad") app.AboutNotepad.OK.click() app.UntitledNotepad.Edit.type_keys("pywinauto Works!", with_spaces = True) ``` I have a question are : how to know Notepad have UntitledNotepad control. I use Autoit to get control info but can't get info of some controls, can't get UntitledNotepad control, but why code above know UntitledNotepad in Notepad. Please show me way to know UntitledNotepad control exist in Notepad. Thanks !!!
<python><frameworks><pywinauto>
2019-11-29 08:10:45
LQ_EDIT
59,101,792
Run CSS in PHP function WooCommerce
<p>I wrote this function:</p> <pre><code>add_action( 'woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1); function adding_custom_price( $cart ) { global $woocommerce; foreach ( $cart-&gt;get_cart() as $cart_item ) { //If there is minimum 1 coupon active if (!empty(WC()-&gt;cart-&gt;applied_coupons)) { } //If there isn't any coupon in cart else { //Here I want to do some styling in CSS or run something in jQuery } } } </code></pre> <p>I want to do some CSS in it and run some jQuery in the else, how can I do that?</p>
<php><jquery><css><wordpress><woocommerce>
2019-11-29 09:07:03
LQ_CLOSE
59,102,038
why type hint cannot be used in the for loop
```for i: str in test_string:``` I received the **invalid syntax** error, I would like to know the reason behind.
<python><python-3.x>
2019-11-29 09:24:04
LQ_EDIT
59,102,680
How to reduce the value from multiple rows by calculation
<p>I have table called : stock , From that qty will be reduced by priority column in the respective warehouse.</p> <pre> ------------------------------------------- Id SKU priority Warehouse Qty -------------------------------------------- 1 sku1 p1 W1 1 2 sku1 p2 w2 2 3 sku1 p3 w3 3 </pre> <p>From the above table, 4 qty item will be reduced based on priority.</p> <p>Expected output :</p> <pre> ------------------------------------------ Id SKU priority Warehouse Qty -------------------------------------------- 1 sku1 p1 W1 0 2 sku1 p2 w2 0 3 sku1 p3 w3 2 </pre> <p>Can anyone suggest how to achieve it.</p>
<mysql><stored-procedures>
2019-11-29 10:05:25
LQ_CLOSE
59,102,750
Symfony4.3.2 - Allow access to specific pages
I am on Symfony 4.3.2, trying to get a way to allow users having role (CommissionOwner) access to only following specific pages. - www.xyz.com/Loginlandingpage - www.xyz.com/reportSalesCommissions I am trying in **myApp/config/packages/security.yaml** access_control: - { path: ^/reportSalesCommissions, roles: IS_CommissionOwner }
<symfony4><symfony-security>
2019-11-29 10:10:42
LQ_EDIT
59,103,845
How can i convert days names to dates of the current month?
<p>I have an array of days in a month excluding friday and sunday as they aren't inculded in policy, i want to convert the array of days names to the dates of the current month but when i convert it is in incorrect format because it shows for different month <a href="https://i.stack.imgur.com/gTQ3u.png" rel="nofollow noreferrer">enter image description here</a></p>
<php><date><time><type-conversion><dayofweek>
2019-11-29 11:21:22
LQ_CLOSE
59,105,631
When I select the incorrect answer the next question loads with the the answer already displayed
I am completely new to coding and c#. I am studying a level 3 ICT and in my programming subject we are asked to make a quiz for essential skills students(Using forms.). I have been asked to create a very basic login in screen, topic selection screen, level selection screen and the actual questions and answers; answers are buttons. My issue is when I select the incorrect answer the next question loads but displays the correct answer for that question. Not quite sure what I need to do. I wanted to get this fixed over the weekend so I am unable to ask my teacher. The must remain very basic. Here is my code. I appreciate any help on this topic, Thanks. Level 0 Form - ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EssentialSkills.Numeracy { public partial class Level0num : Form { Point p1 = new Point(142, 303); Point p2 = new Point(322, 303); Point p3 = new Point(499, 303); List<Point> points = new List<Point>(); public Level0num() { InitializeComponent(); Globals.listQuestionsNum0.Add("1 + 1"); Globals.listQuestionsNum0.Add("9 x 1"); Globals.listQuestionsNum0.Add("10 x 3"); Globals.listQuestionsNum0.Add("3 / 3"); Globals.listQuestionsNum0.Add("2 + 5 + 6"); Globals.listQuestionsNum0.Add("8 x 3"); Globals.listQuestionsNum0.Add("99 - 87"); Globals.listQuestionsNum0.Add("60 + 10 "); Globals.listQuestionsNum0.Add("55 + 15"); Globals.listQuestionsNum0.Add("40 x 20"); Globals.listQuestionsNum0.Add("120 / 60"); Globals.listQuestionsNum0.Add("1.0 + 1.2"); Globals.listQuestionsNum0.Add("3 x 13"); Globals.listQuestionsNum0.Add("2 x 2"); Globals.listQuestionsNum0.Add("10 x 30"); Globals.listQuestionsNum0.Add("8 x 9"); Globals.listQuestionsNum0.Add("9 x 9"); Globals.listQuestionsNum0.Add("3 x 1"); Globals.listQuestionsNum0.Add("4 / 4"); Globals.listQuestionsNum0.Add("21 / 7"); Globals.listQuestionsNum0.Add("42 / 7"); Globals.listQuestionsNum0.Add("10 + 10 - 1"); Globals.listQuestionsNum0.Add("84 - 2 + 3"); Globals.listQuestionsNum0.Add("50 + 9 + 8"); Globals.listQuestionsNum0.Add("-1 + 2"); Globals.listQuestionsNum0.Add("33 + 88"); Globals.listQuestionsNum0.Add("10 - 3"); Globals.listQuestionsNum0.Add("32 + 2 x 1"); Globals.listQuestionsNum0.Add("1 x 543 + 1"); Globals.listQuestionsNum0.Add("3 + 10 x 2"); Globals.listAnswersNum0.Add(1 + 1); Globals.listAnswersNum0.Add(9 * 1); Globals.listAnswersNum0.Add(10 * 3); Globals.listAnswersNum0.Add(3 / 3); Globals.listAnswersNum0.Add(2 + 5 + 6); Globals.listAnswersNum0.Add(8 * 3); Globals.listAnswersNum0.Add(99 - 87); Globals.listAnswersNum0.Add(60 + 10); Globals.listAnswersNum0.Add(55 + 15); Globals.listAnswersNum0.Add(40 * 20); Globals.listAnswersNum0.Add(120 / 60); Globals.listAnswersNum0.Add(1.0 + 1.2); Globals.listAnswersNum0.Add(3 * 13); Globals.listAnswersNum0.Add(2 * 2); Globals.listAnswersNum0.Add(10 * 30); Globals.listAnswersNum0.Add(8 * 9); Globals.listAnswersNum0.Add(9 * 9); Globals.listAnswersNum0.Add(3 * 1); Globals.listAnswersNum0.Add(4 / 4); Globals.listAnswersNum0.Add(21 / 7); Globals.listAnswersNum0.Add(42 / 7); Globals.listAnswersNum0.Add(10 + 10 - 1); Globals.listAnswersNum0.Add(84 - 2 + 3); Globals.listAnswersNum0.Add(50 + 9 + 8); Globals.listAnswersNum0.Add(-1 + 2); Globals.listAnswersNum0.Add(33 + 88); Globals.listAnswersNum0.Add(10 - 3); Globals.listAnswersNum0.Add(32 + 2 * 1); Globals.listAnswersNum0.Add(1 * 543 * 1); Globals.listAnswersNum0.Add(3 + 10 * 2); points.Add(p1); points.Add(p2); points.Add(p3); } private void LoadQuestions() { lblCountdownval.Visible = false; lblCountdown.Visible = false; Globals.intQuestionNumber += 1; lblQuestionsNumber.Text = "Question Number: " + Globals.intQuestionNumber.ToString(); Random random = new Random(); Globals.listIndex = random.Next(0, Globals.listAnswersNum0.Count - 1); lblQuestion.Text = Globals.listQuestionsNum0.ElementAt(Globals.listIndex); btnCorrect.Text = Globals.listAnswersNum0.ElementAt(Globals.listIndex).ToString(); btnAnswer1.Text = random.Next(100).ToString(); btnAnswer3.Text = random.Next(100).ToString(); int locationIndex = random.Next(0, 3); btnCorrect.Location = points.ElementAt(locationIndex); locationIndex = random.Next(0, 3); btnAnswer1.Location = points.ElementAt(locationIndex); while ((btnAnswer1.Location == btnCorrect.Location)) { locationIndex = random.Next(0, 3); btnAnswer1.Location = points.ElementAt(locationIndex); } locationIndex = random.Next(0, 3); btnAnswer3.Location = points.ElementAt(locationIndex); while ((btnAnswer3.Location == btnCorrect.Location) || (btnAnswer3.Location == btnAnswer1.Location)) { locationIndex = random.Next(0, 3); btnAnswer3.Location = points.ElementAt(locationIndex); } } public void showCorrectAnswer() { timerLoadQuestion.Start(); lblCountdownval.Visible = true; lblCountdown.Visible = true; lblCountdownval.Text = "5"; lblCountdown.Text = "Next question will load in .... "; btnAnswer1.Visible = false; btnAnswer3.Visible = false; btnCorrect.Location = p2; btnCorrect.BackColor = Color.Green; } private void Level0num_Load(object sender, EventArgs e) { lblLoggedUser.Text = Globals.loggedUser; lblQuestionsNumber.Text = "Question Number: "; LoadQuestions(); Globals.s = 0; lblScore.Text = "Score: " + Globals.s; } private void btnBack_Click(object sender, EventArgs e) { frmNumeracy back = new frmNumeracy(); this.Close(); back.ShowDialog(); } private void btnAnswer1_Click(object sender, EventArgs e) { showCorrectAnswer(); MessageBox.Show("Incorrect"); LoadQuestions(); } private void btnAnswer3_Click(object sender, EventArgs e) { showCorrectAnswer(); MessageBox.Show("Incorrect"); LoadQuestions(); } private void btnCorrect_Click(object sender, EventArgs e) { MessageBox.Show("Correct!"); Globals.s += 1; lblScore.Text = "Score: " + Globals.s.ToString(); LoadQuestions(); } } } ``` here is my globals class: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EssentialSkills { public static class Globals { public static string username, password; public static string user1, user2, user3, user4, user5, user6, loggedUser, admin; public static string pass1, pass2, pass3, pass4, pass5, pass6, adminPass1; public static List<string> listQuestionsNum0 = new List<string>(); public static List<double> listAnswersNum0 = new List<double>(); public static int intQuestionNumber = 0; public static int listIndex; public static int s; } } ``` Many thanks.
<c#><winforms><linq>
2019-11-29 13:22:00
LQ_EDIT
59,105,774
Why is javascript recursive function returning 'undefined' even when I am returning a value
<p>I am looking at how to implement binary search in a javascript function and found that when I return the value and save it into a variable then when I console.log this comes as undefined.</p> <pre><code>const recursiveBinarySearch = (numbers, target) =&gt; { const midpoint = Math.floor(numbers.length / 2); if (numbers[midpoint] === target){ //it does found the value and return return 'FOUND'; } else if(numbers[midpoint] &lt; target) { recursiveBinarySearch(numbers.slice(midpoint+1), target); } else { recursiveBinarySearch(numbers.slice(midpoint-1), target); } } var result = recursiveBinarySearch([1, 2, 3, 4, 6, 8, 100] , 8); console.log(result); // Here is returning undefined </code></pre> <p>Thanks in advance.</p>
<javascript><binary-search>
2019-11-29 13:30:46
LQ_CLOSE
59,106,395
HTML - Allow only pattern with numbers and dots for input type text
<p>I need to have a text input that accepts only numbers and the dot sign for float numbers.</p> <p>I don't want a number type input.</p>
<html><regex>
2019-11-29 14:12:44
LQ_CLOSE
59,106,783
I can't view the database content on a php page
<p>I can't view the database content on php page I want to fetch data using ID thats the code :</p> <pre><code>&lt;?php //connect with database $servername = "localhost"; $userdbname = "root"; $dbpassword = ""; $dbname = "users"; $usid = 0; $docname = ''; $conn = new mysqli($servername, $userdbname, $dbpassword, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $sql = "SELECT * FROM users WHERE id=".$usid; if ($conn-&gt;query($sql) === TRUE) { $conn-&gt;close(); $URLS = array(); while ($row = $result-&gt;fetch_array()) { $docname= $row['docname']; } header("Location:Editeform.php"); } ?&gt; </code></pre> <p>This is the form I am trying to view the data in :</p> <pre><code>&lt;div class="form-group"&gt; &lt;input type="text" class="form-input" name="docname" id="name" placeholder="Your Name" value="&lt;?php echo $users['docname']; ?&gt;" /&gt; &lt;/div&gt; </code></pre>
<php><mysql>
2019-11-29 14:41:38
LQ_CLOSE
59,107,818
Regex Pattern for domain or hostnames or probably the best way to match a pattern
<p>Here's a sample domain name FQDN, How can I match the domain name after the short hostname? instead of making a pattern match for domain names? Advice is really much appreciated.</p> <pre><code>host1.dept1.domain.com host2.domain.com host3.domain3.com </code></pre>
<arrays><regex><ruby>
2019-11-29 15:50:39
LQ_CLOSE
59,107,922
What is the purpose of period (.) in the ~/.bashrc
<p>I've been studying the bash scripting then i noticed using the period wildcard in the bash script, in my sense the period treated as current directory, </p> <p>I have snippet </p> <pre><code>if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi </code></pre> <p><strong>. /etc/bash_completion</strong> In this script what is the use of the (.), period. </p>
<linux><bash><shell>
2019-11-29 15:57:39
LQ_CLOSE
59,108,603
Pass a vector of pointers to function in c++
<p>I saw many posts here but none of them explains what I'm trying to do. I have the vector <code>vector &lt;Car*&gt; carVector;</code> and I want to pass it to a function so I can read the information of the objects in there. The objective is to pass it and then I can use it in this cicle</p> <pre><code>for (i = 0; i &lt; racetrack.size(); i++) { for (int j = 1; j &lt; nRaceTracks + 1; j++) { if (racetrack[i]-&gt;getNome() == info[j]) { size= racetrack[i]-&gt;getTrackSize() / 100; for (int c = 0; c &lt; carVector.size(); c++) carVector[c]-&gt;chargeBattery(500); } } } </code></pre>
<c++><function><vector>
2019-11-29 16:54:33
LQ_CLOSE
59,109,331
mapping integers 1-max onto 100 integers from 1-1,000,000
<p>I need to map a Java integer from the range 1-max to the range 1-1,000,000, but only using 100 particular (non-linear) values in the destination range. The 100 values are:<br> 1-10 (so the first 10 values map to themselves)<br> then by 5's: 15, 20, 25 ... to 100<br> then by 50's: 150, 200, 250 ... to 1,000<br> and so on, the final values being 900,000 &nbsp;950,000 and 1,000,000<br> I can't quite get my head around anything more elegant than a bag of nested if/else-if's.<br> The solution is not time/cycle sensitive.</p>
<java>
2019-11-29 18:02:02
LQ_CLOSE
59,109,620
GoLang - Conversion of type "interface {}" to another interface in a slice of type "interface {}" via reflection
I've been burning neurons for hours and I couldn't solve this question. I have a slice of type People, I need to pass this slice to a function that gets the type "interface {}". The People type "implements" an interface called HasCustomField, but I can't do the type conversion within the function, as I am doing: type HasCustomField interface { GetCustomField() map[string]interface{} } type People struct { Name string customField map[string]interface{} } func (c *People) GetCustomField() map[string]interface{} { if c.customField == nil { c.customField = make(map[string]interface{}) } return c.customField } func main() { users := []People{{Name:"Teste"},{Name:"Mizael"}} ProcessCustomField(&users) } func ProcessCustomField(list interface{}) { if list != nil { listVal := reflect.ValueOf(list).Elem() if listVal.Kind() == reflect.Slice { for i:=0; i<listVal.Len(); i++ { valueReflect := listVal.Index(i).Interface() objValueFinal, ok := valueReflect.(HasCustomField) if ok { fmt.Println("OK") } else { fmt.Println("NAO OK") } } } The result is always "Not OK", I can not do the conversion, I tried several other ways too, including calling the method "GetCustomField" via reflection, but was unsuccessful.
<go><slice>
2019-11-29 18:34:11
LQ_EDIT
59,110,159
Thread Sleep and ReadKey doesn't cooperate
<p>I want to stop the whole do-while loop by using space and write out my WriteLine, but it doesn't do anything on pressing spacebar. I think it's something to do with Thread.Sleep, maybe It doesn't allow user input while on Sleep. I would be really happy if someone could enlighten me why this doesn't work</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace casinov2 { class Program { static void Main(string[] args) { int x=3; int y = 15; int[] elemek = new int[7]; do{ while (!Console.KeyAvailable){ for (int i = 0; i &lt; 5; i++){ Console.Clear(); Console.SetCursorPosition(x, y); x++; Console.WriteLine("{0:██}{1:██}{2:██}", elemek[i], elemek[i + 1], elemek[i + 2]); System.Threading.Thread.Sleep(100); if (i &gt;= 4){ for (int j = 0; j &lt; 5; j++){ Console.Clear(); Console.SetCursorPosition(x, y); x--; Console.WriteLine("{0:██}{1:██}{2:██}", elemek[i], elemek[i + 1], elemek[i + 2]); System.Threading.Thread.Sleep(100); } i = -1; } } } } while (Console.ReadKey(true).Key != ConsoleKey.Spacebar); Console.WriteLine("ready"); Console.ReadLine(); } } } </code></pre>
<c#>
2019-11-29 19:35:08
LQ_CLOSE
59,111,939
importing an class from the same directory in Perl
<p>i have a directory with main.pl and Product.pl. in the main.pl i try to import the Product class but the execution fails when i run perl main.pl complaining that cant locate Product.pm in @INC. My directory is not in the @INC list. How can i fix this?</p>
<linux><perl><oop>
2019-11-29 23:26:29
LQ_CLOSE
59,112,151
Two constructor calls inside one constructor in C#
<p>I know how to call another constructor for a constructor from the same class or the base class, but how can I do both at once? Here is an example of what I am looking to achieve, noting that in a real case we might want to do something more complex than just set a property:</p> <pre><code>public class BaseClass { public BaseClass(object param) { // base constructor } } public class DerivedClass { DateTime Date { get; private set; } public DerivedClass() { Date = GenerateDate(); } public DerivedClass(object param) : base(param) { // How do I make it call DerivedClass() ? } } </code></pre>
<c#><constructor><base>
2019-11-30 00:08:32
LQ_CLOSE
59,112,429
How to code a javvascript to indicate item in a list clicked?
This javascript fails to show the line number of item clicked. <!DOCTYPE html> <html> <body> <script> function registerHandlers() { var as = document.getElementsByTagName('a'); for (var i = 0; i < as.length; i++) { as[i].onclick = function() { alert(i); return true; } } } </script> In my life, I used the following web search engines:<br/> <a href="//www.yahoo.com">Yahoo!</a><br/> <a href="//www.altavista.com">AltaVista</a><br/> <a href="//www.google.com">Google</a><br/> </body> </html>
<javascript>
2019-11-30 01:22:33
LQ_EDIT
59,113,034
Trying to make the answer randomly generated after retry in C#
<pre><code>using System; namespace Test { class Program { static void Main(string[] args) { int num1 = int.Parse(args[0]); int num2 = int.Parse(args[1]); bool GameOver = false; int turn = 3; Random random = new Random(); int answer = random.Next(num1, num2); // string input = ""; Console.WriteLine("Hello, welcome to the guess a number challenge"); while (!GameOver) { if (turn != 0) { turn--; Console.WriteLine($"Please Select number between {num1} to {num2}:"); int SelectedNumber = int.Parse(Console.ReadLine()); if (SelectedNumber &lt; answer &amp;&amp; SelectedNumber &gt;= num1) { System.Console.WriteLine("Almost there, just the number is too small\n"); } else if (SelectedNumber &gt; answer &amp;&amp; SelectedNumber &lt;= num2) { System.Console.WriteLine("Your number is too big\n"); } else if(SelectedNumber == answer) { System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n"); GameOver = true; retry(); } else { System.Console.WriteLine("Your number is out of range\n"); } } else { System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}"); GameOver = true; retry(); } void retry() { System.Console.WriteLine("Would you like to retry? Y/N"); string input = Console.ReadLine(); string ConsoleInput = input.ToLower(); if(ConsoleInput == "y") { GameOver = false; turn = 3; } else if(ConsoleInput == "n") { GameOver = true; } else { Console.WriteLine("Invalid input"); retry(); } } } } } } </code></pre> <p>Hello all, just want to ask a question. I tried to build "guess a number" game in terminal, where player has to guess a number based on the number range given. I tried to make the <em>answer</em> randomly generated, thus the Random class. and the answer will be randomized after retry. The problem is, after each retry, the <em>answer</em> is still the same. I am not sure where did I did wrong. Thanks for the help, and sorry for the noob question.</p>
<c#><random>
2019-11-30 03:47:53
LQ_CLOSE
59,113,673
Pet.Acropromazine(): Not all code paths return a value
<p>I am trying to make a class for a pet name, age, weight and if it is a dog or cat and the have to methods to calculate the dosage for Aceptomazine and Carprofen. I want to return a different value for both the Aceptomazine and Carprofen method for a cat and a dog but when I do it says Pet.Acropromazine: not all code paths return a value and the same error for the Carprofen method. I am not sure why it's doing this. any help would be appericated</p> <pre><code> class Pet { private string mName; private int mAge; private double mWeight; private string mType; public string Name { get { return mName; } set { if (string.IsNullOrEmpty(value) ) { mName = value; } else { throw new Exception("Name cannot be empty"); } } } public int Age { get { return mAge; } set { if (value &gt; 1) { mAge = value; } else { throw new Exception("Age must be greater than 1"); } } } public double Weight { get { return mWeight; } set { if (value &gt; 5) { mWeight = value; } else { throw new Exception("Age must be greater than 5"); } } } public Pet() { mName = "Super Pet"; mType = "Dog"; mAge = 1; mWeight = 5; } public double Acropromazine() { if (mType == "Dog") { return (mWeight / 2.205) * (0.03 / 10); } else if(mType =="Cat") { return (mWeight / 2.205) * (0.002/ 10); } } public double Carprofen() { if (mType == "Dog") { return (mWeight / 2.205) * (0.5 / 10); } else if (mType == "Cat") { return (mWeight / 2.205) * (0.25 / 10); } } } </code></pre>
<c#>
2019-11-30 06:05:35
LQ_CLOSE
59,113,807
Compilation on Linux - In function '_start': (.text+0x20): undefined reference to 'main'
<p>I want to compile a series of cpp files on Linux. Using CentOS 7, in the Konsole, I type "g++ -std=c++11 main.cpp canvas.cpp patch.cpp utils.cpp", and I get an error: </p> <pre><code>/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: error: ld returned 1 exit status </code></pre> <p>Could anyone tell me how to solve this?</p>
<c++><linux><c++11><compiler-errors><g++>
2019-11-30 06:31:48
LQ_CLOSE
59,114,632
Does my Java code for the Josephus problem work?
Here's some Java code I made for homework on the Josephus problem. I believe it doesn't work, but I want to make sure. If it's broken, I want to see if it can be fixed. If it can't be fixed because it is flawed by design, then please tell me so. Thank you. ``` public Int Josephus problem(int num4){ int reducer = 1; int c = 1; while (num4 > reducer+1){ num4 -= reducer; reducer += c++; } num4 = 1 + (num4-1)*2; return num4; } ``` I want to use this because it is for homework and so original work is worth more than better code. That's why I don't want to use the Bit shifting solution. I didn't think of it myself.
<java><optimization>
2019-11-30 08:51:59
LQ_EDIT
59,115,134
Removing duplicates and printing the string in specific output in python
Well, I tried my hardest to get it done! but i end up failing this at deleting duplicates at listing them. Can you guys tell me how to do this one or any clue? Here's the output I want to get: Please enter sentence: Hello Python! ' ' 1 '!' 1 'H' 1 'P' 1 'e' 1 'h' 1 'l' 2 'n' 1 'o' 2 't' 1 'y' 1 [' ', '!', 'H', 'P', 'e', 'h', 'l', 'n', 'o', 't', 'y'] This is the code I tried: from collections import OrderedDict def rmdup(str1): return "".join(OrderedDict.fromkeys(str1)) str = input('Please enter sentence: ') sorted-str = sorted(str) str1 = [] for i in range(len(str)): j = sorted-str.count(sorted-str[i]) str1 = list(rmdup(str1)) print('%r' % sorted-str + '\t' + '%r' % j) print(str1) and here's what the output I get: Please enter sentence: Hello Python! ' ' 1 '!' 1 'H' 1 'P' 1 'e' 1 'h' 1 'l' 2 'l' 2 'n' 1 'o' 2 'o' 2 't' 1 'y' 1 [' ', '!', 'H', 'P', 'e', 'h', 'l', 'n', 'o', 't', 'y']
<python><python-3.x><string><duplicates>
2019-11-30 10:14:10
LQ_EDIT
59,115,180
How do I get Parent with multiple children in desc order in sql server to show the newly created parent with its children at top in a List
[enter image description here][1] [1]: https://i.stack.imgur.com/SSmyN.png## ---------- I need to get in desc order as Parent1 with its children, parent2 with its children and so on.. ##
<sql><sql-server>
2019-11-30 10:20:40
LQ_EDIT
59,116,048
Java turn HTML codes into normal characters
<p>I am making a trivia game that pulls the questions from <a href="https://opentdb.com/" rel="nofollow noreferrer">https://opentdb.com/</a> but some of the questions and answers don't come out correct in java for example one of the questions looks like this:</p> <pre><code>What color is the &amp;amp;quot;Ex&amp;amp;quot; in FedEx Ground? </code></pre> <p>instaed of:</p> <pre><code>What color is the "Ex" in FedEx Ground? </code></pre> <p>any idea how to fix this in Java, thanks.</p>
<java>
2019-11-30 12:12:39
LQ_CLOSE
59,118,047
is there any package to extract particular keyword in python
I have comments like "the product name with ch12345 and tp12345 " there are so many comments like this. my query is to extract keywords starts with ch and tp followed by two or three-digit number.
<sql><python-3.x>
2019-11-30 16:24:15
LQ_EDIT
59,118,579
How to fix a strange error with List.Find()
public static string[] categoryNames = new string[] { "Control", "Supplies", "Power" }; int listSelected = categoryNames.Find(item => item == "Power"); Hello! For some reason, I get this error over 'Find': *There is no argument given that corresponds to the formal parameter 'match' of 'Array.Find<T>(T[], Predicate<T>)'* This confused me. I've looked through many examples, and can't figure out what I'm doing wrong with List.Find. Any feedback is appreciated. Thanks in advance!
<c#><list><find>
2019-11-30 17:32:47
LQ_EDIT
59,119,132
What is the moral of this?
<p>One great personality said once:</p> <p><strong>"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."</strong></p> <p>Is it true? What do you think the moral of this? </p>
<debugging><coding-style>
2019-11-30 18:40:17
LQ_CLOSE
59,119,822
What's the faster, most efficient way to toggle > 10000 checkboxes with Javascript/JQuery?
I have a `div` with more than 10000 checkboxes in it. ```html <div class="well well-sm" style="min-height: 100px; max-height: 360px; overflow: auto; background-color: #f7f7f7;"> <label> <input type="checkbox" class="checkbox-item" name="some_name" value="28" checked="checked"> Item 1 </label><br /> <!-- another 10000 of these --> </div> ``` and this JQuery code that activates when specific buttons are pressed. ```JavaScript $('.select-all').click(function () { $(this).parent().find(':checkbox:visible').prop('checked', true).change(); }); $('.unselect-all').click(function () { $(this).parent().find(':checkbox:visible').prop('checked', false).change(); }); $('.select-inverse').click(function () { $(this).parent().find(':checkbox:visible').click(); }); ``` (Ignore the `:visible` part as the list could be filtered) When the number of checkboxes is in the thousands the whole thing gets too slow, especially when ~10000 checkboxes need to be toggled. I was wondering if there's a faster (not necessarily better) way to toggle all of them at the same time (mostly for select/unselect all, as inverse selection can be removed altogether)
<javascript><jquery><html><dom><optimization>
2019-11-30 20:09:38
LQ_EDIT
59,120,071
Dictionary to list of strings pair
<p>I have the following dictionary: </p> <pre><code>{'PoP': 4, 'apple': 1, 'anTs': 2, 'poeT': 1} </code></pre> <p>And I wish to have a list of values like this:</p> <pre><code>['PoP, 4', 'apple, 1', 'anTs, 2', 'poeT,1'] </code></pre> <p>Which is like having a list of tuples but without the parentheses. Is there anyway to do this ?</p>
<python><list><dictionary>
2019-11-30 20:39:20
LQ_CLOSE
59,120,347
What is a flag in python while loops?
<p><strong><em>I am new to python and I came across this terminology-> flag in python while loops so can anyone explain what that is?</em></strong></p>
<python><python-3.x><while-loop>
2019-11-30 21:19:22
LQ_CLOSE
59,120,670
statement that executing code over and over
<p>I do not know how to do code that is executing over and over again. I would like to achieve something like this: (&lt; stands for input, > stands for output)</p> <pre><code>message=input() print('Write down the text.') </code></pre> <pre><code>&gt;Write down the text. &lt;qwerty &gt;qwerty &gt;Write down the text. &lt;asd &gt;asd </code></pre>
<python><if-statement>
2019-11-30 22:03:33
LQ_CLOSE
59,121,952
coverting arraylist to array in less than O(n)
<p>I am currently working on program and want to convert ArrayList to an array but in less than O(n) time.</p> <pre><code> for (int i = 0; i &lt; list.size(); i++) { if (list.get(i) != null) { arr[i] = list.get(i); } } </code></pre>
<algorithm><arraylist><data-structures>
2019-12-01 02:05:15
LQ_CLOSE
59,122,185
how many bytes is this struct? - how many bytes is pointer to a struct?
<pre><code>struct hello { size_t num; struct jump *next; } </code></pre> <p>I get that size_t is 4bytes but how many bytes is struct jump *next?</p>
<c>
2019-12-01 03:02:38
LQ_CLOSE
59,122,235
What does ** mean in Python?
<p>I have looked all over Ecosia and SO. I cannot find the answer to this question:</p> <p>What is <code>**</code> used for in Python?</p> <p>Like, <code>exampleVariable = 5 ** 5</code></p> <p>Thanks for any help!</p>
<python><python-3.x><math>
2019-12-01 03:16:43
LQ_CLOSE
59,123,399
What type of ML algorithm / model should I use for prediction?
<p>I apologize this might be a poorly asked question, Im looking for more of a point in the right direction to start research. </p> <p>So say I have large sets of Array data. Ill be easiest to give an example:</p> <pre><code>[{a: 1}, {h: 3}, {r:7}, {p: 2}] [{y: 4}, {p: 3}, {w: -3}, {u: 54}] [{l: -9}, {h: 5}, {r: 9}, {p: 5}] [{o: -5}, {f: 4}, {i: 0}, {t: 1}] [{a: 1}, {h: 2}, {r:5}, {p: 2}] </code></pre> <p>Okay so the keys of the objects doesn't really matter. What I want to be able to do is train a model on these objects by saying which list is 'good' and which list is 'bad'. From the example data above, if the 1st , 3rd, 5th list is 'good' and the 2nd and 4th are 'bad' I want the model to be able to identify that they all share the similar factors of h, r, p, that h, r, p are positive value (or negative or something of that form), and that they are in the same order in the list. so for example if I were to pass in <code>[{h: 2}, {a: 1}, {p: 2}, {r:5}]</code> as bad I would be able to separate it out as a different order. So basically I want to be able to identify what is most likely to results in a 'good' list be comparing similarities.</p>
<python><tensorflow><machine-learning>
2019-12-01 07:18:26
LQ_CLOSE
59,123,445
PHP Get last increment of five minutes
<p>I am looking to get the previous increment of five minutes from the current time...</p> <p>Lets say that the current time is 12:07pm UTC</p> <p>I want to put into a variable 12:05pm UTC</p> <p>What would be an easy way of going about this?</p>
<php>
2019-12-01 07:24:59
LQ_CLOSE
59,123,670
Why my groupby work says "invalid syntax"
<p><a href="https://i.stack.imgur.com/IsAy6.png" rel="nofollow noreferrer">groupby</a></p> <p>Hello, i try to find the mean of a data of groupby a dataframe. However, it shows my work has invalid syntax and please somebody help me.</p>
<python>
2019-12-01 08:01:52
LQ_CLOSE