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 |
|---|---|---|---|---|---|
54,304,811 | I can't find a way to input on the screen value of the words in Morse Alphabet | Don't be punish please me , I am just trying to create a output Morse Alphabet in java , but in my case , there are problems , when I input the letter , this coincide to my require , for example - A output ".-" .
There are two problems in my program , first , if I enter B and after D for example there is no output . Second problem , this is not work for words , when I entering word .
public class Example {
public static void main(String[] args) {
Map<String, String> map = createAlphabet();
Scanner in = new Scanner(System.in);
String s = in.nextLine();
for (Map.Entry<String , String> entry : map.entrySet()){
if (entry.getKey().equalsIgnoreCase(s)){
System.out.println(entry.getValue());
}
}
}
public static Map<String , String> createAlphabet() {
Map<String , String> alphabet = new HashMap<>();
alphabet.put("A" , ".-");
alphabet.put("B" , "-...");
alphabet.put("C" , "-.-");
alphabet.put("D" , "-..");
alphabet.put("E" , ".");
alphabet.put("F" , "..-.");
alphabet.put("G" , "--.");
alphabet.put("H" , "....");
alphabet.put("I" , "..");
alphabet.put("J" , ".---");
alphabet.put("K" , "-.-");
alphabet.put("L" , ".-..");
alphabet.put("M" , "--");
alphabet.put("N" , "-.");
alphabet.put("O" , "---");
alphabet.put("P" , ".--");
alphabet.put("Q" , "--.-");
alphabet.put("R" , ".-.");
alphabet.put("S" , "...");
alphabet.put("T" , "-");
alphabet.put("U" , "..-");
alphabet.put("V" , "...-");
alphabet.put("W" , ".--");
alphabet.put("X" , "-..-");
alphabet.put("Y" , "-.--");
alphabet.put("Z" , "--..");
return alphabet;
}
}
| <java><morse-code> | 2019-01-22 09:14:34 | LQ_EDIT |
54,305,373 | getting null value when parshing string value from json iOS swift | I am getting a json from my server. my server json is
[AnyHashable("smallIcon"): small_icon, AnyHashable("tickerText"): , AnyHashable("message"): {"action":"new_content_notification","msg":{"headline":"iOS REFERRAL BONUS","subhead":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","brief":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","content_id":44}}, AnyHashable("subtitle"): www.ezzyr.com, AnyHashable("sound"): 1, AnyHashable("gcm.message_id"): 0:id, AnyHashable("aps"): {
"content-available" = 1;
}, AnyHashable("title"): Notification from ezzyr, AnyHashable("vibrate"): 1, AnyHashable("largeIcon"): large_icon]
i am converting this by using swifty json. after converting swity json i am gettng this
let fullInfo = JSON(userInfo)
print(fullInfo)
{
"gcm.message_id" : "0: some number",
"subtitle" : "www.someName.com",
"smallIcon" : "small_icon",
"largeIcon" : "large_icon",
"title" : "Notification from ezzyr",
"vibrate" : "1",
"message" : "{\"action\":\"new_content_notification\",\"msg\":{\"headline\":\"iOS REFERRAL BONUS\",\"subhead\":\"Congratulations. You have unlocked another BDT500 discount on long route trip booking.\",\"brief\":\"Congratulations. You have unlocked another BDT500 discount on long route trip booking.\",\"content_id\":69}}",
"sound" : "1",
"tickerText" : "",
"aps" : {
"content-available" : "1"
}
}
i want only data what i have in my message key. so i try to get message key value this way
let message = fullInfo["message"]
print(message)
after printing message i am getting this result
{"action":"new_content_notification","msg":{"headline":"iOS REFERRAL BONUS","subhead":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","brief":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","content_id":94}}
Than i was try to get the key value of "action" in this way.
let action = message["action"]
print(action)
but this time i am getting null value.. How can i fix this issue and get string value and also the key value of msg
Thanks advanced for help
| <ios><json><swift> | 2019-01-22 09:46:11 | LQ_EDIT |
54,305,991 | why this PHP and SQL code with HTML ( drop-down) select item do nothing? | <p>I write this code to retrieve data from the database table and insert the data in "select" drop-down menu, the below code do nothing and the select list empty, the table contains records. I guess there is something wrong with the code. any help? </p>
<pre><code><select class = "input100" name="C_Number" placeholder=" Select Course Number">
<span class="focus-input100"></span>
<span class="symbol-input100">
<i class="fa fa-envelope-o" aria-hidden="true"></i>
<?php
$Query = "SELECT * FROM `courses`";
$CrPost = mysqli_query($db,$Query) Or die($Query);
$post = mysqli_fetch_array($CrPost,MSQL_ASSOC);
do { ?>
<option value="<?php echo $post['C_ID'];?>"><?php echo $post['C_Title']; ?></option>
<?php } while ($post = mysqli_fetch_array($rsPost,MSQL_ASSOC)); ?>
</span> </select>
</code></pre>
| <php><mysql> | 2019-01-22 10:18:14 | LQ_CLOSE |
54,306,241 | Are std::tuple and std::tuple<std::tuple> considered same type by std::vector? | <p>I have a variable defined like this</p>
<pre><code>auto drum = std::make_tuple
( std::make_tuple
( 0.3f
, ExampleClass
, [](ExampleClass& instance) {return instance.eGetter ();}
)
);
</code></pre>
<p>I expect <code>drum</code> to be a tuple of tuple. (i.e. <code>((a, b, c))</code>).</p>
<p>And I have another variable defined like this</p>
<pre><code>auto base = std::make_tuple
( 0.48f
, ExampleClass
, [](ExampleClass& instance) {return instance.eGetter ();}
);
</code></pre>
<p>which I expect to be just a tuple of three elements (i.e <code>(a, b, c)</code>)</p>
<p>I also have a vector defined as follows</p>
<pre><code>std::vector<std::tuple<std::tuple< float
, ExampleClass
, std::function<float (ExampleClass&)>
>>> listOfInstruments;
</code></pre>
<p>Now if I add <code>drum</code> to <code>listOfInstruments</code> I expect no errors.</p>
<p>Which was indeed the case with <code>listOfInstruments.push_back(drum);</code></p>
<p>Where I expected an error was here <code>listOfInstuments.push_back(base);</code> but the code compiles just fine.</p>
<p>Since <code>listOfInstruments</code> has type 'tuple of tuples', should't adding just 'tuple' cause some error? Unless both <code>()</code> and <code>(())</code> are considered same types by <code>std::vector</code>. Or am I completely wrong and there's something else at work here?</p>
<p>Can't seem to figure it out.</p>
| <c++><tuples> | 2019-01-22 10:30:07 | HQ |
54,306,861 | i have a question about to select the last line of the RichTextBox | <p>I have a Question to select the last line of the RichTextBox
When i click the Button1 it will show the last line in the Messagebox </p>
<p>I tried a lot of codes by it only select the index of the lines
i need your help</p>
<p>I want the output like </p>
<p>these are the lines i write in the RichTextBox</p>
<p>1.hello</p>
<p>2.world</p>
<p>3.welcome</p>
<p>when i click the button1 it will show the last line in messagebox</p>
<p>3.welcome // it will appears in the message box</p>
| <c#><vb.net> | 2019-01-22 11:02:54 | LQ_CLOSE |
54,306,866 | International phone number validation using regular expression | <p>I am validating international phone number which may have + or 0 leading with country code and space and phone number after space for this tried reglar expression with '\s' but it is failing.Why it is failing?
For eg. <code>+65 3333311</code></p>
<p>Tried with below regular expression
<code>^([0|\+[0-9]{1,6}[\s]?)?([0-9]{8,10})$</code></p>
| <regex><phone-number> | 2019-01-22 11:03:18 | LQ_CLOSE |
54,307,614 | How can I see the current version of packages installed by pipenv? | <p>I'm managing my Python dependencies with <a href="https://pipenv.readthedocs.io/en/latest/" rel="noreferrer">pipenv</a>. How can see the currently installed versions of packages?</p>
<p>I could examine <code>Pipfile.lock</code>, but is there a simpler way from the command line?</p>
| <python><pipenv> | 2019-01-22 11:46:10 | HQ |
54,310,701 | I keep getting errors for my restaurant code? (python) | So basically idk I just feel like my code is not really getting anywhere. I have trouble with the list and stuff, and I need this for school. My teacher doesn't really teach, and this is what they 'taught' us so far about list arrays, but I don't really understand it. Also, I keep getting this error of:
TypeError: append() takes exactly 2 arguments (1 given) on line 31
So basically? Just fix my entire code.
So my menu is alright, the printing turns out ok. I took out my whole menu here and just pasted where my problem occurs. Here's the part that actually works though:
```
print "[Welcome to Python Cafe!]"
print ('\n')
print "1) Menu and Order"
print "2) Exit"
choice=input("What would you like to do? ")
print ('\n')
if choice == "1":
print "-T H E M E N U-"
print " DRINKS "
print "1. Coffee: $2.50"
print "2. Hot Cocoa: $2.30"
print "3. Tea: $1.50"
print " FOOD "
print "4. Bagel: $1.50"
print "5. Donut: $1.00"
print "6. Muffin: $1.50"
```
The main problem is in the while statements and if statements, and how it
doesn't print my order in the end. I already tried changing like for example: if order == "coffee": to instead if order == "1": so I could make it easier so user doesn't have to type out the whole word? And also I tried taking out the tot=tot+... just to see. I have no idea, my teacher just told us to do that, but I don't think this format is quite right.
```
if choice == "1":
print ('\n')
food=[]
order=0
while order != "done":
order=input("What's your order? ")
if order == "coffee":
list.append("coffee")
tot=tot+2.50
else:
if order == "hot cocoa":
list.append("hotcocoa")
tot=tot+2.30
if order == "tea":
list.append("tea")
tot=tot+1.50
if order == "bagel":
list.append("bagel")
tot=tot+1.50
if order == "donut":
list.append("donut")
tot=tot+1.00
if order == "muffin":
list.append("muffin")
tot=tot+1.50
print ('\n')
print "Here's your final order:"
for item in food:
print(order)
```
And when the append() error doesn't appear, and the code actually 'works' when I change it back, it just ends there after 'done' and doesn't print anything after. I'm sorry if this seems really confusing, I just think this whole code is a mess.
pls send help. | <python><string><list><append> | 2019-01-22 14:43:29 | LQ_EDIT |
54,312,213 | Hashicorp Vault cli return 403 when trying to use kv | <p>I set up vault backed by a consul cluster. I secured it with https and am trying to use the cli on a separate machine to get and set secrets in the kv engine. I am using version 1.0.2 of both the CLI and Vault server.</p>
<p>I have logged in with the root token so I should have access to everything. I have also set my VAULT_ADDR appropriately.</p>
<p>Here is my request:</p>
<p><code>vault kv put secret/my-secret my-value=yea</code></p>
<p>Here is the response:</p>
<pre><code>Error making API request.
URL: GET https://{my-vault-address}/v1/sys/internal/ui/mounts/secret/my-secret
Code: 403. Errors:
* preflight capability check returned 403, please ensure client's policies grant access to path "secret/my-secret/"
</code></pre>
<p>I don't understand what is happening here. I am able to set and read secrets in the kv engine no problem from the vault ui. What am I missing?</p>
| <hashicorp-vault> | 2019-01-22 16:09:41 | HQ |
54,313,049 | App crash when using EditText [Android Studio] | I'm having a problem when trying to get data from "EditText" in Android Studio.
The app crashes immediately when I try to assign "EditText" value to a String variable (I used toString() method).
The problem is in the two lines after the onCreate method.
Here is my code:
public class MainActivity extends AppCompatActivity {
EditText em;
EditText pw;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText em = (EditText) findViewById(R.id.email1);
EditText pw = (EditText) findViewById(R.id.password1);
mAuth = FirebaseAuth.getInstance();
}
// When I remove those two lines the app runs normally
String email = em.getText().toString();
String password = pw.getText().toString();
void login(View v){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
String Logged = user.getEmail().toString();
Intent intent = new Intent(MainActivity.this, afterLogin.class);
intent.putExtra("email", Logged);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(MainActivity.this, "Wrong email/password.", Toast.LENGTH_SHORT).show();
}
}
});
}
} | <java><android> | 2019-01-22 16:58:48 | LQ_EDIT |
54,313,243 | How do you extract a value out of a golang map[string] string thats typed with interface{} | <p>I have something like this:</p>
<pre><code>x1 := someFunctionWithAnInterfaceReturnValue()
</code></pre>
<p>and the underlying type is something like this: </p>
<pre><code>x2 := map[string] string{"hello": "world"}
</code></pre>
<p>How would I access value in x1?</p>
<p>Essentially I want the equivalent of this for x1:</p>
<pre><code> var value string = x2["hello"]
</code></pre>
| <dictionary><go><types> | 2019-01-22 17:09:54 | LQ_CLOSE |
54,314,838 | GooglePlay - wrong signing key for app bundle | <p>I've just now started using app bundles. I've set the two certificates in the <code>App signing</code> section of the dashboard (signing certificate and upload certificate).</p>
<p>I've built an app bundle and signed it with the upload certificate, but when I upload the bundle under <code>Android Instant Apps</code> (which is in fact the reason I switched to app bundles) it says that:</p>
<p><code>Your Android App Bundle is signed with the wrong key. Ensure that your app bundle is signed with the correct signing key and try again: xx:xx:xx:xx.....</code></p>
<p>I've manually checked the SHA-1 of the upload keystore (using keytool in the terminal) and it matches the xx:xx:xx.... it says in the error message.</p>
<p>What am I doing wrong? The app bundle IS signed with the required upload certificate, but google play doesn't seem to like it.</p>
<p>Ideas?</p>
| <android><android-studio><google-play> | 2019-01-22 19:03:07 | HQ |
54,314,945 | Reactjs how to use ref inside map function? | <p>I'm mapping through an array and for each item display a button with text. Say I want that on clicking the button, the text underneath will change its color to red. How can I target the sibling of the button? I tried using ref but since it's a mapped jsx, only the last ref element will be declared.</p>
<p>Here is my code:</p>
<pre><code>class Exams extends React.Component {
constructor(props) {
super()
this.accordionContent = null;
}
state = {
examsNames: null, // fetched from a server
}
accordionToggle = () => {
this.accordionContent.style.color = 'red'
}
render() {
return (
<div className="container">
{this.state.examsNames && this.state.examsNames.map((inst, key) => (
<React.Fragment key={key}>
<button onClick={this.accordionToggle} className="inst-link"></button>
<div ref={accordionContent => this.accordionContent = accordionContent} className="accordionContent">
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aperiam, neque.</p>
</div>
</React.Fragment>
))}
</div>
)
}
}
export default Exams;
</code></pre>
<p>As explained, the outcome is that on each button click, the paragraph attached to the last button will be targeted.</p>
<p>Thanks in advance</p>
| <css><reactjs><ref> | 2019-01-22 19:11:47 | HQ |
54,315,004 | Why is "" necessary for this for loop to run? | <p>The code is below - </p>
<pre><code>for (let n = 1; n <= 100; n++) {
let output = "";
if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";
console.log(output || n);
}
</code></pre>
<p>If I do not have let output = "" the code will not run. Why is that statement required?</p>
| <javascript> | 2019-01-22 19:16:50 | LQ_CLOSE |
54,315,865 | BigQuery: Pageviews, Sessions, Users by differents sources, medium, campaigns | <p>What is the query for Pageviews, Sessions, Users by differents sources, medium, campaigns?</p>
| <google-bigquery> | 2019-01-22 20:18:27 | LQ_CLOSE |
54,315,988 | connectedRouter Error: Could not find router reducer in state tree, it must be mounted under "router" | <p>I am new to React.js and was setting up base project at that I was getting one issue that my routing got changed but component doesn't load. After googling I found that I need to use ConnectedRouter. While setting up ConnectedRouter, I am getting console error: <b>Could not find router reducer in state tree, it must be mounted under "router"</b></p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { ConnectedRouter, connectRouter, routerMiddleware } from "connected-react-router";
import { Provider } from "react-redux";
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import loginReducer from "./store/reducers/login";
import { watchLogin} from "./store/sagas";
import { history } from '../src/shared/history';
import { push } from 'react-router-redux';
import './index.css';
import App from './App';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({
login: loginReducer
});
const routersMiddleware = routerMiddleware(history)
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware, routersMiddleware];
const store = createStore(
connectRouter(history)(rootReducer),
{},
composeEnhancers(applyMiddleware(...middlewares))
);
sagaMiddleware.run(watchLogin);
const app = (
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>
);
ReactDOM.render(app, document.getElementById('root'));
</code></pre>
| <reactjs><react-redux><react-router> | 2019-01-22 20:29:12 | HQ |
54,316,624 | Python csv writer ugly format after change delimiter | I'm trying to change delimiter on csv and write to a new file, is just a simple modification but isn't it.
#!/usr/bin/python
#-*- econde: utf-8 -*-
import sys
import csv
def main():
r = open(sys.argv[1],"r")
wr = open(sys.argv[2],"a+")
rea = csv.reader(r, delimiter=',')
writer = csv.writer(wr,quotechar="'")
for row in rea:
line = str(row).replace(",","|")
writer.writerow("".join(line))
print type(line)
print line
print "".join(line)
r.close()
wr.close()
if __name__ == '__main__':
main()
The output in console looks ugly like:
[ , ' , 0 , 9 , / , 1 , 0 , / , 2 , 0 , 1 , 6 , , 2 , 2 , : , 0 , 0 , : , 0 , 4 , ' , | , , ' , a , n , y , ' , | , , ' , w , w , w , 4 , . , z , w , r , . , g , o , o , g , l , e , e , . , o , r , g , 3 , ' , | , , " , P , r , e , v , i , o , u , s , , M , D , 5 , : , , ' , c , 5 , d , 8 , 3 , 6 , 8 , 1 , 5 , b , 2 , 3 , b , 1 , d , f , 5 , e , e , 5 , 2 , 7 , 8 , 5 , 6 , 4 , 1 , b , 7 , b , 4 , 2 , ' , ; , , C , u , r , r , e , n , t , , M , D , 5 , : , , ' , d , e , 7 , e , a , f , 8 , 2 , 8 , c , 6 , 1 , d , 0 , 5 , 8 , 4 , 9 , 4 , e , d , 6 , d , 3 , d , b , d , 8 , 4 , c , 6 , 9 , ' , ; , , P , r , e , v , i , o , u , s , , S , H , A , 1 , : , , ' , d , c , 1 , 6 , d , 1 , 4 , 4 , 1 , b , a , d , a , d , 2 , 0 , d , a , 0 , d , 3 , d , 9 , 0 , e , 9 , a , b , 7 , a , 4 , 3 , 7 , 2 , 1 , 7 , 8 , 0 , 4 , 5 , ' , ; , , C , u , r , r , e , n , t , , S , H , A , 1 , : , , ' , c , 4 , d , f , 0 , 6 , 5 , 5 , 0 , d , 3 , 6 , 5 , 9 , 9 , 1 , 3 , b , 1 , e , 0 , 1 , 0 , e , c , 6 , 1 , 8 , 6 , 2 , e , 8 , 8 , e , 7 , c , 5 , 9 , 3 , d , ' , ; , , I , n , t , e , g , r , i , t , y , , c , h , e , c , k , s , u , m , , c , h , a , n , g , e , d , , f , o , r , : , , ' , / , M , Y , F , i , l , e , s , _ , t , e , s , t , . , j , s , ' , " , ]
and is worst written to the file because each character is written per field and the file looks ugly
| <python><csv> | 2019-01-22 21:22:14 | LQ_EDIT |
54,316,754 | Combine data from multiple rows | <p>I have the following data in a sql server table:</p>
<hr>
<p><a href="https://i.stack.imgur.com/wgGQH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wgGQH.png" alt="enter image description here"></a></p>
<p>What I need is to combine these rows based on Bulletin_Number and Speed between the mile posts. I need the following output: </p>
<p><a href="https://i.stack.imgur.com/GW6zC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GW6zC.png" alt="enter image description here"></a></p>
<p>How can I do this in SQL Server?</p>
| <sql><sql-server> | 2019-01-22 21:32:39 | LQ_CLOSE |
54,316,898 | C# Task.Result is Null | <p>I have following method which will eventually return some <code>Task<IList<DataModel>></code> but for now just returns <code>null</code>. I want to load result of this list to ObservableCollection in my ViewModel which is then displayed in a ListView.</p>
<p>But for now, I just want to return null and check that that is handled properly, so my ListView should show nothing in it as a result. I simmulate that by this code:</p>
<pre><code>public async Task<IList<DatatModel>> GetData(string id)
{
return await Task.FromResult<IList<DataModel>>(null);
}
</code></pre>
<p>I call the code above and will loop through result of my Task and load it all in my ObservableCollection like so:</p>
<pre><code>public void Initialize()
{
foreach (var data in GetData(Id).Result)
{
MyObservableCollection.Add(data);
}
}
</code></pre>
<p>However, my app just freezes. I think that above call to GetData(id).Result is problem because Result is null. How do I loop through this data and load it into my ObservableCollection if some data exist, or simply dont load anything if there is no data returned?</p>
| <c#><task> | 2019-01-22 21:44:51 | LQ_CLOSE |
54,317,000 | Are there any sealed classes alternatives in Dart 2.0? | <p>I have Android development background and I'm learning Flutter.</p>
<p>In Android it's a common practice to use Kotlin sealed classes to return a state from ViewModel e.g.</p>
<pre><code>sealed class MyState {
data class Success(val data: List<MyObject>) : MyState()
data class Error(val error: String) : MyState()
}
</code></pre>
<p>I want to use similar patter in Flutter and return a State object from the BLOC class. What is the best way to achieve the same in Flutter?</p>
| <dart><flutter> | 2019-01-22 21:52:49 | HQ |
54,317,470 | How to return server not found for domain but allow sub directory to show normally | <p>Most all are typically find a way to "not" show can't connect to server browser errors, where is I'm interested in showing it.</p>
<p>I have a domain example.com for a YOURLS link shortener. The homepage shows a 403 Forbidden Nginx notice. The example.com/admin shows the working admin site. This will not be publicly facing and if someone goes to example.com should show can't connect to server, so people do not know that site exists (yes, they can do a whois or dns lookup but not worried about that).</p>
<p>I could change the nginx server root to be a random location and it would show the desired error but then example.com/admin wouldn't work. Is there any easy fix? In the nginx config there is a line: <code>try_files $uri $uri/ /yourls-loader.php$is_args$args;</code></p>
<p>Is there a change I can make there to stop example.com from showing anything but allow example.com/admin to still work? Also yes, I could put a blank index.html but that would show a white page where is looking to show the standard browser error you see if you enter a domain that doesn't have a website.</p>
<p>There maybe a name for this, but not sure how to describe it thus have beemn unable to find a solution to this presumably easy problem.</p>
| <ubuntu><nginx><ubuntu-18.04> | 2019-01-22 22:37:00 | LQ_CLOSE |
54,317,488 | How do you declare a object that can be accessed through multiple header files? | <p>I'm working on a project and I am cleaning my code and Re-doing the code so it's more readable and easy to tweak. I'm having one issue though when I create an object in a header file the complier throws me an error saying its already defined; int assumed. LNK-2005. </p>
<p>I tried creating the objects as 'extern' so I could access the objects from all files that include the file with the specified objects.</p>
<pre><code>// HeaderA.h
#include <Windows.h>
struct ProcessInfo
{
int ProcID;
HANDLE Handle;
};
</code></pre>
<p>This is header B below</p>
<pre><code>// Header B starts here
// HeaderB.h
#include "HeaderA.h"
{
ProcessInfo pi;
pi.ProcID = 10;
struct Player
{
int health = 0;
float x, y, z;
int score = 0;
}
}
</code></pre>
<p>Header C
This file should be able to use Header B's object 'pi'</p>
<pre><code>//HeaderC.h
#include "HeaderB.h"
// creating object from headerB
Player player;
// is there a way so I can use the object declared in HeaderB in HeaderC?
// like so
pi.ProcID = 45;
</code></pre>
<p>I expected to be able to use the object created in header B through multiple files like HeaderB-HeaderZ. (A-Z; Multiple Headers) But when compiling I get the error "LNK2005 already defined".</p>
| <c++><header> | 2019-01-22 22:38:41 | LQ_CLOSE |
54,317,727 | How do you adb to bluestacks 4? | <p>I'd like to connect to android emulator on bluestacks 4 with adb.
but I've got an error with <code>adb.exe -s emulator-5554 shell</code></p>
<p>checking devices. </p>
<pre><code>$ adb.exe devices
List of devices attached
BH901... device
CB512... unauthorized
emulator-5554 device
</code></pre>
<p>once I shutdown bluestacks window, the <code>emulator-5554</code> will be hidden from above command's result. thus I think <code>emulator-5554</code> means bluestacks.</p>
<p>then commnad as below to use adb.</p>
<pre><code>$ adb.exe -s emulator-5554 shell
error: closed
</code></pre>
<p>but as you know, an error occured.</p>
| <android><adb><bluestacks> | 2019-01-22 23:03:35 | HQ |
54,318,105 | How to implement a single item for a linked list class? C++ homework | I'm extremely new to C++, so I wanted to get some help on a homework problem that I've been working on for the past few hours. The criteria of the problem is this:
In the problems below, we will be implementing a list of "items." In this problem, we will create an Item class for this purpose.
To make things a little interesting, we will have two components to our Item: (1) an integer key and (2) a literal string value.
Your class must include:
[2.5 pts] Private member variables for the key (int) and value (const char *). Don't allocate space for the string -- just keep a pointer.
[2.5 pts] A public constructor that initializes the key and value. Again, don't copy the string that is passed in -- just save the pointer.
[2.5 pts] Public methods to read the key and value -- e.g., getKey(), getValue().
[2.5 pts] A public copy constructor.
I'm extremely confused on how to implement the third and the fourth bullet point. I'll attach my code below, if any of you guys could tell me what I'm doing wrong or how I go about implementing these parts that would be awesome. The reason I'm confused is because I'm not exactly sure what they are designed to do.
class Item {
Private:
int key;
const char* point;
Public:
Item(int key, char* point); //I'm not sure when to put brackets after a constructor? The examples given are usually pretty vague.
getKey(key); //What do these do? We never went over these in class? What is the point?
getValue(point);
Item(const Item &new) {
key = new.key;
value = new.imaginary;
}
};
Like I said, I am very, very new to C++, so any pointers would be helpful. Thank you so much!
| <c++><class> | 2019-01-22 23:50:13 | LQ_EDIT |
54,318,485 | Dynamic import named export using Webpack | <p>Using webpack, if I want to code-split an entire module, I can change</p>
<p><code>import Module from 'module'</code></p>
<p>at the top of my file to</p>
<p><code>import('module').then(Module => {...</code></p>
<p>when I need to use the module (<a href="https://webpack.js.org/api/module-methods/#import-" rel="noreferrer">docs</a>). Is it possible to do this but with just a single named export? That is, how could I code-split the following:</p>
<p><code>import {namedExport} from 'module'</code></p>
| <javascript><webpack><code-splitting> | 2019-01-23 00:44:05 | HQ |
54,319,292 | How to sort after removing'goto'statements, making it easier for people to understand? | How to sort after removing'goto'statements, making it easier for people to understand
[how to format your messy code in the left side to be like the right side in the picture][1]
//**this code
defined('IN_IA') or exit('Access Denied');
class Md_daojiaModuleSite extends WeModuleSite
{
public function doPageUploadmap3()
{
goto A25dm;
ADcuT:
ZLMND:
goto wJ44l;
z_M2Z:
if (empty($_FILES["file"]["tmp_name"])) {
goto ZLMND;
}
goto RnW8Z;
M61ng:
$tempfile = ATTACHMENT_ROOT . "/audios/" . $name;
goto ReGaV;
A25dm:
global $_GPC, $_W;
goto z_M2Z;
RnW8Z:
$exname = strtolower(substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], ".") + 1));
goto BO3TT;
wJ44l:
return $this->result(0, '', "attachment/audios/" . $name);
goto Qx8PP;
BO3TT:
$name = md5(time()) . "." . $exname;
goto M61ng;
ReGaV:
move_uploaded_file($_FILES["file"]["tmp_name"], $tempfile);
goto ADcuT;
Qx8PP:
}
}
[1]: https://i.stack.imgur.com/9Sxot.png
| <php><goto> | 2019-01-23 02:40:45 | LQ_EDIT |
54,321,476 | How to range array in golang to not randomize predetermined key? | <p>I have a trouble with my current golang's project.</p>
<p>I have another package in go that result an array with pretedermined key, example :</p>
<pre><code>package updaters
var CustomSql map[string]string
func InitSqlUpdater() {
CustomSql = map[string]string{
"ShouldBeFirst": "Text Should Be First",
"ShouldBeSecond": "Text Should Be Second",
"ShouldBeThird": "Text Should Be Third",
"ShouldBeFourth": "Text Should Be Fourth"
}
}
</code></pre>
<p>And send it to main.go, to iterate each index and value, but the results is random (In my situation, I need that in sequence).</p>
<p>Real Case : <a href="https://play.golang.org/p/ONXEiAj-Q4v" rel="nofollow noreferrer">https://play.golang.org/p/ONXEiAj-Q4v</a></p>
<p>I google why the golangs iterate in random way, and the example is using sort, but my array keys is predetermined, and sort is only for asc desc alphabet and number.</p>
<p>So, How can I achieve the way that arrays is not being randomize in iterate?</p>
<pre><code>ShouldBeFirst = Text Should Be First
ShouldBeSecond = Text Should Be Second
ShouldBeThird = Text Should Be Third
ShouldBeFourth = Text Should Be Fourth
</code></pre>
<p>Anyhelp will appreciate, thanks.</p>
| <go><beego> | 2019-01-23 06:50:22 | LQ_CLOSE |
54,321,521 | How do You write a code for Unit Testing winform keypress and Button Events | private void Phonenumber_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!char.IsDigit(ch) && (ch != 8))
{
e.Handled = true;
}
}private void Submit_Click(object sender, EventArgs e)
{
//sql commands
messagebox.show("data added successfully");
} | <c#><.net><winforms><unit-testing> | 2019-01-23 06:53:48 | LQ_EDIT |
54,321,572 | Hosting multiple domains on single webapp folder in tomcat | <p>Possible duplicate of <a href="https://stackoverflow.com/questions/16763938/multiple-domains-to-single-webapp-in-tomcat">this</a> but answer is not accepted.</p>
<p>I have 2 scenarios</p>
<ol>
<li>We are building a CRM and we will be having multiple clients using same product. Lets take a example, <code>subdomain1.maindomain1.com</code> and <code>anysubmain.anothermaindomain.com</code> should be pointed to same webapp folder. And depending on domain, we will select database dynamically but codebase will remain same. <strong><em>Point to note here : Whole codebase remains same</em></strong>.</li>
<li>We are building series of website for a client where part of the codebase will remain same for all but depending on subdomain we will load the default servlet file. Lets take example, <code>manage.domain.com</code> <code>crm.domain.com</code> <code>equote.domain.com</code> should be pointing to same webapp folder. And depending on domain we will load default servlet file. <strong><em>Point to note here : Part of codebase will remain same for all domains. Ex. core architect files</em></strong>.</li>
</ol>
<p>What solutions other have suggested</p>
<ol>
<li><a href="https://stackoverflow.com/a/16764089/1056620">Deploy copy of same war file 2 time, Softlink, Create 2 contexts that point to the same file, Use alias</a>. Last one can be good option but no idea how we can use this for different subdomains / domains.</li>
<li><a href="https://stackoverflow.com/a/49726750/1056620">This can be one of the solution but not sure whether it will work on same port or different port </a></li>
<li>There are many articles over internet which shows how we can deploy multiple webapps on multiple domain on single tomcat server but not the way i need.</li>
</ol>
<p>Note: I can create 2 AWS EC2 instances for above 2 scenarios. It means that I am not expecting one solution to above 2 problems.</p>
| <java><tomcat> | 2019-01-23 06:57:36 | HQ |
54,322,885 | Put circle top div position center | <p>I need to replicate this.
What is the best way to add a cirle like this image with css? </p>
<p>thanks <a href="https://i.stack.imgur.com/ZLFie.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZLFie.png" alt="enter image description here"></a></p>
| <html><css> | 2019-01-23 08:27:58 | LQ_CLOSE |
54,324,620 | Why is dplyr so slow? | <p>Like most people, I'm impressed by Hadley Wickham and what he's done for <code>R</code> -- so i figured that i'd move some functions toward his <code>tidyverse</code> ... having done so i'm left wondering what the point of it all is? </p>
<p>My new <code>dplyr</code> functions are <strong>much slower</strong> than their base equivalents -- i hope i'm doing something wrong. I'd particularly like some payoff from the effort required to understand <code>non-standard-evaluation</code>.</p>
<p>So, what am i doing wrong? Why is <code>dplyr</code> so slow?</p>
<p>An example: </p>
<pre><code>require(microbenchmark)
require(dplyr)
df <- tibble(
a = 1:10,
b = c(1:5, 4:0),
c = 10:1)
addSpread_base <- function() {
df[['spread']] <- df[['a']] - df[['b']]
df
}
addSpread_dplyr <- function() df %>% mutate(spread := a - b)
all.equal(addSpread_base(), addSpread_dplyr())
microbenchmark(addSpread_base(), addSpread_dplyr(), times = 1e4)
</code></pre>
<p>Timing results: </p>
<pre><code>Unit: microseconds
expr min lq mean median uq max neval
addSpread_base() 12.058 15.769 22.07805 24.58 26.435 2003.481 10000
addSpread_dplyr() 607.537 624.697 666.08964 631.19 636.291 41143.691 10000
</code></pre>
<p>So using <code>dplyr</code> functions to transform the data takes about 30x longer -- surely this isn't the intention? </p>
<p>I figured that perhaps this is too easy a case -- and that <code>dplyr</code> would really shine if we had a more realistic case where we are adding a column and sub-setting the data -- but this was worse. As you can see from the timings below, this is ~70x slower than the base approach. </p>
<pre><code># mutate and substitute
addSpreadSub_base <- function(df, col1, col2) {
df[['spread']] <- df[['a']] - df[['b']]
df[, c(col1, col2, 'spread')]
}
addSpreadSub_dplyr <- function(df, col1, col2) {
var1 <- as.name(col1)
var2 <- as.name(col2)
qq <- quo(!!var1 - !!var2)
df %>%
mutate(spread := !!qq) %>%
select(!!var1, !!var2, spread)
}
all.equal(addSpreadSub_base(df, col1 = 'a', col2 = 'b'),
addSpreadSub_dplyr(df, col1 = 'a', col2 = 'b'))
microbenchmark(addSpreadSub_base(df, col1 = 'a', col2 = 'b'),
addSpreadSub_dplyr(df, col1 = 'a', col2 = 'b'),
times = 1e4)
</code></pre>
<p>Results: </p>
<pre><code>Unit: microseconds
expr min lq mean median uq max neval
addSpreadSub_base(df, col1 = "a", col2 = "b") 22.725 30.610 44.3874 45.450 53.798 2024.35 10000
addSpreadSub_dplyr(df, col1 = "a", col2 = "b") 2748.757 2837.337 3011.1982 2859.598 2904.583 44207.81 10000
</code></pre>
| <r><performance><dplyr> | 2019-01-23 10:03:48 | HQ |
54,324,967 | how to access first two digits of a number | I want to access first two digits of a number, and i have used sub string/sub str/slice none of them is working its throwing error like sub string is not defined
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
....
}
i have tried above code
output of(above code)
trial123=19.0.0.1
i need only 19.0
how can i achieve this?
| <javascript><string><reactjs> | 2019-01-23 10:21:03 | LQ_EDIT |
54,324,981 | How can i use GroupBy and than Map over Dataset | i'm working with datasets and trying to groupby and than use map.
i am managing to do it with RDD's but with dataset after groupby i dont have to option to use map.
there is a way i can do it?
| <scala><apache-spark><apache-spark-dataset> | 2019-01-23 10:21:55 | LQ_EDIT |
54,325,717 | When using insert statement using array is giving error | Sqlserv php eoor when inserting using array oprtion
ARRAY PREPRATION
foreach ($data as $rs) {
$params []="({$rs->hd},'{$rs->dvn}',{$rs->mth},{$rs->yr},{$rs->stid},{$rs->prcd},'{$rs->prnm}',{$rs->prte},{$rs->ssl},{$rs->clsk},1)";
}
INSERT INTO STATEMENT:
$SqlInsert="insert into SQl_test (Ss_Hq_cd,Ss_division,Ss_month,Ss_yr,Ss_stk_Id,Ss_prod_cod,Ss_prod_name,ss_prod_rate,Ss_Sale,Ss_Cl_stk,ss_tran_stat) values(?,?,?,?,?,?,?,?,?,?,?) ";
$stmt = sqlsrv_query( $conn, $SqlInsert,$params);
EROOR:
Error in statement preparation\/execution.\n"Array ( [0] => Array ( [0] => 22018 [SQLSTATE] => 22018 [1] => 245 [code] => 245 [2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '(757,'MAIN',12,2018,100899,1250,'xyz',0,100,45,1)' to data type int. [message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '(757,'MAIN',12,2018,100899,1250,'xyz',0,100,45,1)' to data type int. ) ) | <php><loops><prepared-statement><sql-insert><sqlsrv> | 2019-01-23 11:01:09 | LQ_EDIT |
54,328,666 | Flutter PageView - Show preview of page on left and right | <p>I am trying to create a pagiewView in flutter that shows preview of the next page and the a preview of the next page as is in the attached image. How can I achieve that?<a href="https://i.stack.imgur.com/qRaLO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qRaLO.jpg" alt="enter image description here"></a></p>
| <dart><flutter> | 2019-01-23 13:42:26 | HQ |
54,329,404 | How to find multiples of 3 and 5, push to an array, and then sum the array in Ruby | I am trying to sum the multiples of 3 and 5 that are less than 1000 using an .each do command, and then a .push to store them all in my array 'multiples'. However, when I try to do this, I get an error message. I am trying to learn how to use these commands and so don't want to use the .select and .inject I've been seeing everywhere.
I have controllers set up to print @your_output on another page, and have done this successfully with other, simpler problems. However, when I try to do the conditional and store it in div, I get an error.
def third_program
numbers = (1..999).to_a
# Your code goes below.
multiples = []
numbers.each do |num|
div = num % 3 == 0 || num % 5 == 0
multiples.push(div)
end
@your_output = div.sum
render("programs_templates/third_program.html.erb")
end
| <ruby> | 2019-01-23 14:24:46 | LQ_EDIT |
54,329,551 | In angularjs Make http service in synchronous way using promises | When i hit the url on particular page of the application i want to check whether the page is allow to load or not using the api call, if it is allowed then allow to load that page else redirect to different page
| <angularjs> | 2019-01-23 14:32:23 | LQ_EDIT |
54,330,926 | Is it valid to "hide" a base class virtual function by making it pure virtual in derived classes? | <p>Consider the example:</p>
<pre><code>#include <iostream>
class A {
public:
virtual void f();
};
void A::f()
{
std::cout << "f() from A\n";
}
class B: public A {
public:
virtual void f() = 0;
};
class C: public B {
public:
void f();
};
void C::f()
{
std::cout << "f() from C\n";
}
int main()
{
C o;
o.f();
}
</code></pre>
<p><code>A::f()</code> implementation is "hidden" from class C, which provides its own implementation for <code>f()</code> - effectively making <code>A::f()</code> more or less pointless. I see little value in such class hierarchy design, but my question whether this is a valid C++ or just "works" (such as undefined behaviours)?</p>
| <c++><c++11><language-lawyer> | 2019-01-23 15:47:48 | HQ |
54,331,018 | Merging two list to create a third one in python | Let say I have the following:
{u'result': {u'status': True, u'queried': 3, u'value': [{u'username': u'firstuser', u'userid': u'1'}, {u'username': u'seconduser', u'userid': u'2'}, {u'username': u'thirduser', u'userid': u'3'}]}
and this one:
{u'result': {u'status': True, u'queried': 2, u'value': [{u'username': u'firstuser', u'userid': u'101'}, {u'username': u'seconduser', u'userid': u'102'}]}
How can I obtain a third one like this:
{u'result': {u'status': True, u'queried': 3, u'value': [{u'username': u'firstuser', u'userid_one': u'1', u'userid_two': u'101'}, {u'username': u'seconduser', u'userid_one': u'2', u'userid_two': u'102'}, {u'username': u'thirduser', u'userid_one': u'3', u'userid_two': u''}]} | <python><list><dictionary> | 2019-01-23 15:53:10 | LQ_EDIT |
54,332,832 | How to create custom type in angular | <p>Can some one explain how to create our own custom types in angular using typescript syntax. Please provide example as well.
Thanks!</p>
| <javascript><angular><typescript> | 2019-01-23 17:41:30 | LQ_CLOSE |
54,333,164 | How can it search inside the directory, if the directory is empty? | I just started learning python and found this snippet. It's supposed to count how many times a word appears. I guess, for all of you this will seem very logical, but unfortunately for me, it doesn't make any sense.
str = "house is where you live, you don't leave the house."
`dict = {}`
`list = str.split(" ")`
`for word in list:` # Loop over the list
`if word in dict:` # How can I loop over the dictionary if it's empty?
`dict[word] = dict[word] + 1`
`else:`
`dict[word] = 1`
So, my question here is, how can I loop over the dictionary? Shouldn't the dictionary be empty because I didn't pass anything inside?
Maybe I am not smart enough, but I don't see the logic. Can anybody explain me how does it work?
Many thanks | <python><python-3.x><dictionary><for-loop> | 2019-01-23 18:05:14 | LQ_EDIT |
54,333,930 | Using wild cards with find and ls | <p>The find command doesn't seem to search recursively when using the * wild card</p>
<p>I have a directory with several sub-directories inside it, many of which contain pdf's. There are no actual pdf's in the main directory, just in the sub-directories within it. I want to find all the pdf's without having to open all the directories.</p>
<pre><code>find *.pdf
</code></pre>
<p>Shouldn't my code return all the pdfs in the sub-directories? I get 'No match'. Am I using the wild card correctly? I've also tried it like </p>
<p>*pdf</p>
<p>*.pdf*</p>
<p>*'.pdf'* </p>
<p>with no luck. Same results with ls. What am I not understanding?</p>
| <linux><unix><tcsh> | 2019-01-23 18:56:38 | LQ_CLOSE |
54,334,017 | Could any one help me with grep | I'm new to shell script and i am assigned to grab files that only contains ascii text.
I found this code online but just dont get it.
```
grep '[^ -~]' $someargument
```
could anyone help me with it? Thanks!
I found this has the same functionality as
```
grep -P -L -r '[^[:ascii:]]' $someargument
| <bash><shell> | 2019-01-23 19:01:53 | LQ_EDIT |
54,334,304 | spacy Can't find model 'en_core_web_sm' on windows 10 and Python 3.5.3 :: Anaconda custom (64-bit) | <p>what is difference between <code>spacy.load('en_core_web_sm')</code> and <code>spacy.load('en')</code>? <a href="https://stackoverflow.com/questions/50487495/what-is-difference-between-en-core-web-sm-en-core-web-mdand-en-core-web-lg-mod">This link</a> explains different model sizes. But i am still not clear how <code>spacy.load('en_core_web_sm')</code> and <code>spacy.load('en')</code> differ</p>
<p><code>spacy.load('en')</code> runs fine for me. But the <code>spacy.load('en_core_web_sm')</code> throws error</p>
<p>i have installed <code>spacy</code>as below. when i go to jupyter notebook and run command <code>nlp = spacy.load('en_core_web_sm')</code> I get the below error </p>
<pre><code>---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-4-b472bef03043> in <module>()
1 # Import spaCy and load the language library
2 import spacy
----> 3 nlp = spacy.load('en_core_web_sm')
4
5 # Create a Doc object
C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\__init__.py in load(name, **overrides)
13 if depr_path not in (True, False, None):
14 deprecation_warning(Warnings.W001.format(path=depr_path))
---> 15 return util.load_model(name, **overrides)
16
17
C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\util.py in load_model(name, **overrides)
117 elif hasattr(name, 'exists'): # Path or Path-like to model data
118 return load_model_from_path(name, **overrides)
--> 119 raise IOError(Errors.E050.format(name=name))
120
121
OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory.
</code></pre>
<p>how I installed Spacy ---</p>
<pre><code>(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>conda install -c conda-forge spacy
Fetching package metadata .............
Solving package specifications: .
Package plan for installation in environment C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder:
The following NEW packages will be INSTALLED:
blas: 1.0-mkl
cymem: 1.31.2-py35h6538335_0 conda-forge
dill: 0.2.8.2-py35_0 conda-forge
msgpack-numpy: 0.4.4.2-py_0 conda-forge
murmurhash: 0.28.0-py35h6538335_1000 conda-forge
plac: 0.9.6-py_1 conda-forge
preshed: 1.0.0-py35h6538335_0 conda-forge
pyreadline: 2.1-py35_1000 conda-forge
regex: 2017.11.09-py35_0 conda-forge
spacy: 2.0.12-py35h830ac7b_0 conda-forge
termcolor: 1.1.0-py_2 conda-forge
thinc: 6.10.3-py35h830ac7b_2 conda-forge
tqdm: 4.29.1-py_0 conda-forge
ujson: 1.35-py35hfa6e2cd_1001 conda-forge
The following packages will be UPDATED:
msgpack-python: 0.4.8-py35_0 --> 0.5.6-py35he980bc4_3 conda-forge
The following packages will be DOWNGRADED:
freetype: 2.7-vc14_2 conda-forge --> 2.5.5-vc14_2
Proceed ([y]/n)? y
blas-1.0-mkl.t 100% |###############################| Time: 0:00:00 0.00 B/s
cymem-1.31.2-p 100% |###############################| Time: 0:00:00 1.65 MB/s
msgpack-python 100% |###############################| Time: 0:00:00 5.37 MB/s
murmurhash-0.2 100% |###############################| Time: 0:00:00 1.49 MB/s
plac-0.9.6-py_ 100% |###############################| Time: 0:00:00 0.00 B/s
pyreadline-2.1 100% |###############################| Time: 0:00:00 4.62 MB/s
regex-2017.11. 100% |###############################| Time: 0:00:00 3.31 MB/s
termcolor-1.1. 100% |###############################| Time: 0:00:00 187.81 kB/s
tqdm-4.29.1-py 100% |###############################| Time: 0:00:00 2.51 MB/s
ujson-1.35-py3 100% |###############################| Time: 0:00:00 1.66 MB/s
dill-0.2.8.2-p 100% |###############################| Time: 0:00:00 4.34 MB/s
msgpack-numpy- 100% |###############################| Time: 0:00:00 0.00 B/s
preshed-1.0.0- 100% |###############################| Time: 0:00:00 0.00 B/s
thinc-6.10.3-p 100% |###############################| Time: 0:00:00 5.49 MB/s
spacy-2.0.12-p 100% |###############################| Time: 0:00:10 7.42 MB/s
(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>python -V
Python 3.5.3 :: Anaconda custom (64-bit)
(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>python -m spacy download en
Collecting en_core_web_sm==2.0.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz#egg=en_core_web_sm==2.0.0
Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz (37.4MB)
100% |################################| 37.4MB ...
Installing collected packages: en-core-web-sm
Running setup.py install for en-core-web-sm ... done
Successfully installed en-core-web-sm-2.0.0
Linking successful
C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\en_core_web_sm
-->
C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder\lib\site-packages\spacy\data\en
You can now load the model via spacy.load('en')
(C:\Users\nikhizzz\AppData\Local\conda\conda\envs\tensorflowspyder) C:\Users\nikhizzz>
</code></pre>
| <python-3.x><spacy> | 2019-01-23 19:24:21 | HQ |
54,337,172 | How two flask app accessing same database | <p>I am going to build two flask REST API accessing same database.
Both 2 app have access to same table. For example I have Order table. Should i create OrderModel class on both of that 2 app or just one of them?</p>
<p>Thanks.</p>
| <python><rest><flask><sqlalchemy><flask-sqlalchemy> | 2019-01-23 23:17:20 | LQ_CLOSE |
54,337,280 | my program is working corectly but I get a warning | guys.
I have allocated memory for a double pointer and I have populated it with some values.(1)
After that I created a function that populates the ints with 0
Than I have made a pointer to that function and crated another function that uses that pointer as an argument
I ran the program and it was working
But the problem was that I was getting a warning
"passing argument 1 of 'cheama_transforma0' makes pointer from integer without a cast"
This is my code:
#include <stdio.h>
#include <stdlib.h>
void printeaza_pointer(int **cacat){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf("%d\n",cacat[i][j]);
}
putchar('\n');
}
}
int transforma_in0(int **cacat){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cacat[i][j] = 0;
}
}
return 0;
}
void cheama_transforma0(int (*p)(int **pointer)){
}
int main()
{
int (*p)(int **cacat);
int **pointer_d = (int **)malloc(sizeof(int*)*3);
for(int i = 0; i < 3; i++){
pointer_d[i] = (int *)malloc(sizeof(int)*3);
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
pointer_d[i][j] = 1;
}
}
p = transforma_in0;
printeaza_pointer(pointer_d);
cheama_transforma0(p(pointer_d));
printeaza_pointer(pointer_d);
return 0;
}
| <c><function-pointers> | 2019-01-23 23:29:32 | LQ_EDIT |
54,337,605 | How do I incorporate a for-loop into this function and still have the same outcomes? | <p>I have written this code for a class and the outcomes are correct, but I did not realize that I needed to incorporate a for-loop into the function. The exact words from the problem are "Hint, use a variable number of arguments (*values) and access them with a for loop." I don't really understand this and I think all I need to do is add a for loop somehow. </p>
<p>I haven't tried anything yet because i'm really bad with for-loops and don't want to mess up the code that I have. Anything helps. This is my code so far:</p>
<pre><code>def values(num1 , num2 , num3):
sum = num1 + num2 + num 3
ave = sum / 3
x = max (num1 , num2 , num3)
y = min (num1 , num2 , num3)
product = num1 * num2 * num3
return sum , ave , x , y , product
sum , ave , x , y , product = values(2 , 2 , 2)
print(sum)
print(ave)
print(x)
print(y)
print(product)
6
2.0
2
2
8
</code></pre>
| <python><python-3.x><function><for-loop> | 2019-01-24 00:15:03 | LQ_CLOSE |
54,339,931 | I have stored few items in the form of multidimensional arrays in userdata and want to access them.Well new to CI please help me out | Code below is basically what i did in actual. here lets say i want to access : array at index 3 and 4th element of that same array
<?php
$data = array( array('1','2','3'),
'4', '5',
array('abc', 'klm','xyz'),
array('1', '2', '88908', '3', '4')
);
$this->session->set_userdata('data', $data);
print_r($this->session->userdata('data["5"]["4"]'));
?>
i want to access only 88908
| <codeigniter> | 2019-01-24 05:33:38 | LQ_EDIT |
54,341,245 | Accessing global variable value in python | <pre><code>def definition():
global storage_account_connection_string
storage_account_connection_string="test"
def load_config():
config = ConfigParser.ConfigParser()
config.readfp(open(r'config.txt'))
temp = config.get('API_Metrics','SCC')
temp1 = temp.split("#")
for conf in temp1:
confTemp=conf.split(":")
print "#########################################"
print confTemp[0]
print confTemp[1]
print confTemp[2]
storage_account_connection_string=confTemp[2]
print storage_account_connection_string
get_details()
def get_details():
print storage_account_connection_string
print "Blob",blob_name_filter
if __name__ == '__main_`enter code here`_':
definition()
load_config()`enter code here`
</code></pre>
<p>My question is why connection string always prints "test" in get_details(), though it is assigned with some value in load_config(), AM I missing something? </p>
| <python><global-variables> | 2019-01-24 07:19:00 | LQ_CLOSE |
54,341,499 | is there something wrong in this code written in java? | the actual answer is supposed to be "stack" and "overflow" in two separate lines for input "stack.overflow".delimiter used is ".".
nothing is shown in the output
Scanner p=new Scanner(System.in);
p.useDelimiter(".");
System.out.println("delimiter is "+ p.delimiter());
\\this above line is producing expected output
while(p.hasNext()){
System.out.println(p.next());
}
for input stack.overflow and delimiter "."
expected output is stack
overflow
| <java><java.util.scanner><delimiter> | 2019-01-24 07:36:56 | LQ_EDIT |
54,341,796 | adding column filters to Angular collapsible material table with | I am using angular material table with collapsible feature. now i need to add column filters to my headers. can you help me to do it.
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
data format (console.log(this.dataSource.data))
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/JnAFb.png | <javascript><angular> | 2019-01-24 07:57:06 | LQ_EDIT |
54,342,954 | How to find a cyclical python script on Ubuntu server | <p>I have a problem with the python script on the Ubuntu server. Scripts are performed every night. How can I find them? I mean their location.
Crontab - empty
crontab.d, .daily, .weekly - empty
init.d - empty
I have root access</p>
| <python><linux><ubuntu><server><cron> | 2019-01-24 09:11:38 | LQ_CLOSE |
54,343,496 | I want that when I select a city of a state, then all the detials of that city are visible | <p>I want that when I select a city of a state, then all the detials of that city are not visible. how to visible it on select city.</p>
<p>I want that when I select a city of a state, then all the detials of that city are visible.</p>
| <javascript><html><json> | 2019-01-24 09:40:48 | LQ_CLOSE |
54,344,101 | Why does my google colab session keep crashing? | <p>I am using google colab on a dataset with 4 million rows and 29 columns. When I run the statement sns.heatmap(dataset.isnull()) it runs for some time but after a while the session crashes and the instance restarts. It has been happening a lot and I till now haven't really seen an output. What can be the possible reason ? Is the data/calculation too much ? What can I do ?</p>
| <python><data-visualization><google-colaboratory> | 2019-01-24 10:11:40 | HQ |
54,344,565 | Why is self a required parameter for a method? | <p>Let's say that I have a tiny code like this:</p>
<pre><code>#!/usr/bin/env python3
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name + " is now sitting.")
my_dog = Dog('willie',6)
my_dog.sit()
</code></pre>
<p>As I understand, the line <code>my_dog = Dog('willie',6)</code> creates an instance named <code>my_dog</code>. It calls the <code>__init__</code> function, converts it internally to <code>Dog.__init__(my_dog, willie, 6)</code> and sets the <code>my_dog.name</code> and <code>my_dog.age</code> variables to <code>willie</code> and <code>6</code>? Now when the <code>my_dog.sit()</code> is executed, then why does the method <code>sit()</code> require a <code>self</code> as a parameter? Is it because if there is another instance of the same class(for example, <code>your_dog</code>), then it knows to use <code>your_dog.name</code> instead of <code>my_dog.name</code>?</p>
| <python> | 2019-01-24 10:33:58 | LQ_CLOSE |
54,344,958 | How to multiply multiple column dataframe to another single column df in Python? | I'm trying to multiply two dataframes:(3868 rows x 758 columns) and (3868 rows x 1 column)
Below codes give me error:operands could not be broadcast together with shapes (14961424,) (3868,)
free_float = pd.DataFrame(free_float)
weights = pd.DataFrame(weights )
columns = weights.columns
weights[columns] *= free_float['A']
| <python><pandas><dataframe><multiplying> | 2019-01-24 10:54:08 | LQ_EDIT |
54,346,709 | How to print results from for loop in one list | <p>Below code is for loop to print many lists</p>
<pre><code>for file in dir:
res = p.Probability(base + i + "/" + file)
print(i + ": " + ": " + str(res))
print(res)
#docum = []
#docum.append(res)
print(docum)
</code></pre>
<p>for loop result will be:</p>
<pre><code>[['hello',123]['hi',456]]
[['hello',123]['hi',456]]
[['hello',123]['hi',456]]
[['hello',123]['hi',456]]
[['hello',123]['hi',456]]
</code></pre>
<p>but I want to print as a one list</p>
<pre><code>[['hello',123]['hi',456],['hello',123]['hi',456],['hello',123]['hi',456]]
</code></pre>
<p>how can I do that. I tried many things but still not working. I am new to python. and one more help how to separate hi and hello.
like: </p>
<pre><code> hi hello
456 123
456 123
456 123
</code></pre>
<p>I am doing school project for my class 11th. I struck in this and I am new to coding</p>
| <python><python-3.x><list> | 2019-01-24 12:29:13 | LQ_CLOSE |
54,348,064 | discord.js message not defined (nodejs How to fix this issue what i have) | Before i ask this question i checked into simlar overflow questions and could not find an answer to my question.
So this is what i want to do.
I get live data from a telnet connection, i get the data live in the console window.
In a line in my code i added read.match("MYDATA")
So if it gets my data it needs to send it into a discord message.. but i cant implement the message.channel.send in it, because i need the main variable.. how can i solve it ?
const port = "11000";
const host = "192.168.1.12";
var socket = net.createConnection(port, host);
console.log('Socket created.');
socket.on('data', function(data) , message{
// Log the response from the HTTP server.
console.log('' + data);
var read = data.toString();
if (read.match("DC,4043,100,0")) {
console.log ("Connected to "); //<--- this shows up fine in the log
message.channel.send('enabled'); //<---- can't send to channel
}
}).on('connect', function() {
// Manually write an HTTP request.
socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
console.log('DONE');
});
| <javascript><node.js><discord.js> | 2019-01-24 13:43:13 | LQ_EDIT |
54,350,295 | how to use class name after getting class name from event.target in jaquery? | i've this code on html
<div id="readMorediv_id">
<button class="readMorebtn_id">Read More</button>
<div class="afterReadMore_Class" style="display: none !important;">
<div >
<span><b>User CNIC:</b></span><span><?php $row['usercnic']?></span>
</div>
<div>
<span><b>Father CNIC:</b></span><span><?php echo$row['fathercnic']?>
</span>
</div>
</div>
</div>
and this is my jquery code
$(".readMorebtn_id").on('click', function( e )
{
var icon = e.target;
var parentDiv = $(icon).parent();
var child = $(parentDiv).children(".afterReadMore_Class");
var cls = $(child).attr('class');
console.log(cls);
});
in jquery, where i'm doing "console.log(cls)" class name is displaying in console box. but i want to use this class name for further process. anyone help me
| <jquery><html> | 2019-01-24 15:39:02 | LQ_EDIT |
54,350,991 | React-navigation: Deep linking with authentication | <p>I am building a mobile app with react-native and the react-navigation library for managing the navigation in my app. Right now, my app looks something like that:</p>
<pre><code>App [SwitchNavigator]
Splash [Screen]
Auth [Screen]
MainApp [StackNavigator]
Home [Screen] (/home)
Profile [Screen] (/profile)
Notifications [Screen] (/notifications)
</code></pre>
<p>I have integrated Deep Linking with the patterns above for the screens <code>Home</code>, <code>Profile</code> and <code>Notifications</code>, and it works as expected. The issue I am facing is how to manage my user's authentication when using a deep link. Right now whenever I open a deep link (<code>myapp://profile</code> for instance) the app takes me on the screen whether or not I am authenticated. What I would want it to do is to check before in <code>AsyncStorage</code> if there is a <code>userToken</code> and if there isn't or it is not valid anymore then just redirect on the <code>Auth</code> screen.</p>
<p>I set up the authentication flow in almost exactly the same way as described <a href="https://reactnavigation.org/docs/en/auth-flow.html" rel="noreferrer">here</a>. So when my application starts the <code>Splash</code> screen checks in the user's phone if there is a valid token and sends him either on the <code>Auth</code> screen or <code>Home</code> screen.</p>
<p>The only solution I have come up with for now is to direct every deep link to <code>Splash</code>, authentify my user, and then parse the link to navigate to the good screen.
So for example when a user opens <code>myapp://profile</code>, I open the app on <code>Splash</code>, validate the token, then parse the url (<code>/profile</code>), and finally redirect either to <code>Auth</code> or <code>Profile</code>.</p>
<p>Is that the good way to do so, or does react-navigation provide a better way to do this ? The <a href="https://reactnavigation.org/docs/en/deep-linking.html" rel="noreferrer">Deep linking</a> page on their website is a little light.</p>
<p>Thanks for the help !</p>
| <react-native><react-navigation><deep-linking> | 2019-01-24 16:15:46 | HQ |
54,351,631 | How to remove div in cross site div? | <p>I have an iframe youtube video, where i want to remove an div element.
I can do it in in the console as long I manually folded out the div which I am looking for, but otherwise i am not able to find it using <code>document.getElementByClassName()</code>..</p>
<p>Is it possible via js to somehow remove an div which resides inside #document?</p>
| <javascript><postmessage><cross-site> | 2019-01-24 16:49:35 | LQ_CLOSE |
54,352,937 | How can i read a csv based on data in other columns? | <p>Heres my example csv:</p>
<pre><code>col1: col2: col3:
1 true false
2 true true
3 false false
4 false true
5 true true
</code></pre>
<p>i want to be able to say 'give me col1 if col2 is true and col3 is false'
Any help is appreciated</p>
| <python><csv> | 2019-01-24 18:09:04 | LQ_CLOSE |
54,353,130 | How to "cd" between directories using a python script | <p>I'm writing a test script that is supposed to cd from the current directory into a new one if that path is confirmed to exist and be a directory</p>
<pre><code>serial_number = input("Enter serial number: ")
directory = "/etc/bin/foo"
if os.path.exists(directory) and os.path.isdir(directory):
#cd into directory?
subprocess.call(['cd ..' + directory])
</code></pre>
<p>My dilemma is that I don't know how to properly pass a variable into a subprocess command, or whether or not I should use call or Popen. When I try the above code, it comes back with an error saying that <code>No such file or directory "cd ../etc/bin/"</code>. I need is to travel back one directory from the current directory so then I can enter <code>/etc</code> and read some files in there. Any advice?</p>
| <python><linux><python-3.x><subprocess> | 2019-01-24 18:22:28 | LQ_CLOSE |
54,353,665 | Haskell, How many elements from one list are present in the other list | I am new to functional programming using Haskell and I can't seem to be able to create a function that takes two lists as arguments and returns how many elements there are common in both lists.
e.g. f [1, 2, 4, 2] [2, 3, 4, 4] returning 2 (repetitions are ignored).
Any suggestions? | <function><haskell><recursion><functional-programming> | 2019-01-24 19:02:31 | LQ_EDIT |
54,355,722 | UNIQID alternative | <p>I'm looking to generate a UNIQUE random code.</p>
<p>When you use uniqid(), result is based on time, example:
if user created ID yesterday at 12:12:35 and another user create a new ID today at same time, ID are identical because based on 24 hour loop time.</p>
<p>I'm tinking about using microtime in this way</p>
<pre><code>// create random based on unix epoch
$random = round(microtime(true) * 1000);
</code></pre>
<p>In this way can I grant uniqueless of generated IDs?</p>
| <php> | 2019-01-24 21:40:37 | LQ_CLOSE |
54,356,709 | Replace period character (".") from an entire data.table column in R | <p>I am trying to remove all the period characters (<code>.</code>) from a data.table using <code>gsub</code>. Unfortunately, it isn't working. How do you propperly express the pattern to describe the periods to then replace them by nothing?</p>
<p>My code:</p>
<pre><code>dt[, Address := gsub(".", "", Address)]
</code></pre>
<p>Result:</p>
<pre><code>head(dt$Address)
[1] "" "" "" "" "" ""
</code></pre>
<p>I'm guessing that when <code>pattern = "."</code> R thinks I'm refering to the entire content of the object in question. What am I doing wrong?</p>
| <r><gsub> | 2019-01-24 23:09:04 | LQ_CLOSE |
54,357,468 | How to set build and version number of Flutter app | <p>How do you set the version name and version code of a Flutter app without having to go into the Android and iOS settings?</p>
<p>In my pubspec.yaml I have</p>
<pre><code>version: 2.0.0
</code></pre>
<p>but I don't see a place for the build number.</p>
| <flutter><version> | 2019-01-25 00:39:13 | HQ |
54,358,506 | How to average all columns in dataset by group | <p>I'm using aggregate in R to try and summarize my dataset. I currently have 3-5 observation per ID and I need to average these so that I have 1 value (the mean) per ID. Some columns are returning all "NA" when I use aggregate. </p>
<p>So far, I've created a vector for each column to average it, then tried to use merge to combine all of them. Some columns are characters, so I tried converting them to numbers using as.numeric(as.character(column)), but that returns too many NA in the column. </p>
<pre><code>library(dplyr)
Tr1 <- data %>% group_by(ID) %>% summarise(mean = mean(Tr1))
Tr2 <- data %>% group_by(ID) %>% summarise(mean = mean(Tr2))
Tr3 <- data %>% group_by(ID) %>% summarise(mean = mean(Tr3))
data2 <- merge(Tr1,Tr2,Tr3, by = ID)
</code></pre>
<p>From this code I get error codes: </p>
<pre><code>There were 50 or more warnings (use warnings() to see the first 50)
</code></pre>
<p>then,</p>
<pre><code>Error in fix.by(by.x, x) :
'by' must specify one or more columns as numbers, names or logical
</code></pre>
<p>My original dataset looks like:</p>
<pre><code>ID Tr1 Tr2 Tr3
1 4 5 6
1 5 3 9
1 3 5 9
4 5 1 8
4 2 6 4
6 2 8 6
6 2 7 4
6 7 1 9
</code></pre>
<p>and I am trying to find a code so that it looks like:</p>
<pre><code>ID Tr1 Tr2 Tr3
1 4 4.3 8
4 3.5 3.5 6
6 3.7 5.3 6.3
</code></pre>
| <r><dataset><aggregate><mean><summarize> | 2019-01-25 03:18:48 | LQ_CLOSE |
54,359,732 | Is it possible Nlog not to write the same message | <p>I want to see something like that:</p>
<p>error1<br>
50 times: error2<br>
error3<br>
10 times: error2<br></p>
<p>Is it possible?</p>
| <c#><logging><nlog> | 2019-01-25 06:01:30 | LQ_CLOSE |
54,360,813 | Ubuntu 18.04 - firewall | <p>Can someone tell me which firewall is better to use for ubuntu 18.04? On previus version I used firestarter. Maybe is alternativ firewall? Firewall must have function for sharing the internet.</p>
<p>Best regards,
Jure</p>
| <ubuntu><firewall> | 2019-01-25 07:33:04 | LQ_CLOSE |
54,361,821 | Possible bug with Bcrypt implementation on Spring | <p>I'm testing to move our password hash from sha-256 to sha-512 or bcrypt. For that, I've implemented a very simple test, but I've found out that with a specific rawPassword when Bcrypt tries to match it against the same rawPassword + anything else, it fails, returning true instead of false. Maybe it is related to the encoding, but I'm not sure.</p>
<pre class="lang-java prettyprint-override"><code>...
@Test
public void testEncodePassword() {
final String rawPassword = "¡Oh envidia, raíz de infinitos males y carcoma de las virtudes!";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(rawPassword);
assertTrue(passwordEncoder.matches(rawPassword,encodedPassword));
assertFalse(passwordEncoder.matches("dds",encodedPassword));
assertFalse(passwordEncoder.matches("dds"+rawPassword,encodedPassword));
assertFalse(passwordEncoder.matches(rawPassword+"something else",encodedPassword));
}
...
</code></pre>
| <java><spring-security><bcrypt> | 2019-01-25 08:52:58 | LQ_CLOSE |
54,363,101 | str' object has no attribute 'get' attribute | How can I solve it...
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Mani\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "F:\Monu\Work\python\PROJECT\New folder\LMS.py", line 262, in onDoubalclick
cursor.execute("SELECT * FROM `TRANSECTION` WHERE Book_Id=?",(val1.get(),))
AttributeError: 'str' object has no attribute 'get'
I already convert it in string or integer but not working
def onDoubalclick(event):
test=treeview.item(treeview.selection())
print(test)
items=treeview.selection()[0]
val1=str(treeview.item(items)['values'][0])
print(type(val1))
popsearch()
DataBase()
cursor.execute("SELECT * FROM `TRANSECTION` WHERE Book_Id=?",(val1.get(),))
info=cursor.fetchall()
for ROW1 in info:
print(rows)
treeview2.insert("",END,value=ROW1)
I want to get a value that stores in val1 and search that value in the database
| <python><python-3.x> | 2019-01-25 10:11:45 | LQ_EDIT |
54,363,678 | how to use variable(value) anywhere in function in javascript |
Below there if part of my javascript function. In that function, i am trying to use mathematical formula:
if(m == 1){
var intAmt = amt * (Math.pow((1 + rate / (12*100)), 12*period)) - amt;
var notPaid = Math.round(parseInt(amt) + intAmt,2);
}else if(status === "Not Paid"){
//dueAmt is tobe taken from below
var intAmt = dueAmt * (Math.pow((1 + rate / (12*100)), 12*period)) -dueAmt;
var notPaid = parseInt(dueAmt) + parseInt(amt) + intAmt;
}
//dueAmt is passed to the formula again n again
var dueAmt = notPaid;
the above part of code is javascript function is in for loop
I need to use the dueAmt variable again in if loop.But in else part of the loop it gives me undefined. | <javascript> | 2019-01-25 10:44:48 | LQ_EDIT |
54,364,181 | json won`t get parsed with variables out of an array | I don´t understand why my json doesn´t get parsed. I hope someone could explain this to me. I try to send a json from php to javascript.
**This code works fine:**
From PHP
echo json_encode(array($row['jobunique'], $row['jobtitle']));
to JAVASCRIPT
success: function(getjoblist) {
var getjobdetails = $.parseJSON(getjoblist);
}
**But this code gives me an error back:**
From PHP - data comes out of an array
echo json_encode(array($data[2], $data[3]));
I thought, maybe it's an object and I need to make a string out of the variables like this:
echo json_encode(array(strval($data[2]), strval($data[3])));
But it did not work either.
Here is the JAVASCRIPT code:
success: function(callback) {
var namearray = $.parseJSON(callback);
}
**Here is the error from the console:**
Uncaught SyntaxError: Unexpected token in JSON at position 0
| <javascript><php><arrays><json> | 2019-01-25 11:13:24 | LQ_EDIT |
54,364,732 | Python - How to decompile python script? | <p>I have a script and i think its compiled with something like <code>Cpython</code>.
I can run this script, but i want to access to source code.
Is there any way to do this? </p>
<p>Thanks</p>
| <python><cython><cpython> | 2019-01-25 11:47:12 | LQ_CLOSE |
54,364,917 | Not able to comment, android developers please read! WebView display | since i don't have the 50 rep required to comment -.- stupid idea...
This is my first app development so please bare with me on this ^^.
ill simply have to ask this question here again, it's topic related to this: https://stackoverflow.com/questions/14423981/android-webview-display-only-some-part-of-website/14424866#14424866
and it's about this code that is written there:
public class MyWebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:your javascript");
}
}
.........
final MyWebClient myWebViewClient = new MyWebClient();
mWebView.setWebViewClient(myWebViewClient);
Im having difficulties running this code even after modified like this:
public class MyWebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl("http://tid.mspot.nu");
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("document.getElementsByClassName('white').style.visibility = 'hidden'");
}
}
final MyWebClient myWebViewClient = new MyWebClient();
mWebView.setWebViewClient(myWebViewClient);
> error: class, interface, or enum expected
> error: class, interface, or enum expected
Since im not a java developer this gets a bit confused (mainly working with PHP) and some parts im totally familiar with.
Here is my currently working code:
import android.annotation.TargetApi;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.getSettings().setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();// super.onReceivedSslError(view, handler, error);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
webView.loadUrl("http://tid.mspot.nu");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
and i would love to be able to implement that feature of hiding this "btn_white" class i know it's supposed to be an id which ill change right now. This is just a button to download the app that i wan't to hide in the app, makes sense i suppose ^^
would love to have some help with this since it's my first time developing anything for android. Thanks!
| <java><android><android-webview> | 2019-01-25 11:58:10 | LQ_EDIT |
54,367,852 | How would I go about generating a number from a range, and making it so that each possibility in the range has a different probability? | <p>I want to figure out how to generate a number from a range, where each item in the range has a different probability of it being generated.</p>
<p>For instance, I want the chances to be:</p>
<pre><code>p=c(.1,.2,.3,.35, .02, .03)
</code></pre>
<p>For a range of 1-6.</p>
<p>I believe I need to use cumsum, but I'm not sure how to go about it.</p>
| <r> | 2019-01-25 15:02:40 | LQ_CLOSE |
54,368,529 | How to split or tokenize an array of strings by a space " " delimiter to find the second word in each string in C | I have an array that holds a bunch of strings. I want to find the second word in each of the strings that are contained in this array so I can sort the sentences alphabetically by the second word in the sentence. I tried using strtok but it doesn't work for tokenizing an array of strings. The delimiter is just the space between each word. I have to do this in c
| <c><string><sorting><parsing> | 2019-01-25 15:41:40 | LQ_EDIT |
54,371,152 | How i can get Data from Wordpress plugin in json, like if a plugin showing data on wordpress , i want also get json and use in android | i upload a plugin on wordpress and all set it is working fine and fetching data, but same data i have to use in android as web service, How can this happen. is it possible?
i download plugin and search url's from where plugin getting data but not found.
i have download plugin but not understanding.
| <php><json><wordpress> | 2019-01-25 18:43:09 | LQ_EDIT |
54,371,312 | How to prevent an instance of a class from being created when the condition is true. C# | <p>I have the class Pos:</p>
<pre><code>public class Pos
{
int x;
int y;
public int X
{
get
{
return x;
}
set
{
try
{
if (value == 3)
{
x = value;
}
}
catch
{
throw new ArgumentException();
}
}
}
public int Y { get; set; }
public Pos(int x, int y)
{
X = x;
Y = y;
}
}
</code></pre>
<p>I have an instance created, with X = 0. That is, as far as I understand, in the case of value = 3 -> x = 0 and in the constructor X = 0, then create an instance of the class.
How do I prevent an instance of a class from being created when the x property setter fails?
I will create a List that should not contain "wrong" objects.</p>
| <c#><c#-4.0> | 2019-01-25 18:55:57 | LQ_CLOSE |
54,372,422 | How do I check whether a scanned integer is indeed an integer? | <p>I'm pretty new to Java, I program in C# which is very similar, but I have some troubles defending my code in java.</p>
<p>I'd like to defend my code against illegal input such as string,char,special char.</p>
<p>I want every time an input other than int to STAY in the do-while loop(exact place marked with ?????????)</p>
<p>Here is my code, pretty simple, it takes numbers and calculates the minimum number,maximum, avg,sum.
If the number -1 is entered, either the program won't start or the loop would stop and calculation will be printed.</p>
<p>Thanks in advance for your help!</p>
<pre><code>public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Variables
int count=0;
int sum=0;
int max=0;
int min=0;
//Initializing minimum value for a reference
System.out.print("Enter a number ");
int number = scan.nextInt();
if(number!=-1){
min=number;
count++;
sum+=number;
}
while(number!=-1){
do {
System.out.print("Enter a number or -1 to stop: ");
number = scan.nextInt();
}while((Integer.toString(number)==null)||???????????? (Check for illegal input));
if(number==-1){
break;
}
else {
sum+=number;
count++;
if(number>max) {
max=number;
}
else if(number<min) {
min=number;
}
}
}
if(count!=0)
{
System.out.println("The Maximum number is: "+max);
System.out.println("The Minimum number is: "+min);
System.out.println("The Sum of all entered numbers is: "+sum);
System.out.println("The Average of all entered numbers is: "+(double)sum/(double)count);
System.out.println("T H E E N D");
}
else {
System.out.println("T H E E N D");
}
scan.close();
}
</code></pre>
<p>}</p>
| <java> | 2019-01-25 20:37:07 | LQ_CLOSE |
54,373,983 | c# pass method into parameter for logging | <p>I am implementing simple logging, and I would like to do something like below</p>
<pre><code>public int SomeMethod(int x)
{
Log(SomeMethod,"here is a log entry);
}
</code></pre>
<p>In the Log method, I would like to parse out the class name from the method and print to the log file the method name and class name.</p>
<p>Is it possible to do something that would look as simple as above or something similar?</p>
| <c#><.net> | 2019-01-25 23:08:11 | LQ_CLOSE |
54,374,501 | How do I find a shell script that accepts one or more arguments, and outputs a line for each argument that names an ASCII file? | I understand that I have to use an array of arguments, but have no experience doing so. I am using Emacs for my shell scripting.
This is what I have so far:
#!/bin/bash
find $@ -type f -exec file {} + | grep ASCII
| <linux><bash><shell> | 2019-01-26 00:19:17 | LQ_EDIT |
54,377,477 | Return input value inside a function | <p>I need help if someone types a wrong input it should return the question again in python3.</p>
<p>I tried to return the variable.</p>
<pre><code>def main():
this = input ('Is this your ..? (Yes/No)')
if this != 'Yes' and this != 'No':
print ('please provide a valid answer')
</code></pre>
<p>I want to ask the question again and again until the answer will be Yes or No.</p>
| <python><function><variables><input> | 2019-01-26 10:23:36 | LQ_CLOSE |
54,377,679 | Why do I get "Error: Could not find or load main class" for any java code? | <p>Any java code I compile and try to execute from CMD line results in the error: <br>
<strong>Error: Could not find or load main class</strong></p>
<p>I have tried setting environment variables:<br>
PATH=C:\Program Files\Java\jdk1.8.0_202\bin<br>
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_202</p>
<p>and with and with out:<br>
CLASSPATH=C:\Program Files\Java\jdk1.8.0_202\jre\lib or<br>
CLASSPATH=C:\Program Files\Java\jdk1.8.0_202\jre\lib\rt.jar or<br>
CLASSPATH=(directory of code)</p>
<p>The following is an example of a simple test prog that will not run:</p>
<pre><code>/**
* Experiment with println() and print()
*/
public class HelloGoodbye
{
public static void main(String[] args)
{
System.out.println("My First Hello!");
System.out.println("Hello again!");
System.out.print("Hello finally!");
System.out.print("Goodbye!");
}
}
</code></pre>
<p>This produces:
Error: Could not find or load main class</p>
| <java> | 2019-01-26 10:52:27 | LQ_CLOSE |
54,379,595 | How to fix "NullPointerException" in viewmodel.setText? | <p>I'm trying to pass the user information from MainActivity to one of the fragments in my NavigationHeader and i keep getting a NullPointerException everytime i try to setText in the Fragment.</p>
<p>I tried using the Bundle and Interface approach before trying ViewModel. Also getActivity() warns me that it's null.</p>
<pre><code>public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
//NavHeader
private TextView header_name, header_email;
//SessionManager
SessionManager sessionManager;
//maps
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final String FINELOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSELOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private Boolean mLocationPermissionsGranted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
private FusedLocationProviderClient mFusedLocationProviderClient;
private GoogleMap mMap;
String pontopartida, pontochegada;
private EditText ponto_partidaInput, ponto_chegadaInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//GET USER DATA
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
header_name = (TextView) headerView.findViewById(R.id.header_name);
header_email = (TextView) headerView.findViewById(R.id.header_email);
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.NAME);
String mEmail = user.get(sessionManager.EMAIL);
header_name.setText(mName);
header_email.setText(mEmail);
//Navigation Drawer
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_myaccount:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MyAccountFragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SettingsFragment()).commit();
break;
case R.id.nav_logout:
sessionManager.logout();
break;
case R.id.nav_share:
Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
</code></pre>
<p>and MyAccountFragment</p>
<pre><code>
public class MyAccountFragment extends Fragment {
private SharedViewModel viewModel;
private EditText account_name;
private EditText account_email;
protected FragmentActivity mActivity;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_myaccount, container, false);
account_name = (EditText) view.findViewById(R.id.name_accountfrag);
account_email = (EditText) view.findViewById(R.id.email_accountfrag);
viewModel.setText(account_name.getText().toString());
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
viewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
account_name.setText(s);
}
});
}
}
</code></pre>
<p>Also here is my error log</p>
<pre><code>
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tiago.teleperformance, PID: 9236
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.tiago.teleperformance.SharedViewModel.setText(java.lang.String)' on a null object reference
at com.example.tiago.teleperformance.MyAccountFragment.onCreateView(MyAccountFragment.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code></pre>
<p>I was expecting it to update the information in the Fragment with the same Name and Email in the MainActivity as soon as i opened it. Instead it crashes. Can anyone help me?</p>
| <android><null><fragment><viewmodel><settext> | 2019-01-26 15:03:17 | LQ_CLOSE |
54,380,680 | Importing a module in haskell makes the code not compile | <p>I wrote the following haskell code for test. It compiles fine with <code>ghc</code> (version 8.0.2), and prints 20, as expected.</p>
<pre class="lang-hs prettyprint-override"><code>f x = x * 2
main = print $ f 10
</code></pre>
<p>But when I import <code>Char</code> module like this:</p>
<pre class="lang-hs prettyprint-override"><code>module Data.Char
f x = x * 2
main = print $ f 10
</code></pre>
<p>it gives me this error: <code>test.hs:3:1: error: parse error on input ‘f’</code>.</p>
<p>Does haskell change the environment when a module is imported? What is the difference and am I importing the module wrong?</p>
| <haskell> | 2019-01-26 17:10:10 | LQ_CLOSE |
54,380,949 | Index was outside the bounds of the array c# so confusing | Hello Ladies And Gentlemen goodevening to all, may i ask ? how can i get error for this ? it is so confusing i get bug like this i try to fix it many hours but not work at all sorry for being noob coding im just newbie
namespace WindowsFormsApp1
{
public partial class Schedule : Form
{
public Schedule()
{
InitializeComponent();
}
MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=Payroll;User Id=root;password=''");
MySqlDataReader dr;
int tc = 0;
private void Schedule_Load(object sender, EventArgs e)
{
datagrid();
fillsched();
}
public void datagrid()
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter("Select * from employee where Pstatus='Active'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
con.Close();
}
public void fillsched()
{
con.Open();
MySqlDataReader dr;
MySqlCommand cmd = new MySqlCommand("select * from updateschedule ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
int data = dr.GetInt32("empSched");
comboBox1.Items.Add(data);
}
con.Close();
}
public void getsched()
{
if (Int32.TryParse(comboBox1.SelectedItem.ToString(), out tc))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from updateschedule where empSched=@empSched ", con);
cmd.Parameters.Add("@empSched", MySqlDbType.Int32).Value = tc;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr["TimeIn"].ToString();
textBox3.Text = dr["TimeOut"].ToString();
label5.Text = tc.ToString();//to pass the data in the combobox1
}
con.Close();
}
}
public void view()
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
getsched();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
view();
}
}
private void button1_Click(object sender, EventArgs e)
{
insert();
insertempsched();
}
public void insert()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule (empSchedID,empID,empIN,empOut)VALUES(@empSchedID,@empID,@empIn,@EmpOut)", con);
cmd.Parameters.Add("@empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("@empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("@empIn", MySqlDbType.Date).Value = textBox2.Text;
cmd.Parameters.Add("@empOut", MySqlDbType.VarChar).Value = textBox3.Text;
execnonquery(cmd, "Data Inserted");
}
public void insertempsched()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update employee set empSched=empSched where empID=@empID", con);
cmd.Parameters.Add("@empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("@empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
con.Close();
}
public void execnonquery(MySqlCommand sqc, string mymsg)
{
con.Open();
if (sqc.ExecuteNonQuery() == 1)
{
MessageBox.Show(mymsg);
}
else
{
MessageBox.Show("Query not Executed");
}
con.Close();
}
}
}
| <c#><database><indexing> | 2019-01-26 17:37:49 | LQ_EDIT |
54,382,655 | boostrap div margin top | **Boostrap**
<div class="mb-md-3 ml-md-3 col-lg-8" >
<!-- <div class="mb-md-3 ml-md-3 col-lg-8" > -->
<a href="<?php echo base_url();?>admin/admin/add_hospital">
<button class="btn btn-success" onclick="add_hospital()">
<i class="fas fa-plus"></i> Add Hospital
</button>
</a>
</div>
please make a margin top as possible, I try some more times ith different ways but it cant fix. boostrap class may *mt-md-3*
| <css><bootstrap-4> | 2019-01-26 20:53:31 | LQ_EDIT |
54,383,077 | returning data from a database aplhabetically | Okay so I've created a database which stores different attributes for a given user. I have implemented an algorithm which takes the username attribute and stores the contents of this attribute and stores it in an array. However for some reason, when printing the array it shows the users in alphabetical order: I want it to return the original order of my database. For context I am using the JDBC API in java which takes mySQL sytax.
I have not implemented an ORDER BY statement, it is just a simple SELECT FROM WHERE statement but it seems to return alphabetically.
public void DisplayUsers() throws SQLException {
String queryCount = "SELECT COUNT(Username) FROM UserInfo";
String query = "SELECT Username FROM UserInfo";
declaringDataBase();
rsObj = statObj.executeQuery(queryCount);
String x = null;
while(rsObj.next()){
x = rsObj.getString(1);
}
int rowNum = Integer.parseInt(x);
rsObj = statObj.executeQuery(query);
String UserArray[] = new String[rowNum];
int counter = 0;
while(rsObj.next()){
String user = rsObj.getString("Username");
UserArray[counter] = user;
System.out.println(UserArray[counter]);
counter++;
}
}
the line *declaringDatabase();* simply calls another method to connect my database to the code. The count statement is taking the number of users under attribute Username and creating an integer to store as the length of the array. But anyway my UserArray[] returns values in alphabetical order? does anybody know why! highly appreciated. | <java><mysql><sql><jdbc> | 2019-01-26 21:43:21 | LQ_EDIT |
54,383,467 | what if i want to write another function |
int main(){
const int length = 30;
const int width = 20;
const char newline = '\n';
int area;
area = length * width;
if( length < width){
printf("the size of this property : %d", area);
printf("%c", newline);
} else if(length > width){
for(int n = 0; n<2; n++){
printf("miao\n");
}
} else{
for(int i =0; i < 3; i++){
printf("haooo\n");
}
}
return 0;
}
i tried to write another function after it that isn't called main and it didn't run it, why so?
| <c> | 2019-01-26 22:39:08 | LQ_EDIT |
54,383,785 | CSS Center curved figure | <p>Is there a way to draw the following figure just with pure CSS?
<a href="https://i.stack.imgur.com/UDjI7.jpg" rel="nofollow noreferrer">figure</a></p>
| <css><figure><curve> | 2019-01-26 23:32:34 | LQ_CLOSE |
54,383,963 | How do I access a variable that's defined within an imported file? | <p>My windows batch file:</p>
<pre><code>python test.py
pause
</code></pre>
<p>test.py:</p>
<pre><code>import test_import
print(greeting)
</code></pre>
<p>test_import.py:</p>
<pre><code>greeting='hello world'
</code></pre>
<p>This isn't working. I'm getting an error message, saying 'greeting' is not defined. I'd like to show you the output, but I'm having trouble with that too.</p>
<p>What do I need to change withint test_import.py, so the variable is accessible within the main module?</p>
| <python> | 2019-01-27 00:04:12 | LQ_CLOSE |
54,387,064 | expected 2d array got scalar array instead, Please help out | Hello everyone i am getting this error
ValueError: Expected 2D array, got scalar array instead:
array=6.5.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
while executing this code
#SVR
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
#Fitting the SVR to the Data Set
from sklearn.svm import SVR
regressor = SVR(kernel = 'rbf', gamma = 'auto')
regressor.fit(X, y)
#Predicting a new result
y_pred = regressor.predict(6.5)
| <python><machine-learning><anaconda><spyder><data-science> | 2019-01-27 10:18:46 | LQ_EDIT |
54,388,037 | Is there any alternative to the code below for attaching files in the google spreadhseet (depreciation error(UIapp))? | I must admit I cannot programme the solution I am seeking from scratch, usually I manipulate codes available for solving issues that I face regularly. The problem while running the code I was using "UiApp has been deprecated. Please use HtmlService instead.". I looked into Htmlservice documentation but did not get any idea how I could convert the entire UIapp code into functional html code. If someone has already solved file attachment problem due to deprecation(UIapp), then it would be a great help. Or, if anyone can suggest me anything that I can use as an alternative pls advise me.
// upload document into google spreadsheet
// and put link to it into current cell
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var menuEntries = [];
menuEntries.push({name: "File...", functionName: "doGet"});
ss.addMenu("Attach ...", menuEntries);
}
function doGet(e) {
var app = UiApp.createApplication().setTitle("upload attachment into Google Drive");
SpreadsheetApp.getActiveSpreadsheet().show(app);
var form = app.createFormPanel().setId('frm').setEncoding('multipart/form-data');
var formContent = app.createVerticalPanel();
form.add(formContent);
formContent.add(app.createFileUpload().setName('thefile'));
// these parameters need to be passed by form
// in doPost() these cannot be found out anymore
formContent.add(app.createHidden("activeCell", SpreadsheetApp.getActiveRange().getA1Notation()));
formContent.add(app.createHidden("activeSheet", SpreadsheetApp.getActiveSheet().getName()));
formContent.add(app.createHidden("activeSpreadsheet", SpreadsheetApp.getActiveSpreadsheet().getId()));
formContent.add(app.createSubmitButton('Submit'));
app.add(form);
SpreadsheetApp.getActiveSpreadsheet().show(app);
return HtmlService.createHtmlOutputFromFile('Index');
}
function doPost(e) {
var app = UiApp.getActiveApplication();
app.createLabel('saving...');
var fileBlob = e.parameter.thefile;
var doc = DriveApp.getFolderById('enterfolderId').createFile(fileBlob);
var label = app.createLabel('file uploaded successfully');
// write value into current cell
var value = 'hyperlink("' + doc.getUrl() + '";"' + doc.getName() + '")'
var activeSpreadsheet = e.parameter.activeSpreadsheet;
var activeSheet = e.parameter.activeSheet;
var activeCell = e.parameter.activeCell;
var label = app.createLabel('file uploaded successfully');
app.add(label);
SpreadsheetApp.openById(activeSpreadsheet).getSheetByName(activeSheet).getRange(activeCell).setFormula(value);
app.close();
return app;
}
| <google-apps-script><web-applications><google-sheets> | 2019-01-27 12:18:29 | LQ_EDIT |
54,388,280 | C++ How do you call a method for all members of a class? | <p>I have a class will many members and I want to
call a method for ALL membersof that class rather than
just an individual member</p>
<p>I could link all members of class via linked lists but is there a better way?</p>
| <c++><class> | 2019-01-27 12:50:49 | LQ_CLOSE |
54,388,489 | Integer Division in Negative Numbers in Python | <p>I'm testing big integers in Python; they are implemented as an object with sign and an array of digits. It's, basically, to describe Karatsuba Multiplication, and, for those big integers, I need the same behaviour like oridinary numbers with integer division by <code>10</code>, and, there is a problem:<br>
Why, in Python, <code>-22 // 10 = -3</code>?</p>
| <python><python-3.x><math><arithmetic-expressions><integer-division> | 2019-01-27 13:12:34 | LQ_CLOSE |
54,388,769 | C# how do I pass text from form1 to form2 when "both forms are open" | I have two forms "which are both open". I want to send a datagridview cell value from form 1 (already open) to form 2 (already open). (I don't want to pass text on form load, but after some edits on the already open form). I've searched the web for days but I can't find one for already open forms. (Only those containing form.show() property). | <c#><winforms><datagridview> | 2019-01-27 13:44:04 | LQ_EDIT |
54,389,341 | Vue computed property not working as expected | <p>I have a vue component with a computed property i use to produce a list, it works on an array grouped by first letter..
see </p>
<p><a href="https://jsfiddle.net/c6gtj1hw/" rel="nofollow noreferrer">https://jsfiddle.net/c6gtj1hw/</a></p>
<pre><code>if (details.length > 0) {
accum.push[curr];
}
</code></pre>
<p>the push to accumulator isnt working as i would have expected. Is there something obvious im missing?</p>
| <javascript><vue.js><vuejs2><vue-component> | 2019-01-27 14:44:36 | LQ_CLOSE |
54,390,777 | reading excel sheet with visual basic | I'm writing the code below to read data from excel sheet and display data into a combo box in visual basic >>>
when I click run nothing display
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim MyConnection As New OleDb.OleDbConnection
Dim MyCommand As New OleDb.OleDbCommand
Dim filePath, sql As String
filePath = "C:\Users\Nour\Desktop\projects\grade10\grade10\atlas.xlsx"
sql = "Select continent from [Sheet1]"
MyConnection.ConnectionString = $"Provider= Microsoft.Jet._OLEDB 11.0;data source = {filePath};Extended_Properties=Excel 8.0"
MyConnection.Open()
MyCommand.Connection = MyConnection
MyCommand.CommandText = sql
Dim da As New OleDb.OleDbDataAdapter
da.SelectCommand = MyCommand
Dim dt As New DataTable
da.Fill(dt)
Me.ComboBox1.DataSource = dt
Me.ComboBox1.DisplayMember = dt.Columns(0).ToString
MyConnection.Close()
| <excel><vb.net><jet> | 2019-01-27 17:16:27 | LQ_EDIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.