input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Loading Coldfusion javascript asynchronously? <p>Whenever a page is loaded with Coldfusion, it loads many default Coldfusion javascripts. When I run the Goolge PageSpeed Tools, it always complain about the render-blocking JavaScript. Apparently, Coldfusion has many javascript when a page is loaded such as </p>
<pre><code>...scripts/ajax/yui/yahoo-dom-event/yahoo-dom-event.js
...scripts/ajax/yui/aniax/yui/autocomplete/autocomplete-min.js
...scripts/ajax/yui/autocomplete/autocomplete-min.js
...scripts/ajax/messages/cfmessage.js
...scripts/ajax/package/cfajax.js
...scripts/ajax/package/cfautosuggest.js
...scripts/cfform.js
...scripts/masks.js
</code></pre>
<p>These all are considered render-blocking scripts. I can't find any information on how to make them none-render-blocking because obviously I can't add the async="async" parameter to the Coldfusion script which I can't see. How can I make the Coldfusion script none-render-blocking or am I stuck with it?</p>
<p>Can someone please shed some lights?</p>
| <p>If you really wanted to do something about this instead of rewriting your UI code, you can actually grab the output from the buffer before it is sent to the client and modify it. Your modifications could be as simple as removing a hardcoded list of script tags and replacing them with a custom script file that you host in your webroot. The custom script file would simply be all of the other script files' contents combined.</p>
<p>To do this: </p>
<ol>
<li>In onRequestEnd in application.cfc you can call <code>var outputBuffer = getPageContext().popBody().getBuffer()</code> which will return the body to be sent to the client. </li>
<li>Run replacements on <code>outputBuffer</code>, looking for those script tags and removing them via regular expressions. You'll want to keep track of whether or not you've actually removed any to use as a flag in the next step. </li>
<li>Finally, you would append to the output with your new master script tag if your flag that replacements have been made is true. After you do that, the buffer will be automatically flushed to the client. </li>
</ol>
<p>I believe that Adobe no longer updates the script files, so you basically don't have to worry about versioning your master script file to clear the browser cache.</p>
<p>Edit/Note: Definitely avoid using the CF UI stuff, but we don't know what your situation is like right now. If you have hundreds or thousands of hours of rewriting to do, then obviously rewriting it all is likely not something that is practical at this time.</p>
|
How can i switch two strings in a 2d array <p>Below is my code. Here, i have to switch two of the names in the 2D array but i'm not sure how to do this.</p>
<p>Anyone knows how to do? </p>
<pre><code> import java.util.Scanner;
public class Homeworktest {
public static void main(String[] args) {
String[][] people = new String[3][3];
people[0][0] = "April";
people[0][1] = "Jenny";
people[0][2] = "Charlie";
people[1][0] = "Maya";
people[1][1] = "Daniel";
people[1][2] = "Felix";
people[2][0] = "Jack";
people[2][1] = "Charlotte";
people[2][2] = "Nick";
for(int i = 0; i < people.length; i++) {
String[] subarrays = seatingChart[i];
for(int y = 0; y < people.length; y++) {
System.out.print(subarrays[y] + " ");
}
System.out.println();
}
public static void switchSeats(int row1, int col1, int row2, int col2) {
}
}
}
</code></pre>
| <p>To swap values of two array locations, first, hold one value in a temporary variable, assign the second location's value to the first location and lastly assign the temporary variable's value to the second location.</p>
<pre><code>public static void switchSeats(String[][] people, int row1,
int col1, int row2, int col2) {
String tmp = people[row1][col1];
people[row1][col1] = people[row2][col2];
people[row2][col2] = tmp;
}
</code></pre>
<p>In the above code, <code>tmp</code> serves as the temporary variable.</p>
|
Create input file in HDFS <p>I'm trying to create an input file in the hdfs using this command :</p>
<pre><code>hduser@salma-SATELLITE-C855-1EQ:/usr/local/hadoop$ ./bin/hadoop fs -mkdir /in
</code></pre>
<p>but it gives me an error that the connection failed :</p>
<pre><code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/local/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
16/10/09 02:12:04 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
mkdir: Call From salma-SATELLITE-C855-1EQ/127.0.1.1 to localhost:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
</code></pre>
<p>I already run hadoop service with start-all.sh :</p>
<pre><code>hduser@salma-SATELLITE-C855-1EQ:/usr/local/hadoop$ jps
20437 Jps
20030 SecondaryNameNode
19839 DataNode
</code></pre>
<p>So can anyone help to solve this problem </p>
| <p>Your are missing the namenode ( primary ) this is where you code is attempitng to connect. Check the log to understand why it does not started.</p>
|
How do you animate rows swapping with ListView? (React Native) <p>I'm trying to animate the swapping of two rows with a React Native ListView</p>
<p>Here's my datasource code (both in my render method):</p>
<pre><code>const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id})
var dataSource = ds.cloneWithRows(state.todoLists[this.props.index].todos.slice())
</code></pre>
<p>Here's my swap code (using MobX):</p>
<pre><code> var {todo, i} = forID(state.todoLists[list].todos, id) //Gets index and todo from id
state.todoLists[list].todos.splice(i, 1)
state.todoLists[list].todos.push({...todo, done: !todo.done})
</code></pre>
<p>As you can see, the equivalence is persisted since the array item is just shifted down.</p>
<p>If I try LayoutAnimation, I get this weirdness:
<a href="http://i.stack.imgur.com/Ukybn.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ukybn.png" alt="enter image description here"></a></p>
<p>Any ideas?</p>
| <p>I suspect the problem is the fact that (according to what you say) you are creating the DataSource in your <code>render</code> method. You should create the <code>ListView.DataSource</code> object in your constructor (or <code>componentWillMount</code>), then call <code>cloneWithRows</code> when your data changes, not in <code>render</code>. The issue is that by recreating a new DataSource on each render, it never calls the <code>rowHasChanged</code> function because there is never a previous state in the datasource.</p>
<p><strong>Example Correct Implementation</strong></p>
<p>In the below example, I setup the datasource in the constructor and store it in the state. Then once mounted, I have it load the todos, and update the datasource in the state, which will trigger a re-render.</p>
<p>Then, when you want to move a todo to the bottom, you would call <code>this.moveItemToBottom(id)</code>, which modifies the state, and updates the datasource on the state, and re-render after setting up the LayoutAnimation.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class TodoList extends Component {
constructor(props, context) {
super(props, context);
this.state = {
ds: new ListView.DataSource({
rowHasChanged: (r1, r2) => (r1 !== r2),
}),
};
}
componentDidMount() {
loadInitialData();
}
loadInitialData() {
// Do something to get the initial list data
let todos = someFuncThatLoadsTodos();
this.setState({
ds: this.state.ds.cloneWithRows(todos),
});
}
moveItemToBottom(id) {
// get your state somewhere??
let todos = state.todoLists[list].todos;
let {todo, i} = forID(state.todoLists[list].todos, id)
todos.splice(i, 1).push({...todo, done: !todo.done});
LayoutAnimation.easeInEaseOut();
this.setState({
ds: this.state.ds.cloneWithRows(todos),
});
}
render() {
return (
<ListView
dataSource={this.ds}
// Other props
/>
);
}
}</code></pre>
</div>
</div>
</p>
<p>EDIT/NOTE: My example doesn't take into account anything to do with MobX. I haven't used it, but from a cursory look, you may need to observe the todos list and update the datasource whenever it updates, and just have the <code>moveItemToBottom</code> method update the MobX state and rely on the observable to <code>setState</code> with the cloned datasource.</p>
|
In OS X who owns the model, NSDocument or NSViewController <p>Working in iOS I've never dealt with OS X and NSDocument based apps. Where should the model reference live, inside the NSDocument or the representedObject in the NSWindow's content NSViewController? Or both?</p>
| <p>It should be stored in the NSDocument object as stated by the Apple documentation in <a href="https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/Designing/Designing.html" rel="nofollow">here</a>. In particular, check Figure 1-1. Further below, on the same page, Apple states that a <strong>data model corresponds to a document type</strong>, so if you have different models you should use different document types that should be stored in NSDocument objects.</p>
|
How to override user input on Jquery autocomplete? <p>I have a simple autocomplete function that searches an array of objects. It's working fine, but I want to override what the user is searching for. </p>
<p>I want to <strong>append another input's value to their search</strong>. For example, if they search "cat", I want to append <code>$('#input2').val()</code> so their search becomes "cat dog" (without changing the actual <input>'s value).</p>
<p>This seems like an easy thing to do, but I can't figure out how to do it without overriding the entire search method.</p>
<p><strong>Existing code:</strong></p>
<pre><code>$("#search").autocomplete({
source: data,
appendTo: '#admin-results'
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $('<li>')
.append('<div>' + item.label + '</div>')
.appendTo(ul);
};
</code></pre>
| <p>The following will do what you ask by using function for source</p>
<pre><code>var terms = ["c++", "java dog", "php dog", "coldfusion", "javascript dog", "asp dog", "ruby"]
$("#autocomplete").autocomplete({
source: function(req, response) {
var term = req.term + ' dog';// adjust to a dom value or whatever
var res = terms.filter(function(item) {
return item.toLowerCase() === term.toLowerCase()
});
response(res);
}
});
</code></pre>
<p>Adjust filter function accordingly also. This is only rough for absolute match</p>
<p><kbd><strong><a href="http://plnkr.co/edit/ivOaZQY9mZ1LlTKptVsJ?p=preview" rel="nofollow">DEMO</a></strong></kbd></p>
|
copy elision using STL (vector as example) <p>I was reading about the copy elision in c++. And i was having doubts about STL in c++ using this copy elision.</p>
<p>The following code:</p>
<pre><code>#include <vector>
#include <iostream>
using namespace std;
vector<int> merge(vector<int> &arrA, vector<int> &arrB)
{
int x;
vector<int> result;
for(x = 0; x < arrA.size(); x++)
{
result.push_back(arrA[x]);
}
for(x = 0; x < arrB.size(); x++)
{
result.push_back(arrB[x]);
}
cout << "fun return: " << &result <<endl;
return result;
}
int main(int argc, char const *argv[])
{
vector<int> arrA;
arrA.push_back(1);
vector<int> arrB;
arrB.push_back(2);
vector<int> res;
res = merge(arrA, arrB);
cout << "return: " << &res <<endl;
return 0;
}
</code></pre>
<p>So I was doing a simple task (merging) the vectors A and B (do not pay attention to the process, just the function and return. </p>
<pre><code>vector<int> merge(vector<int> &arrA, vector<int> &arrB)
</code></pre>
<p>With the following definition it is returning a <code>vector<int></code> (no reference)</p>
<p>And also <code>return result;</code> which is the variable declared in the function scope. </p>
<p>I was trying to see the memory address at which these vectores are located.
output:</p>
<pre><code>==5036== Memcheck, a memory error detector
==5036== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==5036== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==5036== Command: ./a.out
==5036==
fun return: 0xffefffe40
return: 0xffefffe20
==5036==
==5036== HEAP SUMMARY:
==5036== in use at exit: 0 bytes in 0 blocks
==5036== total heap usage: 5 allocs, 5 frees, 28 bytes allocated
==5036==
==5036== All heap blocks were freed -- no leaks are possible
==5036==
==5036== For counts of detected and suppressed errors, rerun with: -v
==5036== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code></pre>
<p>The memory address is different for both so I was thinking that as long as it will no make a copy-construtor, it will be the same memory address at the end (0xffefffe40) Does that means it is copy-constructed?</p>
<p>Is this method being copy elision? </p>
<ul>
<li>if not: why it is not copy elision?</li>
<li>if yes: How can I know it is really doing the copy elision? </li>
</ul>
<p>And the important one: if this is not being copy elision, is it possible to do it? what is needed in order to do the copy elision in STL?</p>
| <p>For copy elision, you need to have the "copy" in the first place, i.e. your <code>res</code> vector has to be copy constructed from the return value.<br>
Otherwise you'll just have an assignment, which requires getting rid of whatever was in the vector and as such cannot be elided.</p>
<p>Notice that it would still be a move assignment, so the drawback won't be that much (You can test it with memcheck too).</p>
|
How to solve "Failed to convert property value[...]" <p>So I have a form with a dropdown in Spring MVC:</p>
<pre><code><form:form modelAttribute="user" action="registerVerify" method="post">
<!-- Other fields-->
<spring:message code="register.country" />
<form:select path="country" items="${countryList}" />
<br/>
</form:form>
</code></pre>
<p>Which is populated by this controller:</p>
<pre><code>@Controller
public class RegisterController {
@RequestMapping(value = "registerForm", method = RequestMethod.GET)
public String register(@ModelAttribute("user") User user, Model model) {
model.addAttribute("user", new User());
model.addAttribute("countryList", cDao.getCountryMap());
model.addAttribute("companyList", cpDao.getCompanyMap());
return "login/registerForm";
}
@RequestMapping(value = "registerVerify", method = RequestMethod.POST)
public String makeRegistration(@ModelAttribute("user") @Valid User user, BindingResult result,
RedirectAttributes redirectAttributes, Model model) {
if (result.hasErrors()) {
System.out.println(result.getFieldError().getDefaultMessage());
model.addAttribute("org.springframework.validation.BindingResult.user", result);
return "redirect:registerForm";
}
if (dao.add(user)) {
redirectAttributes.addFlashAttribute("user", user);
return "redirect:login";
} else {
return "redirect:registerForm";
}
}
// Service classes bellow
</code></pre>
<p>I've made some converters</p>
<pre><code>package br.com.sirious.energyquality.converters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import br.com.sirious.energyquality.dao.CompanyDao;
import br.com.sirious.energyquality.models.Company;
public class IdToCompanyConverter implements Converter<String, Company>{
@Autowired
CompanyDao dao;
@Override
public Company convert(String id) {
return dao.getCompanyByID(Integer.parseInt(id));
}
}
</code></pre>
<p>And I've set My WebMVCConfig (and WebApplicationInitializer, and spring-context...)</p>
<pre><code>@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry){
registry.addConverter(new IdToCompanyConverter());
}
}
</code></pre>
<p>But I still get "Failed to convert property value of type [java.lang.String] to required type [br.com.sirious.energyquality.models.Company] for property 'Company'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [br.com.sirious.energyquality.models.Company] for property 'Company': no matching editors or conversion strategy found"</p>
<p>I've checked on many similar posts but none solved the problem. Can someone diagnose what is happening?</p>
| <p>Try using the following <em>ConverterRegistry</em> method:</p>
<pre><code><S,T> void addConverter(Class<S> sourceType,
Class<T> targetType,
Converter<? super S,? extends T> converter)
</code></pre>
<p>Which will result in:</p>
<pre><code>public void addFormatters(FormatterRegistry registry){
registry.addConverter(String.class, Company.class, new IdToCompanyConverter());
}
</code></pre>
|
Java - add a space after splitting a String <p>I need to add a space after splitting a String with a <code>" "</code> delimiter. The reason I need to do this is because a space has not been added at the start of the next String as shown in this example:</p>
<pre><code>"There was nothing so VERY remarkable in that; nor did Alice" +
"think it so VERY much out of the way to hear the Rabbit say to"
</code></pre>
<p>My code below only splits the string (and reverses it), but the concatenations produce the following result (Notice where "Alicethink" is joined together):</p>
<pre><code>erehT saw gnihton os YREV elbakramer ni ;taht ron did knihtecilA
ti os YREV hcum tuo fo eht yaw ot raeh eht tibbaR yas
</code></pre>
<p>Code:</p>
<pre><code>String[] text = PROBLEM5PARA.split(" ");
String reverseString = "";
for (int i = 0; i < text.length; i++) {
String word = text[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord += word.charAt(j);
}
reverseString += reverseWord + " ";
}
System.out.println(reverseString);
</code></pre>
<p>How can I fix it? </p>
<p>EDIT:
Here is the whole String:</p>
<pre><code>private static final String PROBLEM5PARA =
" There was nothing so VERY remarkable in that; nor did Alice" +
"think it so VERY much out of the way to hear the Rabbit say to" +
"itself, `Oh dear! Oh dear! I shall be late!' (when she thought" +
"it over afterwards, it occurred to her that she ought to have" +
"wondered at this, but at the time it all seemed quite natural);" +
"but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT-" +
"POCKET, and looked at it, and then hurried on, Alice started to" +
"her feet, for it flashed across her mind that she had never" +
"before seen a rabbit with either a waistcoat-pocket, or a watch to" +
"take out of it, and burning with curiosity, she ran across the" +
"field after it, and fortunately was just in time to see it pop" +
"down a large rabbit-hole under the hedge.";
</code></pre>
| <p>If the original string is</p>
<pre><code>"There was nothing so VERY remarkable in that; nor did Alice" + "think it so VERY much out of the way to hear the Rabbit say to"
</code></pre>
<p>that is seen by your code as</p>
<pre><code>"There was nothing so VERY remarkable in that; nor did Alicethink it so VERY much out of the way to hear the Rabbit say to"
</code></pre>
<p>After that concatenation (which happens in compilation, I believe), <code>Alicethink</code> is a single word, and there is no way to reverse <code>Alice</code> and <code>think</code> individually.</p>
<p>If this is a homework assignment, I think your code is currently doing what it's supposed to. If there is doubt, ask your instructor.</p>
|
Calculate BMI in Java using metrics <p>Please bear with me, I'm an interactive design student in week 2 of a Java class. </p>
<p>I need to create a BMI calculator using the following formula:Calculate the BMI using the following formula:</p>
<pre><code> w
BMI = ___
(h/100) 2
</code></pre>
<p>where w is weight in kilograms and h is height in centimeters. Note that the denominator is squared.</p>
<p>Here is my code:</p>
<pre><code> /**
* Calculates the Body Mass Index (BMI) for the user. The user must type in his
* or her height in centimeters and weight in kilograms, and the computer prints
* out the user's BMI.
*/
import java.util.Scanner; // import class
public class BMI {
public static void main(String[] args) {
int weight;
int height;
double bmi;
Scanner console; // create a variable to represent the console
console = new Scanner (System.in); // create the object with new
System.out.print("How much do you weigh (in kg)? "); // user prompt to provide weight
weight = console.nextInt(); // read from console
System.out.print("How tall are you (in cm)? "); // user prompt to provide height
height = console.nextInt(); // read value from console
bmi = (double) weight / (height/100*height/100); // calculates BMI
System.out.println("Your BMI is " + bmi); // displays user's BMI
}
}
</code></pre>
<p>The program if one can call it that, runs but I think the calculation written incorrectly. </p>
<p>I've formatted the calculation several ways:
bmi = (double) weight / (height/100*height/100); returns the weight EXCEPT when I use 100 for the weight and 200 for the height. I've tried the following:</p>
<p>bmi = (double)weight / height/100*height/100; </p>
<p>bmi = (double) weight / (height/100*height/100); </p>
<p>bmi = (double) weight / (height/100)*(height/100); </p>
<p>bmi = (double) weight / ((height/100)*(height/100)); </p>
<p>bmi = (double)(weight / height/100*height/100); </p>
<p>bmi = (double) (weight / (height/100*height/100); </p>
<p>bmi = (double) (weight /(height/100)*(height/100); </p>
<p>bmi = (double)(weight) / ((height/100)*(height/100)); </p>
<p>bmi = (double)(weight) / ((height/100)*(height/100)); </p>
<p>bmi = (double)(weight) / height/100*height/100;</p>
<p>I either get the weight 100% of the time or it only works with 100 and 200 as the variables. I tried 75 and 150 and that also returns the weight. </p>
<p>At this point I don't even remember PEMDAS</p>
| <p>When you divide the int <code>height</code> by 100 it truncates the decimal since it is still an int. </p>
<p>Try initializing the variables as doubles:</p>
<pre><code>double weight;
double height;
</code></pre>
<p>Then cast them when you get the int from the input:</p>
<pre><code>weight = (double) console.nextInt();
height = (double) console.nextInt();
</code></pre>
<p>That way you're still taking an int for the input, but it acts like a double when you do your calculations.</p>
|
Possible to use Docker machine with continuous integration tools? <p>What I'm trying to do: use a continuous integration tool like CircleCI or GitLab to deploy to a DigitalOcean droplet. Locally I'm able to use Docker Machine to run something like </p>
<p><code>$ eval $(docker-machine env my-droplet)</code></p>
<p>to connect to an already created droplet and then <code>docker run foo</code>.</p>
<p>Is it possible to do such an action via the traditional deploy.yml file? Assume that I have a <code>digitalocean-access-token</code> and a droplet already created.</p>
| <p>The integration proposed by DigitalOcean is more with Docker Cloud, meaning your CI should push your image to Docker Cloud, for DigitalOcean to use in a Droplet.</p>
<p>See "<a href="http://tutorials.pluralsight.com/devops/deploy-horizon-using-docker-cloud-digitalocean#bAfwkQxFwCUX8gOT.99" rel="nofollow">Deploy Horizon Using Docker Cloud & DigitalOcean</a>" from <strong><a href="https://twitter.com/devcasche" rel="nofollow">Chris Asche</a></strong></p>
<blockquote>
<p>log into Docker Cloud and link your DigitalOcean account. To do this, click on 'Cloud Settings' at the bottom left. You should now see a list of Cloud Providers on the page. Click on the plug icon next to DigitalOcean to link your accounts. Note that, at the time of writing, there is a $20 credit added to your DigitalOcean account when linked with Docker Cloud.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/zlYj3.png" rel="nofollow"><img src="http://i.stack.imgur.com/zlYj3.png" alt="https://raw.githubusercontent.com/pluralsight/guides/master/images/d0ffee77-f47c-41ac-942d-3d02f8b3d42f.png"></a></p>
<blockquote>
<p>Once your accounts are linked, create a new DigitalOcean Node Cluster. I'm going to call mine, <code>horizon-with-docker</code> in the region <code>Toronto 1</code>.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/LGKf2.png" rel="nofollow"><img src="http://i.stack.imgur.com/LGKf2.png" alt="https://raw.githubusercontent.com/pluralsight/guides/master/images/82fcfbc6-5e4c-4038-8ce4-152c54bbf711.png"></a></p>
<blockquote>
<p>The newly created node cluster can be used to run a stack. A stack is a collection of services and each service is a collection of containers. Stacks are created with the <a href="https://docs.docker.com/docker-cloud/apps/stack-yaml-reference/" rel="nofollow"><code>stack-yaml</code> file</a>.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/2qAxC.png" rel="nofollow"><img src="http://i.stack.imgur.com/2qAxC.png" alt="https://raw.githubusercontent.com/pluralsight/guides/master/images/9109de97-3698-4f44-9d10-15b7e5e6970d.png"></a></p>
<blockquote>
<p>Once created, revisit the node cluster created earlier to grab the IP address of your DigitalOcean droplet - my droplet IP is 159.203.61.66. Go ahead and visit your freshly deployed Horizon application at the IP address. </p>
</blockquote>
|
C# Filestream to SQL Server database <p>I want to create a file in SQL Server from a string. I can't figure out how to put it into the database. After reading it seems it has someting to do with filestream. If so then once the stream is created then how do I put that to my DB as a file?</p>
<pre><code>FileStream fs1 = new FileStream("somefilename", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs1);
writer.WriteLine("file content line 1");
writer.Close();
</code></pre>
<p>What I am trying to achieve is create a file from a string. I believe that my db is already set up for files. As we have a savefile method that works:</p>
<pre><code>HttpPostedFile file = uploadedFiles[i];
if (file.ContentLength < 30000000)
{
//DOFileUpload File = CurrentBRJob.SaveFile(CurrentSessionContext.Owner.ContactID, Job.JobID, fileNew.PostedFile);
DOFileUpload File = CurrentBRJob.SaveFile(CurrentSessionContext.Owner.ContactID, Job.JobID, file, file.ContentLength, CurrentSessionContext.CurrentContact.ContactID);
DOJobFile jf = CurrentBRJob.CreateJobFile(CurrentSessionContext.Owner.ContactID, Job.JobID, File.FileID);
CurrentBRJob.SaveJobFile(jf);
}
</code></pre>
<p>What I want to do is: Instead of the user selecting a file for us to save to the DB. I want to instead create that file internally with strings and then save it to the db.</p>
| <p>Create a a column type of any one below. Use ADO.NET <code>SqlCommand</code> write it to database.</p>
<ul>
<li><code>varbinary(max)</code> - to write binary data</li>
<li><code>nvarchar(max)</code> - for unicode text data (i mean if text involves UNICODE chars)</li>
<li><code>varchar(max)</code> - for non unicode text data</li>
</ul>
|
Webadmin and php are not working correctly <p>I have ubuntu server 16.04 running within hyper-v on a Windows 10 computer. I am running LAMP with Apache2, MariaDB, and PHP7.0. I have installed phpmyadmin but when I attempt to call it through my browser I get text, I'm assuming that it is the correct file but it is obviously not outputting the program. These are screenshots of what I'm seeing: </p>
<p><a href="http://i.stack.imgur.com/EIuBR.png" rel="nofollow"><img src="http://i.stack.imgur.com/EIuBR.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/ngBd3.png" rel="nofollow"><img src="http://i.stack.imgur.com/ngBd3.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/TnWDd.png" rel="nofollow"><img src="http://i.stack.imgur.com/TnWDd.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/9eYzY.png" rel="nofollow"><img src="http://i.stack.imgur.com/9eYzY.png" alt="enter image description here"></a></p>
<p>I am stuck at this point and have tried doing just about everything. I've entered the Include statement, as well as configured, updated, and upgraded everything. I started out using mysql but MariaDB seems to be working better. I just want to get phpmyadmin up and working and to put my websites up on the internet. Any help is appreciated. </p>
| <p>After doing everything that is listed, I had rebooted and tried accessing phpmyadmin with success, so I'm at loss for words. </p>
|
C - Forward declaration for struct and function <p>I'm trying to figure out how exactly forward declarations interact. When forward declaring a function that takes a typedef'd struct, is there a way to just get the compiler to accept a previously forward declared (but not actually defined) struct as a parameter?</p>
<p>The code that I've got working:</p>
<pre><code>typedef struct{
int year;
char make[STR_SIZE];
char model[STR_SIZE];
char color[STR_SIZE];
float engineSize;
}automobileType;
void printCarDeets(automobileType *);
</code></pre>
<p>What I wish I could do:</p>
<pre><code>struct automobileType;
void printCarDeets(automobileType *);
//Defining both the struct (with typedef) and the function later
</code></pre>
<p>I feel like I'm either missing something really basic or not understanding how the compiler deals with forward declarations of structs.</p>
| <p>Typedefs and struct names are in different namespaces. So <code>struct automobileType</code> and <code>automobileType</code> are not the same thing.</p>
<p>You need to give your anonymous struct a tag name in order to do this.</p>
<p>The definition in your .c file:</p>
<pre><code>typedef struct automobileType{
int year;
char make[STR_SIZE];
char model[STR_SIZE];
char color[STR_SIZE];
float engineSize;
}automobileType;
</code></pre>
<p>The declaration in your header file:</p>
<pre><code>typedef struct automobileType automobileType;
void printCarDeets(automobileType *);
</code></pre>
|
Android Studio Gradle not Syncing <p>I'm very new to Android Studio and I'm basically trying to open an existing project that I had downloaded and compile/run it. I am getting the following error when Gradle attempts to sync...</p>
<pre><code>Error:Cannot read packageName from /Users/Amanda/Desktop/MyProject/src/main/AndroidManifest.xml
</code></pre>
<p>I have researched online and have tried several solutions, none of which have fixed my problem :/ I have also tried to "invalidate caches and restart" but it did not work either...</p>
<p>This is my Manifest:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.amanda.myproject.app">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="My Project">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".resourceListing"
android:label="My App Listing">
</activity>
<activity
android:name=".ListApps"
android:label="@string/title_activity_list_apps">
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</manifest>
</code></pre>
<p>My build.gradle:</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply plugin: 'com.android.application'
allprojects {
repositories {
mavenCentral()
}
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
}
dependencies {
}
</code></pre>
| <p>some times <code>clean</code> cant delete some of build folder files.</p>
<p>try these steps :</p>
<p>1- make a copy of your manifest file and delete your manifest file from project. </p>
<p>2- delete your <code>app/build</code> folder.</p>
<p>3-then clean your project</p>
<p>4- add the manifest file again to <code>src/main</code> directory</p>
<p>5- clean the project again</p>
<p>6- rebuild the project</p>
|
Routing error after trying to make a post <p>I'm getting a confusing routing error after trying to submit a post. the error is <code>No route matches [POST] "/blog"</code> despite it being in routes.rb. </p>
<p>Here is my route file: </p>
<pre><code>Rails.application.routes.draw do
get 'welcome/index'
get '/blog', to: 'posts#post', as: :post
get '/geobot', to: 'welcome#geobot', as: :geobot
get "/blog/show/:id", to: 'posts#show'
get '/blog/new', to: 'posts#new', as: :new
root 'welcome#index'
end
</code></pre>
<p>and post controller: </p>
<pre><code>class PostsController < ApplicationController
def post
end
def new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
</code></pre>
| <p>You have to put in your route.rb</p>
<pre><code>...
post '/blog', to: 'posts#post', as: :post
...
</code></pre>
<p>first word is the method</p>
<p>Maybe you need to look this <a class='doc-link' href="http://stackoverflow.com/documentation/ruby-on-rails/307/routing/1080/resource-routing-basic#t=20161009025958119533">Resource Routing (Basic)</a> </p>
|
How to split this string to dict with python? <p><strong>String</strong> </p>
<pre><code>string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
</code></pre>
<p><strong>Expected Result</strong> </p>
<pre><code>dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'}
</code></pre>
<p>Perhaps it is simple question,<br>
Is there any easy method to split <code>string1</code> to <code>dict1</code>?</p>
| <p>If you are looking for a one-liner, this will work:</p>
<pre><code>>>> dict(tuple(x.split(',')) for x in string1[1:-1].split('","'))
{'{ABCD-1B34-3X5F}': 'MEANING2', '{XLMN-2345-KFDE}': 'WHITE', '{ABCD-1234-3E3F}': 'MEANING1'}
</code></pre>
|
Swift/Xcode - UITextView and UIButtons in UIContainerView not responding to touch <p>My buttons and textviews are displaying properly inside the container view but they are not responding to clicks/taps. The container view's height is set to the regular portrait size (780). The container view is placed in a scroll view</p>
<p><a href="http://i.stack.imgur.com/gcv17.png" rel="nofollow"><img src="http://i.stack.imgur.com/gcv17.png" alt="Picture"></a></p>
| <p>The view controllers you get out of the container are independent controllers. Don't forget to set delegate there. </p>
|
(BeautifulSoup) how do I access an attribute of a tag? <p>I searched everywhere and I can't seem to get it understood in my head.
The documentation at <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes</a></p>
<p>The documentation says: </p>
<blockquote>
<p>You can access a tagâs attributes by treating the tag like a dictionary: <code>tag['class']</code></p>
</blockquote>
<p>What do they mean by "tag"? Do I have to put <code><a>['class']</code> or something?</p>
| <p>A "tag" is a kind of BeautifulSoup object. For example, <code>soup.find("a")</code> returns a tag object of the first anchor tag in the html being parsed. Just as the documentation says, tag attribute access is just like accessing a dictionary.</p>
<pre><code>my_tag = soup.find("a")
href_value = my_tag["href"]
#or
href_value = my_tag.get("href")
</code></pre>
|
Java: How to implement Dancing Links algorithm (with DoublyLinkedLists)? <p>I am trying to implement Knuth's Dancing Links algorithm in Java.</p>
<p>According to Knuth, if <code>x</code> is a node, I can totally unlink a node by the following operations in C:</p>
<pre><code>L[R[x]]<-L[x]
R[L[x]]<-R[x]
</code></pre>
<p>And revert the unlinking by:</p>
<pre><code>L[R[x]]<-x
R[L[x]]<-x
</code></pre>
<p>What am I doing wrongly in my main method?</p>
<p>How do you implement the unlinking and revert in Java?</p>
<p>Here's my main method:</p>
<pre><code> ///////////////
DoublyLinkedList newList = new DoublyLinkedList();
for (int i = 0; i < 81; i++) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(i);
newList.addFirst(set);
}
newList.displayList();
// start at 69
newList.getAt(12).displayNode();
//HOW TO IMPLEMENT UNLINK?
//newList.getAt(12).previous() = newList.getAt(12).next().previous().previous();
//newList.getAt(12).next() = newList.getAt(12).previous().next().next();
newList.displayList();
//HOW TO IMPLEMENT REVERT UNLINK?
//newList.getAt(12) = newList.getAt(12).next().previous();
//newList.getAt(12) = newList.getAt(12).previous().next();
System.out.println();
///////////////
</code></pre>
<p>Here's the DoublyLinkedList class:</p>
<pre><code>public class DoublyLinkedList<T> {
public Node<T> first = null;
public Node<T> last = null;
static class Node<T> {
private T data;
private Node<T> next;
private Node<T> prev;
public Node(T data) {
this.data = data;
}
public Node<T> get() {
return this;
}
public Node<T> set(Node<T> node) {
return node;
}
public Node<T> next() {
return next;
}
public Node<T> previous() {
return prev;
}
public void displayNode() {
System.out.print(data + " ");
}
@Override
public String toString() {
return data.toString();
}
}
public void addFirst(T data) {
Node<T> newNode = new Node<T>(data);
if (isEmpty()) {
newNode.next = null;
newNode.prev = null;
first = newNode;
last = newNode;
} else {
first.prev = newNode;
newNode.next = first;
newNode.prev = null;
first = newNode;
}
}
public Node<T> getAt(int index) {
Node<T> current = first;
int i = 1;
while (i < index) {
current = current.next;
i++;
}
return current;
}
public boolean isEmpty() {
return (first == null);
}
public void displayList() {
Node<T> current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public void removeFirst() {
if (!isEmpty()) {
Node<T> temp = first;
if (first.next == null) {
first = null;
last = null;
} else {
first = first.next;
first.prev = null;
}
System.out.println(temp.toString() + " is popped from the list");
}
}
public void removeLast() {
Node<T> temp = last;
if (!isEmpty()) {
if (first.next == null) {
first = null;
last = null;
} else {
last = last.prev;
last.next = null;
}
}
System.out.println(temp.toString() + " is popped from the list");
}
}
</code></pre>
| <p>I am not familiar with Knuth's Dancing Links algorithm, but found <a href="https://www.ocf.berkeley.edu/~jchu/publicportal/sudoku/sudoku.paper.html" rel="nofollow">this article</a> which made it quiet clear. In particular I found this very helpful: </p>
<blockquote>
<p>Knuth takes advantage of a basic principle of doubly-linked lists.
When removing an object from a list, only two operations are needed:</p>
<p>x.getRight().setLeft( x.getLeft() )<br>
x.getLeft().setRight(> x.getRight() ) </p>
<p>However, when putting the object back in the list, all
is needed is to do the reverse of the operation.</p>
<p>x.getRight().setLeft( x )<br>
x.getLeft().setRight( x ) </p>
<p>All that is
needed to put the object back is the object itself, because the object
still points to elements within the list. Unless xâs pointers are
changed, this operation is very simple.</p>
</blockquote>
<p><br>
To implement it I added setters for linking / unlinking. See comments:
<br></p>
<pre><code>import java.util.HashSet;
public class DoublyLinkedList<T> {
public Node<T> first = null;
public Node<T> last = null;
static class Node<T> {
private T data;
private Node<T> next;
private Node<T> prev;
public Node(T data) {
this.data = data;
}
public Node<T> get() {
return this;
}
public Node<T> set(Node<T> node) {
return node;
}
public Node<T> next() {
return next;
}
//add a setter
public void setNext(Node<T> node) {
next = node;
}
public Node<T> previous() {
return prev;
}
//add a setter
public void setPrevious(Node<T> node) {
prev = node;
}
public void displayNode() {
System.out.print(data + " ");
}
@Override
public String toString() {
return data.toString();
}
}
public void addFirst(T data) {
Node<T> newNode = new Node<T>(data);
if (isEmpty()) {
newNode.next = null;
newNode.prev = null;
first = newNode;
last = newNode;
} else {
first.prev = newNode;
newNode.next = first;
newNode.prev = null;
first = newNode;
}
}
public Node<T> getAt(int index) {
Node<T> current = first;
int i = 1;
while (i < index) {
current = current.next;
i++;
}
return current;
}
public boolean isEmpty() {
return (first == null);
}
public void displayList() {
Node<T> current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public void removeFirst() {
if (!isEmpty()) {
Node<T> temp = first;
if (first.next == null) {
first = null;
last = null;
} else {
first = first.next;
first.prev = null;
}
System.out.println(temp.toString() + " is popped from the list");
}
}
public void removeLast() {
Node<T> temp = last;
if (!isEmpty()) {
if (first.next == null) {
first = null;
last = null;
} else {
last = last.prev;
last.next = null;
}
}
System.out.println(temp.toString() + " is popped from the list");
}
public static void main(String[] args) {
///////////////
DoublyLinkedList newList = new DoublyLinkedList();
for (int i = 0; i < 81; i++) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(i);
newList.addFirst(set);
}
newList.displayList();
// start at 69
Node node = newList.getAt(12);
node.displayNode(); System.out.println();
//HOW TO IMPLEMENT UNLINK?
node.previous().setNext(node.next);
node.next().setPrevious(node.previous());
//The 2 statements above are equivalent to
//Node p = node.previous();
//Node n = node.next();
//p.setNext(n);
//n.setPrevious(p);
newList.displayList();
//HOW TO IMPLEMENT REVERT UNLINK?
node.previous().setNext(node);
node.next().setPrevious(node);
newList.displayList(); System.out.println();
///////////////
}
}
</code></pre>
|
Android Glide Image is not showing on the first screen <p>I am using Android glide to load remote images, but here i met a strange problem which image on the first screen not showing but while i scroll down and scroll up again, those images become showing normally.here is the screen shot:
<a href="http://i.stack.imgur.com/jPDSs.png" rel="nofollow"><img src="http://i.stack.imgur.com/jPDSs.png" alt="enter image description here"></a>
I have also googled such question and find a <a href="https://github.com/bumptech/glide/issues/1026" rel="nofollow">duplicate</a>,and after trying such steps it still doesn't work, and you may need to check code, here is it:</p>
<pre><code>public class SiteAdapter extends ArrayAdapter<Site> {
private int resourceId;
private List<Site> sites = null;
private Context context;
private SiteHolder siteHolder;
/**
* @param context the current activity context, we can get it using the super ArrayAdapter constructor
* @param resource the site_layout.xml file
* @param objects the collection to store all the sites
*/
public SiteAdapter(Context context, int resource, List<Site> objects) {
super(context, resource, objects);
this.context = context;
this.resourceId = resource;
this.sites = objects;
}
@Override
public Site getItem(int position) {
return sites.get(position);
}
@Override
public int getCount() {
return sites.size();
}
//get the viewpage which inflate by site_layout.xml file
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Site site = getItem(position);
View view = convertView;
siteHolder = new SiteHolder();
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(resourceId, null);
}
//this place we need to get the whole widget in site_layout.xml file
siteHolder.image = (ImageView) view.findViewById(R.id.thumbnail);
siteHolder.address = (TextView)view.findViewById(R.id.address);
siteHolder.mallName = (TextView) view.findViewById(R.id.name);
siteHolder.distance = (TextView) view.findViewById(R.id.distance);
siteHolder.address.setText(site.getAddress());
//set name of the view
siteHolder.mallName.setText(site.getName());
//set price of the view
//set distance of the view
siteHolder.distance.setText("<" + site.getDistance() + "m");
//set image
ImageTask task = new ImageTask();
task.execute("http://xxxx/springmvc/getFirst/" + site.getName());
return view;
}
//æ£æµadapaterä¸å è½½ç½ç»èµæºæ¯å¦å¯è¡?ç»è®º:ä¸å¯è¡
public String getImgUrl(String str){
String data = "";
try {
URL u = new URL(str);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String content = "";
StringBuffer sb = new StringBuffer();
while((content = br.readLine()) != null){
sb.append(content);
}
data = sb.toString();
br.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
class ImageTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... str) {
String data = "";
data = getImgUrl(str[0]);
return data;
}
@Override
protected void onPostExecute(String s) {
Glide.with(context)
.load(s)
.fitCenter()
.into(siteHolder.image);
}
}
class SiteHolder{
ImageView image;
TextView mallName;
TextView address;
TextView distance;
}
}
</code></pre>
<p>if there anybody who met such scene before, thank you in advance.</p>
| <p>See <a href="https://github.com/bumptech/glide/blob/master/README.md#compatibility" rel="nofollow">https://github.com/bumptech/glide/blob/master/README.md#compatibility</a></p>
<blockquote>
<p><strong>Round Pictures</strong>: <code>CircleImageView</code>/<code>CircularImageView</code>/<code>RoundedImageView</code> are known to have <a href="https://github.com/bumptech/glide/issues?q=is%3Aissue+CircleImageView+OR+CircularImageView+OR+RoundedImageView" rel="nofollow">issues</a> with <code>TransitionDrawable</code> (<code>.crossFade()</code> with <code>.thumbnail()</code> or <code>.placeholder()</code>) and animated GIFs, use a <a href="https://github.com/wasabeef/glide-transformations" rel="nofollow"><code>BitmapTransformation</code></a> (<code>.circleCrop()</code> will be available in v4) or <code>.dontAnimate()</code> to fix the issue.</p>
</blockquote>
<p>In short: the rounding views always rasterize the incoming Drawables into Bitmaps, which won't work if there's an animation inside the Drawable (GIF or crossFade).</p>
<p>On the first load the placeholder is shown while retrieving the image and then crossFaded to the image; later, when you scroll up the image is loaded from memory cache immediately so there's no animation.</p>
|
Should I migrate local JSON database to MariaDB? <h3>Fictional story:</h3>
<p>I have a car website containing over 200,000+ car listings around the United States. I get my data from two sources CarSeats and CarsPro updated nightly. Both sources contain about 100,000 detailed listings each in JSON format. The file size of both feeds is about 8GB and I plan to incorporate more used car sources in the near future.</p>
<p>The current JSON data contains everything I need to display car info from car search to car purchase, however, the JSON DB is stored locally and I use PHP's <code>file_get_contents()</code> to grab the appropriate metadata for each listing. It takes about 8 to 12 seconds to return 200 cars which is not bad, but I know there is room for improvement.</p>
<h3>My Question:</h3>
<p>Will migrating my data from localized JSON files to MariaDB 10.1 be a best practice move? Is that the scalable alternative for the future?
What should my stack look like to improve speed and improve search capabilities?</p>
<p><strong>Note:</strong> </p>
<ul>
<li>Forge installs MariaDB on the instance you boot.</li>
<li>The 8GB is chunked by "car make" into over 20 different files. No individual file is larger than 400MB.</li>
</ul>
<p>Currently using</p>
<ul>
<li>Laravel 5.2</li>
<li>Forge</li>
<li>PHP 5.6.10</li>
<li>Servers from AWS</li>
</ul>
| <blockquote>
<p>Will migrating my data from localized JSON files to MariaDB 10.1 be a
best practice move? Is that the scalable alternative for the future?
What should my stack look like to improve speed and improve search
capabilities?</p>
</blockquote>
<p>Yes. The whole purpose of a database is to make the storageâand usageâof data like this easier in the long run.</p>
<p>Each time you load a JSON file in PHP, PHP has to parse the data and I highly doubt 200,000 listings that consist of 8GB of data will ever work well as a file loaded into PHP memory from the file system. PHP will most likely die (aka: throw up an error) just when you attempt to load the file to begin with. Sorting and manipulating that data in PHP in that low-level state is even less efficient.</p>
<p>Storing that JSON data in a database of some kindâMariaDB, MySQL, MongoDB, etcâ¦âis the only practical and best practice way to handle something like this.</p>
<p>The main reason anyone would repeatedly load a local JSON file into PHP would be for small tests and development ideas. On a practical level, itâs inefficient but when you are in an early stage of development and donât feel like dealing with creating a process to import a large JSON file like that into an actual database a small sample file of data can be useful from your developerâs perspective to hash out basic concepts and idea.</p>
<p>But there is utterly no âbest practiceâ that would ever state a file being read from a filesystem is a âbest practiceâ; itâs honestly a very bad idea.</p>
|
How do I create an animated gif in Python using Wand? <p>The instructions are simple enough in the <a href="http://docs.wand-py.org/en/0.4.1/guide/sequence.html" rel="nofollow">Wand docs</a> for <em>reading</em> a sequenced image (e.g. animated gif, icon file, etc.):</p>
<pre><code>>>> from wand.image import Image
>>> with Image(filename='sequence-animation.gif') as image:
... len(image.sequence)
</code></pre>
<p>...but I'm not sure how to <em>create</em> one. </p>
<p>In Ruby this is easy using <strong>RMagick</strong>, since you have <code>ImageList</code>s. (see <a href="https://gist.github.com/dguzzo/99bbca3df827df475f768383a1b04102" rel="nofollow">my gist</a> for an example.)</p>
<p>I tried creating an <code>Image</code> (as the "container") and instantiating each <code>SingleImage</code> with an image path, but I'm pretty sure that's wrong, especially since the constructor documentation for <code>SingleImage</code> doesn't look for use by the end-user.</p>
<p>I also tried creating a <code>wand.sequence.Sequence</code> and going from that angle, but hit a dead-end as well. I feel very lost.</p>
| <p>The best examples are located in the unit-tests shipped with the code. <a href="https://github.com/dahlia/wand/blob/master/tests/sequence_test.py" rel="nofollow"><code>wand/tests/sequence_test.py</code></a> for example.</p>
<p>For creating an animated gif with wand, remember to load the image into the sequence, and then set the additional delay/optimize handling after all frames are loaded.</p>
<pre class="lang-py prettyprint-override"><code>from wand.image import Image
with Image() as wand:
# Add new frames into sequance
with Image(filename='1.png') as one:
wand.sequence.append(one)
with Image(filename='2.png') as two:
wand.sequence.append(two)
with Image(filename='3.png') as three:
wand.sequence.append(three)
# Create progressive delay for each frame
for cursor in range(3):
with wand.sequence[cursor] as frame:
frame.delay = 10 * (cursor + 1)
# Set layer type
wand.type = 'optimize'
wand.save(filename='animated.gif')
</code></pre>
<p><a href="https://i.stack.imgur.com/do522.gif" rel="nofollow"><img src="https://i.stack.imgur.com/do522.gif" alt="output animated.gif"></a></p>
|
How to optimize employee transport service? <p>Gurus,</p>
<p>I am in the process of writing some code to optimize employee transport for corporate. I need all you expert's advice on how can this be achieved. Here is my scenario.</p>
<p>There are 100 pick up points all over city from where employees need to be brought to company with multiple vehicles. Each vehicle can occupy say 4 or 6 employees. My objective is to write some code which will group the people from nearby areas and bring them to company. Master data will have addresses and its latitude/longitude. I want to build an algorithm to optimize vehicle occupancy as well as distance and time. Could you guys please give some directions how can this be achieved. I understand I may need to use google maps or direction API for this but looking for some logic hint/advice how this can be achieved. </p>
<p>Some more inputs: These vehicles are of company's vehicle with driver. Travel time should not be more than 1.5 Hrs.</p>
<p>Thanks in advance.</p>
| <p>Your problem description is a more complicated version of "The travelling salesman problem". You can look it up on and find some different examples and how they are implemented.</p>
<p>One point that need to be clarified : the vehicules to be use will be the employee vehicule that will be carshared or it will be company's vehicule with a driver?</p>
<p>You also need to define some time constrain. For example 50 employees should have under 30 min travel, 40 employe under 1h travel and 10 employe under 1,5H.</p>
<p>You also need to define the travel time for each road depending of the time, because at different time there will be traffic jam or not.</p>
<p>You also need to define group within the employee: usually people (admin clerck or CEO) in a company don't commute at the same time, it can have 1 hour range or more.</p>
<p>In fine, don't forget to include about 10% of the employee that wil be 2 to 5 min late to their meeting point.</p>
|
How to make hotkeys in VB6? <p>I've some problem, i'm planning to make a form can hide itself and the form can show again (activate it only with a hotkey). what's the source code for my problem?</p>
| <p>Declare with this</p>
<pre><code>Dim i As Integer
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
</code></pre>
<p>then make a timer</p>
<pre><code>Private Sub Timer1_Timer()
If GetAsyncKeyState(vbKeyControl) And GetAsyncKeyState(vbKeyR) Then
Frmsav.Show
End If
End Sub
</code></pre>
<p>that code using Ctrl + R to show your form </p>
|
What is the best way to fetch huge data from mysql with sqlalchemy? <p>I want to process over 10 millions data stored in MySQL. So I wrote this to slice the sql to several parts then concatenate the data for latter process. It works well if <code>count < 2 millions</code>. However when the <code>count</code> rise, the time sqlalchemy consumes goes much longer.</p>
<pre><code>def fetch_from_sql(_sql_pat, count):
"""
:param _sql_pat: SELECT id, data FROM a.b LIMIT {},{};
:param count: how many data you want to fetch from mysql
:return: generator
"""
def gen_connect(sql):
__engine = create_engine(db_config['SQLALCHEMY_DATABASE_URI'])
with __engine.connect() as c:
for row in c.execute(sql)
yield row
def gen_range(limit, step):
if step > limit:
yield 0, limit
else:
R = range(0, limit + 1, step)
for idx, v in enumerate(R):
if idx == 0:
yield v, step
elif limit - v >= step:
yield v + 1, step
else:
yield v + 1, limit - v
sqls = [_sql_pat.format(start, step) for start, step in gen_range(count, 100000)]
sources = (gen_connect(sql) for sql in sqls)
for s in sources:
for item in s:
yield item
gc.collect()
</code></pre>
<p>The <strong>question</strong> is why the sqlalchemy take more and more time (I logged time and post below), and what is the best way to deal with this situationï¼</p>
<pre><code>Dumped 10000 items, at 2016-10-08 11:55:33
Dumped 1000000 items, at 2016-10-08 11:59:23
Dumped 2000000 items, at 2016-10-08 12:05:07
Dumped 3000000 items, at 2016-10-08 13:54:05
</code></pre>
| <p>This is because you're using <code>LIMIT</code>/<code>OFFSET</code>, so when you specify offset 3000000, for example, the database has to skip over 3000000 records.</p>
<p>The correct way to do this is to <code>ORDER BY</code> some indexed column, like the primary key <code>id</code> column, for example, then do a <code>WHERE id > :last_fetched_id</code>.</p>
|
Python Regex for ignoring a sentence with two consecutive upper case letters <p>I have a simple problem at hand to ignore the sentences that contain two or more consecutive capital letters and many more grammar rules .</p>
<p><strong>Issue:</strong> By the definition the regex should not match the string <code>'This is something with two CAPS.'</code> , but it does match.</p>
<p><strong>Code:</strong> </p>
<pre><code>''' Check if a given sentence conforms to given grammar rules
$ Rules
* Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.)
* Then lowercase character follows.
* There must be spaces between words.
* Then the sentence must end with a full stop(.) after a word.
* Two continuous spaces are not allowed.
* Two continuous upper case characters are not allowed.
* However the sentence can end after an upper case character.
'''
import re
# Returns true if sentence follows these rules else returns false
def check_sentence(sentence):
checker = re.compile(r"^((^(?![A-Z][A-Z]+))([A-Z][a-z]+)(\s\w+)+\.$)")
return checker.match(sentence)
print(check_sentence('This is something with two CAPS.'))
</code></pre>
<p><strong>Output:</strong></p>
<pre><code><_sre.SRE_Match object; span=(0, 32), match='This is something with two CAPS.'>
</code></pre>
| <p>Itâs probably easier to write your regex in the negative (find all sentences that are bad sentences) than it is in the positive. </p>
<pre><code>checker = re.compile(r'([A-Z][A-Z]|[ ][ ]|^[a-z])')
check2 = re.compile(r'^[A-Z][a-z].* .*\.$')
return not checker.findall(sentence) and check2.findall(sentence)
</code></pre>
|
Are There Alternatives to Collision Detection in Unity3D? <p>So, I'm working on a game and I've run in to the problem that.. I'm trying to detect the collision of two objects, and at first I assumed I needed two colliders. Then I found out I needed a rigid body, now I've come to find both object need a rigid body and this is a lot of cpu usage and the rigid bodies serve only to detect these collisions. It vastly limits how many objects I can have in a scene.</p>
<p>The only solution I can thin of is to be cast small rays from each side. Are there any other industry standard solutions that are more optimal?</p>
<p>Thanks in advance</p>
| <p>There's no way to do exactly what you want. As you did not describe what you are planning to do (not even if 2D or 3D), here's a generic solution:<br>
1) Attach a <code>Rigidbody</code> to only to one of the objects (out of two which could collide)<br>
2) Tick in <code>IsKinematic</code> on <code>Rigidbody</code>so it won't react on Physics<br>
3) Tick in <code>isTrigger</code> on the other object's Collider (so it won't need a <code>Rigidbody</code> yet fires away trigger events when hits another object with a <em>non-trigger</em>(!!!) collider (<em>and</em> a Rigidbody)
<br><br>(<em>Or use <code>Rigidbody</code> on all your GOs, yet tick in <code>IsKinematic</code> on all of them</em>)<br><br><br>
As of your own collision detection, see @Hellium's comment.
<br>I would add that, if you code your own collision detection, at the end of the day you'll most probably end up with a code eating more calc. time (and probably being at least a bit more sloppy).<br>
Simply because you'll code in script, not C++ and the engine's Collision Detection is C++. (Your .net script will compile to native via il2cpp, so not a native implementation == must be slower than the code having similar nature, yet supported by the engine, i.e. coded in c++)<br><br></p>
<p>Side note: If you find your app. running slow, that's not necessarily because of collision detection. It's not impossible it's <em>your code</em>, what <em>you do</em> when you detect collision is running slow.<br>
I highly recommend using <a href="https://unity3d.com/learn/tutorials/topics/interface-essentials/introduction-profiler" rel="nofollow">the profiler</a> to see what slows things down in your application.<br>
If it really is your code, post a question on how to make that run faster.</p>
|
Select columns for ORDER BY only, not returning them in the results <p>So I have a complicated <code>INSERT</code> query which puts information into a relational table based on information pulled from another table and with given variables.</p>
<p>Here's the query:</p>
<pre><code>INSERT INTO relational (class_id, teacher_id, student_id)
VALUES (
(SELECT `id`,
(`name` = "John Smith") as exact_score,
(`name` RLIKE "[[:<:]]John Smith[[:>:]]") as reg_score,
(MATCH (`name`) AGAINST ("John Smith")) as match_score
FROM `teachers`
WHERE (`title` RLIKE "[[:<:]]John Smith[[:>:]]" || MATCH (`title`) AGAINST ("John Smith"))
ORDER BY
CASE WHEN exact_score = 1 THEN exact_score END DESC,
CASE WHEN reg_score > 1 THEN reg_score END DESC,
CASE WHEN reg_score = 0 AND exact_score = 0 THEN match_score END DESC),
1, 1);
</code></pre>
<p>The regex is required because the name might be <code>Mr. John Smith</code> or <code>John Smith PH.d</code>, and the match is required because the name might be <code>jon smith</code> When the stored name is actually just <code>John Smith</code>.</p>
<p>The select query yields the results I am looking for 90% of the time, but the only real <em>column</em> that I need from it is <code>id</code>. The problem I'm running into is with the INSERT's expected column count vs. the column count that is returned by the query.</p>
<p>Right now the INSERT basically looks like this:</p>
<pre><code>INSERT INTO relational (class_id, teacher_id, student_id) VALUES ({{returned id (desired)}}, {{exact score (undesired)}}, {{reg score (undesired)}}, {{match score (undesired)}}, 1, 1);
</code></pre>
<p>The last <code>1, 1</code> is provided by variables.</p>
<p>My question is, is there a way to select columns for the sake of ORDER BY, but then to omit them from the results?</p>
| <p>If the column is defined in a table/view, you can use it in <code>ORDER BY</code> and omit it from results. But in your case, you are using <em>calculated columns</em> in <code>ORDER BY</code>, so if you want to omit these columns, you have to replace them in <code>ORDER BY</code> with corresponding formula, e.g. </p>
<pre><code>ORDER BY
CASE WHEN (`name` = "John Smith") = 1 THEN (`name` = "John Smith") END DESC
-- etc...
</code></pre>
<p>I think this is not a good solution. Instead, It's better to use subquery:</p>
<pre><code>INSERT INTO relational (class_id, teacher_id, student_id)
SELECT id,1,1 FROM
(SELECT `id`,
(`name` = "John Smith") as exact_score,
(`name` RLIKE "[[:<:]]John Smith[[:>:]]") as reg_score,
(MATCH (`name`) AGAINST ("John Smith")) as match_score
FROM `teachers`
WHERE (`title` RLIKE "[[:<:]]John Smith[[:>:]]" || MATCH (`title`) AGAINST ("John Smith"))
ORDER BY
CASE WHEN exact_score = 1 THEN exact_score END DESC,
CASE WHEN reg_score > 1 THEN reg_score END DESC,
CASE WHEN reg_score = 0 AND exact_score = 0 THEN match_score END DESC)
AS t1;
</code></pre>
|
maintain, cleanup, compress large number of git repositories in Ubuntu <p>By going through the below git documentation, I learned how to maintain, cleanup, compress and save space for a git repository. But the problem I am facing is, having a large number of git repositories, say around ( 500 ) of them, Its not easy to visit each repository and do these clean up things, is there an automated way to visit each repository and clean up or compress each repository ?</p>
<p>a shell script or something like that ?</p>
<p><a href="https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery" rel="nofollow">https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery</a></p>
| <blockquote>
<p>a shell script or something like that ?</p>
</blockquote>
<p>There is nothing in Git itself for managing <em>multiple</em> repos, so yes, you would need to script the process you are currently doing for one repo.</p>
<p>See for instances the approaches taken in:</p>
<ul>
<li>"<a href="http://stackoverflow.com/q/11981716/6309">How to quickly find all git repos under a directory?</a></li>
<li>"<a href="http://stackoverflow.com/q/961101/6309">git: Find all uncommited locals repos in a directory tree</a>"</li>
</ul>
<p>Once you can find all your repos, you can apply the same set of commands you are currently using for one repo to compress and optimize said repo.</p>
|
Modifying search function to exclude posts and limit results to 10 per page on front end only <p>This problem is kind of two part. I have the solution to exclude posts from the search and limit the results to 10 results per page but the problem is it also affects the backend wp-admin area. So if i search for posts through the wp-admin area the posts will be excluded even though I only want this to occur for users who are not admin. This is the code I have for excluding posts and limiting the results to 10:</p>
<pre><code>function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
function change_wp_search_size($query) {
if ( $query->is_search ) // Make sure it is a search page
$query->query_vars['posts_per_page'] = 10;
return $query;
}
add_filter('pre_get_posts', 'change_wp_search_size');
</code></pre>
<p>Now I have done a little bit of reading and research on stack and other sites and it looks like there is a way to only trigger these functions only after checking if admin is logged in. I'll reference to the <a href="https://codex.wordpress.org/Function_Reference/is_admin" rel="nofollow">wordpress codex</a> for the is_admin function </p>
<p>This is the way I attempted to use the is_admin function which caused an http error 500. Please excuse me if the code is grossly incorrect:</p>
<pre><code>if ( !is_admin() ) {
function SearchFilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
if ( !is_admin() ) {
function change_wp_search_size($query) {
if ( $query->is_search && !is_admin() )
$query->query_vars['posts_per_page'] = 10;
return $query;
}
add_filter('pre_get_posts', 'change_wp_search_size');
</code></pre>
<p>I'm hoping that I'm close and just need some tweaking for the code </p>
<p>Edit:
So now this is what i have for both functions. I know its my php code which is the problem can you help further please:</p>
<pre><code>function SearchFilter($query) {
if ( is_admin () ) {
return $query;
}
else {
($query->is_search) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
function change_wp_search_size($query) {
if ( is_admin () ) {
return $query;
}
if ( $query->is_search ) // Make sure it is a search page
$query->query_vars['posts_per_page'] = 10;
return $query;
}
add_filter('pre_get_posts', 'change_wp_search_size');
</code></pre>
<p>EDIT 2: Pastebin of the entire function.php file <a href="http://pastebin.com/tTEnHGp2" rel="nofollow">http://pastebin.com/tTEnHGp2</a></p>
| <p>Okay don't wrap your search functions around the <em>is_admin()</em> instead put the <em>is_admin()</em> inside the function</p>
<p>Like this:</p>
<pre><code>Function search(){
if ( is_admin()){
//Search query for admin
}
else {
//Search query for users
}
}
</code></pre>
<p>That should do it</p>
|
save image from image tag <img> using POST service call using jquery <p>Am trying to save image from image tag</p>
<p>i have tried like file upload method </p>
<p>but it not working ,</p>
<pre><code> var request = new XMLHttpRequest();
var imageUrl = info.ImageUri + '/Upload?imagePath=' + imagePath + '&imageName=' + imagename + '&imageSize=' + imagesize;
var imageFileUri;
request.open('POST', imageUrl);
request.send(imgFile.files[0]);
request.onreadystatechange = function () {
if (request.readyState == 4) {
if (request.status == 200) {
</code></pre>
<p>is there any way to save image which is already displaying in the image tag?</p>
| <p>You can get the base64 string from the image.</p>
<p>html:</p>
<pre><code><img src="http://some/image/source" id="myImage"/>
<canvas id="myCanvas" style="display:none;"/>
</code></pre>
<p>js:</p>
<pre><code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("myImage");
ctx.drawImage(img, 10, 10);
var imgString = c.toDataURL();
$.ajax({
type: "POST",
dataType: "JSON",
data: {
imageString: imgString
}
url: "/route/to/store/my/image",
success: function (data) {
alert('success');
}
});
</code></pre>
<p>and in server side make an image from base64 string and store it with a file name. :)</p>
|
WinForms ListView Details Column Rendering Issue <p>I have a simple WinForms ListView that is set to display in Details view with a few items.</p>
<p>Maybe this is a well-known issue with an easy fix but I can't seem to get this to look right:</p>
<p><a href="http://i.stack.imgur.com/L2rv8.png" rel="nofollow"><img src="http://i.stack.imgur.com/L2rv8l.png" alt="Zoomed-in screenshot of the ListView (click to embiggen)"></a></p>
<p>The column gridlines are slightly off.</p>
<p>Here's the relevant code:</p>
<pre class="lang-cs prettyprint-override"><code>partial class MainForm
{
private void InitializeComponent()
{
this.listView = new System.Windows.Forms.ListView();
this.SuspendLayout();
//
// listView
//
this.listView.FullRowSelect = true;
this.listView.GridLines = true;
this.listView.Location = new System.Drawing.Point(13, 13);
this.listView.MultiSelect = false;
this.listView.Name = "listView";
this.listView.Size = new System.Drawing.Size(539, 150);
this.listView.TabIndex = 0;
this.listView.UseCompatibleStateImageBehavior = false;
this.listView.View = System.Windows.Forms.View.Details;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(564, 185);
this.Controls.Add(this.listView);
this.Name = "MainForm";
this.Text = "Main Form";
this.ResumeLayout(false);
}
private System.Windows.Forms.ListView listView;
}
</code></pre>
<p>Has anyone seen this? I haven't used the ListView control before but I have noted more than a few problems with it here on the Internet. I haven't yet found anything specifically about this problem, though.</p>
<p>NOTE: Unfortunately, I cannot use any third-party controls as a solution to this, only stock-standard WinForms.</p>
| <p>You should use DatagridView control for multiple column, else look this link <a href="http://csharp.net-informations.com/gui/cs-listview.htm" rel="nofollow">http://csharp.net-informations.com/gui/cs-listview.htm</a> ;)</p>
|
Returning index of an array based on mixture of values(integer,string) or (integer,float) <p>Hi I am trying to find a index for a number in percentage and integer array. Say <code>arraynum = ['10%','250','20%','500']</code> and user sends a value <code>15%</code>,in which range does this number resides? I could find index for a integer number using this code</p>
<pre><code> function test(number, ranges) {
for (var i = 0; i < ranges.length; ++i) {
if (number < ranges[i]) {
return i;
}
}
}
var ranges = [2000, 4000, 6000, 999999];
console.log(test(1710, ranges));
</code></pre>
<p>Now I have <strong>mixture of integer and percentage value</strong> inside a array and number that a user pass to this function can be a integer,decimal or percentage How to find in which index does the given number resides? Should I convert all value in the mixture array to some format? How to do this? Can someone please help me with this? Thanks in advance.</p>
| <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat" rel="nofollow"><code>parseFloat()</code></a> to get the floating-point value of a string. You can use the fact that it only parses up until the first non-numeric character in the string in order to ignore the <code>%</code>.</p>
<p>Here is an implementation using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="nofollow"><code>Array#findIndex</code></a> from ES6.</p>
<pre><code>function test(number, ranges) {
var num = parseFloat(number);
return ranges.findIndex(function(element) {
return num === parseFloat(element);
});
}
</code></pre>
|
MySQL Group by complex script <p>I have an script that works perfect, but need to add values from another table
Current script is</p>
<pre><code> select v.id, vm.producto_id, sum(vm.total), count(v.id)
from visita v, reporte r, visitamaquina vm, maquina m,
(select r.id, empleado_id, fecha, cliente_id from ruta r, rutacliente rc where r.id=rc.ruta_id and
fecha>='2016-10-01' and fecha<='2016-10-30' group by fecha, cliente_id, empleado_id) as rem
where rem.fecha=v.fecha and v.cliente_Id=rem.cliente_id and r.visita_id=v.id and vm.visita_id=v.id and m.id=vm.maquina_id
group by vm.visita_id, vm.producto_id
</code></pre>
<p>Current Script returns this (I need some extra columns but for this purpose I only leave the ones with issues):</p>
<pre><code>| Producto_Id | Id | Total | count(id) |
|---------------|--------------|-----------|-----------|
| 1 | 31 | 21 | 2 |
| 2 | 31 | 15 | 3 |
| 3 | 31 | 18 | 2 |
</code></pre>
<p>Table VisitaMaquina has multiple records for same producto_id
VisitaMaquina has this:</p>
<pre><code>| Producto_Id | Visita_Id | Total |
|---------------|--------------|-----------|
| 1 | 31 | 8 |
| 1 | 31 | 13 |
| 2 | 31 | 9 |
</code></pre>
<p>Same situation happens with table called reporteproducto, where multiple times producto_id is repeated.</p>
<p>Table reporteproducto has</p>
<pre><code>| Producto_Id | Visita_Id | Quantity |
|---------------|--------------|-----------|
| 1 | 31 | 4 |
| 1 | 31 | 7 |
| 2 | 31 | 5 |
</code></pre>
<p>My previous query works fine, and I just need to get the sum of quantity</p>
<p>I used this Script and this is what I got</p>
<pre><code> select v.id, vm.producto_id, sum(vm.total), sum(quantity), count(id)
from visita v, reporte r, visitamaquina vm, maquina m, reporteproducto rp,
(select r.id, empleado_id, fecha, cliente_id from ruta r, rutacliente rc where r.id=rc.ruta_id and
fecha>='2016-10-01' and fecha<='2016-10-30' group by fecha, cliente_id, empleado_id) as rem
where rem.fecha=v.fecha and v.cliente_Id=rem.cliente_id and r.visita_id=v.id and vm.visita_id=v.id and m.id=vm.maquina_id and rp.visita_Id=v.id and rp.producto_id=vm.producto_id
group by vm.visita_id, vm.producto_id
</code></pre>
<p>I got this</p>
<pre><code>|Producto_Id | Visita_Id | Total |Quantity | count(id)
|---------------|--------------|-----------|-----------|-----------|
| 1 | 31 | 42 | 11 | 4 |
| 2 | 31 | 45 | 18 | 6 |
| 3 | 31 | 36 | 44 | 4 |
</code></pre>
<p>The desired result is (focus on producto_id=1):</p>
<pre><code>|Producto_Id | Visita_Id | Total |Quantity |
|---------------|--------------|-----------|-----------|
| 1 | 31 | 21 | 11 |
| 2 | 31 | 15 | 18 |
| 3 | 31 | 18 | 44 |
</code></pre>
<p>Any Idea on how to solve this?</p>
| <p>Better group the sub table that has multiple data with the same group of your outer group by columns.In your case the <code>VisitaMaquina</code> and <code>reporteproducto</code> should be group by with <code>visita_id, producto_id</code> since they all have repeat rows with the same combination of <code>vid=31 and pid=1</code>. </p>
<p>You can change the <code>visitamaquina vm</code> and <code>reporteproducto rp</code> table alias to sub query form of the following:</p>
<pre><code>(select visita_id, Producto_Id, sum(Total) as Total from visitamaquina
group by visita_id, Producto_Id) vm,
(select Producto_Id, Visita_Id, sum(Quantity) as Quantity from reporteproducto
group by Producto_Id, Visita_Id) rp
</code></pre>
<p>Also I found that there is <code>vm.maquina_id</code> in your where clause, maybe this causes your problem.Because if the <code>visitamaquina</code> and <code>reporteproducto</code> both have repeat values of <code>visita_id, producto_id</code> then the output should have <code>Total, Quantity</code> both doubled.In your output the <code>Quantity</code> is right, that's odd.</p>
|
Emulator does not run on avd manager <p>I created an emulator with API 23 in AVD manager. But when I want to start it, it does not work. </p>
<p>And at the bottom shows me this Error:</p>
<blockquote>
<p>Starting emulator for AVD 'Emulator_6.0'
/home/hadi/Android/Sdk/tools/emulator: 1: /home/hadi/Android/Sdk/tools/emulator: Syntax error: "(" unexpected</p>
</blockquote>
| <p>Try deleting and redownloading the emulator.</p>
|
Retrieve data from two table <p>I have two tables <code>tblRegistration(id,name,program,regdno,address)</code> and <code>tblDue(id,regdno,amountdue)</code>. What I want is to pass regdno from a <code>textbox</code> and then retrieve the <code>name</code>, <code>program</code> values form <code>tblRegistration</code> and <code>amountdue</code> from <code>tblDue</code>.</p>
<p>What i tried is ,</p>
<pre><code>select t1.name,t1.program, t2.amountdue
from tblRegistration as t1
inner join tblDue as t2 on t2.regdno= t1.regdno;
</code></pre>
<p>It returns all values having same <code>regdno</code> in both tables. </p>
<p>Help me on getting those values only whose <code>regdno</code> I provide from textbox.</p>
<p>Sorry for the language. Thank you in advance.</p>
| <p>If you haven't any relationship between Registration and Due table. you mustn't join these table. You can Simple run two query to fetch data. the first, from Registration table and the second, from Due table:</p>
<pre><code>select * from tblReg where regdno=...;
select * from tblDue where regdno=...;
</code></pre>
|
How to implement search in list in given listView using edit text <p>I am creating an app.I have three data in one row (Name,id,other) of list view. so I want to implement search on list view by name using edit text. I am getting search data by name its good but id is not change according to name on search its still showing fix just like(1,2,3...) in list view.So i want when i search by name then id should be show according to name.</p>
<p>//MainActicity</p>
<pre><code>public class MainActivity extends AppCompatActivity {
private ListView mSearchNFilterLv;
private EditText mSearchEdt;
private ArrayList<String> mStringList;
private ArrayList<String> mStringList1;
private ValueAdapter valueAdapter;
private TextWatcher mSearchTw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initData();
valueAdapter=new ValueAdapter(mStringList,mStringList1,this);
mSearchNFilterLv.setAdapter(valueAdapter);
mSearchEdt.addTextChangedListener(mSearchTw);
}
private void initData() {
mStringList=new ArrayList<String>();
mStringList.add("one");
mStringList.add("two");
mStringList.add("three");
mStringList.add("four");
mStringList.add("five");
mStringList.add("six");
mStringList.add("six");
mStringList.add("six");
mStringList.add("six");
mStringList.add("seven");
mStringList.add("eight");
mStringList.add("nine");
mStringList.add("ten");
mStringList.add("eleven");
mStringList.add("twelve");
mStringList.add("thirteen");
mStringList.add("fourteen");
mStringList1=new ArrayList<String>();
mStringList1.add("1");
mStringList1.add("2");
mStringList1.add("3");
mStringList1.add("4");
mStringList1.add("5");
mStringList1.add("6");
mStringList1.add("7");
mStringList1.add("8");
mStringList1.add("9");
mStringList1.add("10");
mStringList1.add("11");
mStringList1.add("12");
mStringList1.add("13");
mStringList1.add("15");
mStringList1.add("16");
mStringList1.add("17");
mSearchTw=new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
valueAdapter.getFilter().filter(s);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
}
private void initUI() {
mSearchNFilterLv=(ListView) findViewById(R.id.list_view);
mSearchEdt=(EditText) findViewById(R.id.txt_search);
}
}
</code></pre>
<p>//value adapter</p>
<pre><code> public class ValueAdapter extends BaseAdapter implements Filterable {
private ArrayList<String> mStringList;
private ArrayList<String> mStringList1;
private ArrayList<String> mStringFilterList;
private LayoutInflater mInflater;
private ValueFilter valueFilter;
public ValueAdapter(ArrayList<String> mStringList,ArrayList<String> mStringList1,Context context) {
this.mStringList=mStringList;
this.mStringList1=mStringList1;
this.mStringFilterList=mStringList;
mInflater=LayoutInflater.from(context);
getFilter();
}
//How many items are in the data set represented by this Adapter.
@Override
public int getCount() {
return mStringList.size();
}
//Get the data item associated with the specified position in the data set.
@Override
public Object getItem(int position) {
return mStringList.get(position);
}
//Get the row id associated with the specified position in the list.
@Override
public long getItemId(int position) {
return position;
}
//Get a View that displays the data at the specified position in the data set.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder viewHolder;
if(convertView==null) {
viewHolder=new Holder();
convertView=mInflater.inflate(R.layout.list_item,null);
viewHolder.nameTv=(TextView)convertView.findViewById(R.id.txt_listitem);
viewHolder.nameTv1=(TextView)convertView.findViewById(R.id.txt_listitem1);
convertView.setTag(viewHolder);
}else{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.nameTv.setText(mStringList.get(position).toString());
viewHolder.nameTv1.setText(mStringList1.get(position).toString());
return convertView;
}
private class Holder{
TextView nameTv;
TextView nameTv1;
}
//Returns a filter that can be used to constrain data with a filtering pattern.
@Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint!=null && constraint.length()>0){
ArrayList<String> filterList=new ArrayList<String>();
for(int i=0;i<mStringFilterList.size();i++){
if(mStringFilterList.get(i).contains(constraint)) {
filterList.add(mStringFilterList.get(i));
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=mStringFilterList.size();
results.values=mStringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
Filter.FilterResults results) {
mStringList=(ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
</code></pre>
<p>When i search by name that time id should be show according according to name in list view.</p>
<p>Thanks.</p>
| <p>You can apply a constraint to <strong>EditText</strong>, if a number is entered it reads the item at that position of <strong>ListView</strong>. </p>
|
Fatal Exception: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v7.internal.view.menu.ExpandedMenuView <p>I am getting below error and problem is that I donât see any familiar names or my classes in the error message nor in stack trace. The other difficulty is that I still cannot reproduce this crash on my devices, so I donât know what action may cause it.</p>
<p>Here is the full stack trace:</p>
<pre><code>Fatal Exception: android.view.InflateException: Binary XML file line #17: Error inflating class android.support.v7.internal.view.menu.ExpandedMenuView
at android.view.LayoutInflater.createView(LayoutInflater.java:613)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.support.v7.internal.view.menu.ListMenuPresenter.getMenuView(ListMenuPresenter.java:102)
at android.support.v7.app.AppCompatDelegateImplV7$PanelFeatureState.getListMenuView(AppCompatDelegateImplV7.java:1908)
at android.support.v7.app.AppCompatDelegateImplV7.initializePanelContent(AppCompatDelegateImplV7.java:1203)
at android.support.v7.app.AppCompatDelegateImplV7.openPanel(AppCompatDelegateImplV7.java:1045)
at android.support.v7.app.AppCompatDelegateImplV7.onKeyUpPanel(AppCompatDelegateImplV7.java:1410)
at android.support.v7.app.AppCompatDelegateImplV7.onKeyUp(AppCompatDelegateImplV7.java:877)
at android.support.v7.app.AppCompatDelegateImplV7.dispatchKeyEvent(AppCompatDelegateImplV7.java:871)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:226)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1876)
at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:4196)
at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:4139)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3199)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5427)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Constructor.java)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.support.v7.internal.view.menu.ListMenuPresenter.getMenuView(ListMenuPresenter.java:102)
at android.support.v7.app.AppCompatDelegateImplV7$PanelFeatureState.getListMenuView(AppCompatDelegateImplV7.java:1908)
at android.support.v7.app.AppCompatDelegateImplV7.initializePanelContent(AppCompatDelegateImplV7.java:1203)
at android.support.v7.app.AppCompatDelegateImplV7.openPanel(AppCompatDelegateImplV7.java:1045)
at android.support.v7.app.AppCompatDelegateImplV7.onKeyUpPanel(AppCompatDelegateImplV7.java:1410)
at android.support.v7.app.AppCompatDelegateImplV7.onKeyUp(AppCompatDelegateImplV7.java:877)
at android.support.v7.app.AppCompatDelegateImplV7.dispatchKeyEvent(AppCompatDelegateImplV7.java:871)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:226)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1876)
at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:4196)
at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:4139)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3199)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5427)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f01012b a=4}
at android.content.res.Resources.loadDrawable(Resources.java:2343)
at android.content.res.TypedArray.getDrawable(TypedArray.java:604)
at android.widget.AbsListView.<init>(AbsListView.java:810)
at android.widget.ListView.<init>(ListView.java:147)
at android.widget.ListView.<init>(ListView.java:143)
at android.support.v7.internal.view.menu.ExpandedMenuView.<init>(ExpandedMenuView.java:54)
at android.support.v7.internal.view.menu.ExpandedMenuView.<init>(ExpandedMenuView.java:50)
at java.lang.reflect.Constructor.constructNative(Constructor.java)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.support.v7.internal.view.menu.ListMenuPresenter.getMenuView(ListMenuPresenter.java:102)
at android.support.v7.app.AppCompatDelegateImplV7$PanelFeatureState.getListMenuView(AppCompatDelegateImplV7.java:1908)
at android.support.v7.app.AppCompatDelegateImplV7.initializePanelContent(AppCompatDelegateImplV7.java:1203)
at android.support.v7.app.AppCompatDelegateImplV7.openPanel(AppCompatDelegateImplV7.java:1045)
at android.support.v7.app.AppCompatDelegateImplV7.onKeyUpPanel(AppCompatDelegateImplV7.java:1410)
at android.support.v7.app.AppCompatDelegateImplV7.onKeyUp(AppCompatDelegateImplV7.java:877)
at android.support.v7.app.AppCompatDelegateImplV7.dispatchKeyEvent(AppCompatDelegateImplV7.java:871)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:226)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1876)
at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:4196)
at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:4139)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3199)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5427)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(NativeStart.java)
</code></pre>
| <p>You are using wrong resource in your xml. Probably you are trying to use color resource as a drawable (i.e. <code>@color/</code> instead of <code>@drawable/</code>.
If you can not reproduce it yourself, you can recheck your xml and replace any color usage with drawable one.
Also, it might be because you put your drawable in wrong folder (i.e. <code>drawable-v21</code> and trying to run application on API 19)
Thus, recheck your xml.</p>
|
How to use xpath to get the text <p>I am new to Html and XPath. So I got this trouble.
If I want to get the text 'Saturday', what the xpath code should be like?
Thank you for your help!
The html like this.</p>
<pre><code><div class="D(ib) Va(m) W(1/4)" data-reactid=".28cjlo02kxy.$tgtm-Col1-0-Weather.2.$0.$0.1.1.$0.0">
<span data-reactid=".28cjlo02kxy.$tgtm-Col1-0-Weather.2.$0.$0.1.1.$0.0.0">Saturday
</span></div>
</code></pre>
<p>and then, if I want to get the title="Showers", what should I do next?</p>
<pre><code><span data-code="11" class="D(ib) Va(m) W(1/4) Ta(c)" data-reactid=".28cjlo02kxy.$tgtm-Col1-0-Weather.2.$0.$0.1.1.$1.1">
<img alt="Showers" height="32" title="Showers" width="32" class="Trsdu(.42s) " src="/sy/os/weather/1.0.1/shadow_icon/60x60/rain_day_night@2x.png" data-reactid=".28cjlo02kxy.$tgtm-Col1-0-Weather.2.$0.$0.1.1.$1.1.0"></span>
</code></pre>
| <p>Well, there is not enough information to provide a reliable XPath, but, given what we have, I'd have a partial match on <code>data-reactid</code> attribute(s):</p>
<pre><code>//div[contains(@data-reactid, "Col1-0-Weather")]/span[contains(@data-reactid, "Col1-0-Weather")]
</code></pre>
|
C Why when passing this int by value, it is incorrectly passing 0 every time <p>Ok so sorry for the length of the code block, but I am at a loss. The variable currentProcess holds the index of the last structue added to the array. I have included print statements to prove that the value of currentProcess is being incremented correctly as elements are being added. However, when I then pass this variable to the function printCurrent() it passes the value 0. I included the whole program as it stands, because I have no idea where this error could be coming from, any help is appreciated. thanks in advance. (Apologies for the blank switch case block, this is a work in progress)</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
typedef struct {
int pCount;
float pAccul;
int pAddress;
}pState;
typedef struct {
int id;
char status[10];
pState state;
char priority;
}PCB;
//function prototypes
int addProcess(PCB*, PCB, int*);
PCB getPcb(PCB);
void printCurrent(PCB[], int);
int main()
{
PCB process;
PCB pArray[SIZE];
PCB* pcbPtr;
char option = ' ';
int i;
int currentProcess;
int* cpPtr;
for(i=0; i<SIZE; i++)
{
pArray[i].id = 0;
}//end for
cpPtr = &currentProcess;
pcbPtr = pArray;
//simple menu with 4 options
while(option != '0')
{
printf("\n-----Menu-----\n");
printf("\n1) Add Process\n");
printf("\n2) Delete Process\n");
printf("\n3) Display PCB\n");
printf("\n0) Quit\n");
scanf("%1s", &option);
switch(option)
{
case '1':
addProcess(pcbPtr, process, cpPtr);
printf("\nCHECK CHECK %d CHECK CHECK\n", currentProcess);//ERROR CHECK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
break;
case '2':
//deleteProcess();
break;
case '3':
printCurrent(pArray, currentProcess);
break;
case '0':
exit(0);
default:
printf("Error! Choose From Available Options!!");
break;
}//end main switch/case
}//end main while
}//end main
int addProcess(PCB* ptr, PCB newSt, int* currentProcess)
{
int i;
for(i=0; i<SIZE; i++)
{
if((ptr+i)->id == 0)
{
ptr[i] = getPcb(newSt);
*currentProcess = i;
printf("%d", *currentProcess);//ERROR CHECK!!!
return 0;
}//end if
}//end for
return 1;
}//end addProcess()
PCB getPcb(PCB new)
{
printf("\nEnter Id\n");
scanf("%d", &new.id);
printf("\nEnter Status\n");
scanf("%s", new.status);
printf("\nEnter Process Counter Value\n");
scanf("%d", &new.state.pCount);
printf("\nEnter Acculumator Value\n");
scanf("%f", &new.state.pAccul);
printf("\nEnter Process Address (Unsigned Int)\n");
scanf("%d", &new.state.pAddress);
printf("\nEnter Priority (l/h)\n");
scanf("%1s", &new.priority);
return new;
}//end getPcb()
void printCurrent(PCB array[], int currentProcess)
{
printf("!!!!!!!!%d!!!!!!!!!!!!!!!!!!!!!", currentProcess);//!!!!!!!!!!
printf("\n---------------------------\n");
printf("\nProcess ID: %d\n", array[currentProcess].id);
printf("Status: %s\n", array[currentProcess].status);
printf("Process Counter: %d\n", array[currentProcess].state.pCount);
printf("Acculumator Value: %.2f\n", array[currentProcess].state.pAccul);
printf("Process Address: %d\n", array[currentProcess].state.pAddress);
printf("Priority: %c\n", array[currentProcess].priority);
printf("\n----------------------------\n");
}//end printCurrent()
</code></pre>
| <p>M.M is right. <code>{scanf("%1s", &option);}</code> is ugly. Make if "%c".</p>
<p>Here is changed code:</p>
<pre><code>//function prototypes
int addProcess(PCB* arr, int*); //you don't need newSt
PCB getPcb();
void printCurrent(PCB[], int);
</code></pre>
<hr>
<pre><code>case '1':
// address of first element of the array is passed
// this way, you are letting addProcess know the location
// of pArray on main()'s stack so that it can fill it
addProcess(&pArray, &currentProcess);
break;
</code></pre>
<hr>
<pre><code>int addProcess(PCB* ptr, int* currentProcess)
{
int i;
for(i = 0; i < SIZE; i++)
{
if(ptr[i].id == 0)
{
ptr[i] = getPcb();
// getPcb() will initialize and return
// a new PCB which is assigned to the
// appropriate location of array
*currentProcess = i;
printf("%d", *currentProcess);//ERROR CHECK!!!
return 0;
// the function is anyway returning an int
// why not return "i"?
}//end if
}//end for
return 1;
}//end addProcess()
</code></pre>
|
I'm using bootstrap to create forms. Unfortunately some of my field values don't post to the action page. <p>Below is the bootstrap code I am using. The form appears properly (this is from an include file). When I submit the form all of the fields pass the variables to the next page - except for the dropdown elements</p>
<p>I used to build websites from about 1994 - 2008. This is my first site using bootstrap. And my first website since 2009. </p>
<pre><code><div class="col-md-3 col-sm-12 col-xs-12">
<div class="white-box">
<h3 class="box-title">Add User</h3>
</code></pre>
<p>The following line is where I am posting the form to. That is where I check the back end database to either add the user or give an error that the user exists.</p>
<pre><code><form id="add-user" method="post" action="/dcs/admin/confirmAddUser.html" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_ID">ID</label>
<input id="form_ID" type="text" name="id" id="focusedInput" class="form-control" placeholder="ID Number *" required="required" data-error="ID is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_pass">Password</label>
<input id="form_pass" type="text" name="pass" class="form-control" placeholder="Employee Password *" required="required" data-error="Password is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="form_fName">Name</label>
<input id="form_fName" type="text" name="fName" class="form-control" placeholder="First *" required="required" data-error="Name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="form_lName">.</label>
<input id="form_lName" type="text" name="lName" class="form-control" placeholder="Last *" required="required" data-error="Name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</code></pre>
<p>Below shortened based on the warnings from Stackoverflow :) I do normally have all twelve months. </p>
<pre><code><div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="form_birthMonth">Birth Month</label>
<select id="birthMonth" class="form-control" required="required" data-error="Birth Month is required.">
<option VALUE="Jan">January</option>
<option VALUE="Feb">February</option>
<option VALUE="Mar">March</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</code></pre>
<p>Same below, I normally have all 31 days. </p>
<pre><code><div class="col-md-2">
<div class="form-group">
<label for="form_birthDay">Day</label>
<select id="birthDay" class="form-control" required="required" data-error="Birth Day is required.">
<option VALUE="1">1</option>
<option VALUE="2">2</option>
<option VALUE="3">3</option>
<option VALUE="4">4</option>
<option VALUE="5">5</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Employee email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Employee phone *">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_position">Position</label>
<input id="form_position" type="text" name="position" class="form-control" placeholder="Employee Position *" required="required" data-error="Employee Position is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_groups">Groups</label><br />
<div class="checkbox-inline">
<label class="checkbox-inline"><input type="checkbox" value="Technician">Technician</label>
<label class="checkbox-inline"><input type="checkbox" value="Parts">Parts</label>
<label class="checkbox-inline"><input type="checkbox" value="Reports">Reports</label>
<label class="checkbox-inline"><input type="checkbox" value="Database Mgr">Database Mgr</label>
<label class="checkbox-inline"><input type="checkbox" value="Admin">Admin</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="form_shiftStart">Shift Start</label>
<select class="form-control" id="startshift">
<option VALUE="0600">6:00</option>
<option VALUE="0630">6:30</option>
<option VALUE="0700">7:00</option>
<option VALUE="0730">7:30</option>
<option VALUE="0800">8:00</option>
<option VALUE="0830">8:30</option>
<option VALUE="0900">9:00</option>
<option VALUE="0930">9:30</option>
<option VALUE="1000">10:00</option>
<option VALUE="1030">10:30</option>
<option VALUE="1100">11:00</option>
<option VALUE="1130">11:30</option>
<option VALUE="1200">12:00</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="form_shiftStart">Shift Start</label>
<select class="form-control" id="endshift">
<option VALUE="0600">6:00</option>
<option VALUE="0630">6:30</option>
<option VALUE="0700">7:00</option>
<option VALUE="0730">7:30</option>
<option VALUE="0800">8:00</option>
<option VALUE="0830">8:30</option>
<option VALUE="0900">9:00</option>
<option VALUE="0930">9:30</option>
<option VALUE="1000">10:00</option>
<option VALUE="1030">10:30</option>
<option VALUE="1100">11:00</option>
<option VALUE="1130">11:30</option>
<option VALUE="1200">12:00</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="form_LunchStart">Lunch Start</label>
<select class="form-control" id="startshift" type="text">
<option VALUE="0600">6:00</option>
<option VALUE="0630">6:30</option>
<option VALUE="0700">7:00</option>
<option VALUE="0730">7:30</option>
<option VALUE="0800">8:00</option>
<option VALUE="0830">8:30</option>
<option VALUE="0900">9:00</option>
<option VALUE="0930">9:30</option>
<option VALUE="1000">10:00</option>
<option VALUE="1030">10:30</option>
<option VALUE="1100">11:00</option>
<option VALUE="1130">11:30</option>
<option VALUE="1200">12:00</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_assignedLots">Assigned Location(s)</label>
<textarea id="form_assignedLots" name="assignedLots" class="form-control" placeholder="Work Locations *" rows="4" required="required" data-error="Assigned Location(s)."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-9"></div>
<div class="col-md-3">
<input type="submit" class="btn btn-success btn-send" value=" Add User ">
</div>
</div>
</div>
<input id="form_login" type="hidden" name="login" value="Y" class="form-control">
</form>
</div>
</div>
</code></pre>
<p>The above forms came from a bootstrap compliant theme we purchased. The backend scripting language / database I am using is WebDNA - although at this point that doesn't enter the question.</p>
| <pre><code><select id="birthMonth" NAME="GIVE_SOME_NAME_HERE" class="form-control" required="required" data-error="Birth Month is required.">
<option VALUE="Jan">January</option>
<option VALUE="Feb">February</option>
<option VALUE="Mar">March</option>
</select>
</code></pre>
<p>the name attribute to the select field is not set. make sure it is set </p>
|
highcharts dynamic plotlines <p>I am encountering a problem, how to update the plotlines(on YAxis) dynamically? Specifically, I need to calculate a max, min and average value for a period of the chart, then setup the 3 lines which they stand for. How can I do that?
many thanks!</p>
| <p>This is a very simple example of how to update plotlines dynamically.</p>
<ul>
<li>It has one data series which can be updated by the press of a button. </li>
<li>When pressing the second button, plotlines will be added or removed+redrawn according to the data of the series.</li>
<li>If you want to use a subset of data points, feel free to work on the function <code>getKPIByData</code> accordingly, or change the <code>data</code> argument. </li>
</ul>
<p><a href="http://jsfiddle.net/hsL4pwsh/12/" rel="nofollow">http://jsfiddle.net/hsL4pwsh/12/</a></p>
<pre><code>;$(function() {
var curActiveData = 1;
var addedPlotlines = false;
var data1 = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];
var data2 = [31.9, 73.5, 117.4, 29.2, 109.0, 181.0, 212.6, 137.5, 225.4, 199.1, 91.6, 11.4];
var getKPIByData = function(data) {
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
function getMinOfArray(numArray) {
return Math.min.apply(null, numArray);
}
var minRate,
maxRate = 0,
rate,
i,
avgRate,
totalRate = 0;
for (i = 0; i < data.length; i++) {
totalRate += data[i];
}
return {
minRate: getMinOfArray(data),
maxRate: getMaxOfArray(data),
avgRate: totalRate / data.length
};
};
$('#container').highcharts({
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
},
series: [{
data: data1
}]
});
// the button action
var $button1 = $('#addPlotlines'),
$button2 = $('#updatePlotlines'),
chart = $('#container').highcharts();
$button1.on("click", function() {
var curData = [];
for (var i = 0; i < chart.series[0].data.length; i++) {
curData[curData.length] = chart.series[0].data[i].y;
}
var result = getKPIByData(curData);
if (addedPlotlines) {
chart.yAxis[0].removePlotLine('min');
chart.yAxis[0].removePlotLine('max');
chart.yAxis[0].removePlotLine('avg');
}
chart.yAxis[0].addPlotLine({
color: 'green',
width: 2,
id: "min",
value: result.minRate
});
chart.yAxis[0].addPlotLine({
color: 'red',
width: 2,
id: "max",
value: result.maxRate
});
chart.yAxis[0].addPlotLine({
color: 'blue',
width: 2,
id: "avg",
value: result.avgRate
});
addedPlotlines = true;
});
$button2.on("click", function() {
var newActive = (curActiveData == 1) ? 2 : 1;
console.log(newActive);
chart.series[0].update({
data: (newActive == 1) ? data1 : data2
});
curActiveData = newActive;
});
});
</code></pre>
|
stuck in implementing search in django <p>I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django.
Now the problem is this:
I have a model <strong><code>Product</code></strong>
with five field <code>name</code>, <code>cost</code>, <code>brand</code>, <code>expiry_date</code>, <code>weight</code>
I want to implement a advanced search feature with all fields,
by:</p>
<pre><code>name = request.GET.get('name')
</code></pre>
<p>I get a value on which basis I search all product.
What I want is that when <strong><code>name = None</code></strong>, it has to search for all names.
<strong>So problem is this: if values are not coming by user side, how can i search for all names?</strong></p>
| <p>You didn't show your search query. However, I think using <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#contains" rel="nofollow"><code>contains</code></a> (or <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#icontains" rel="nofollow"><code>icontains</code></a> for case insensitive match) will help you solve the problem, with the benefit of being able to search for say first names, last names and names containing a matching text.</p>
<p>You would do:</p>
<pre><code>name = request.GET.get('name', '')
search_result = Product.objects.filter(name__icontains=name)
</code></pre>
<p>Notice the <code>get</code> method has been instructed to return a <code>''</code> instead of the default <code>None</code>. And keep in mind that all strings in Python contain the empty string <code>''</code>. So when no <code>name</code> is sent via the <code>request</code>, every <code>Product</code> in the DB (with a not <em>NULL</em> name) is returned, as their names all contain the empty string <code>''</code>.</p>
|
reflection to pass tagName as string props to be rendered <pre><code>class Button extends React.Component{
renderAnchor(){
return <a onClick={this.props.onClick}>{this.props.children}</a>
}
renderButton(){
return <button onClick={this.props.onClick}>{this.props.children}</button>
}
render(){
return (this.tagName==='a')?this.renderAnchor():this.renderButton();
}
}
</code></pre>
<p>I have the above react-component , i want to avoid code redundancy, so , i decide to remove all render methods except the last (<code>render</code>) by replacing the tagname by <code>this.props.tagName</code></p>
<pre><code> render(){
return <{this.props.tagName} onClick={this.props.onClick}>{this.props.children}</{this.props.tagName}>
}
</code></pre>
<p>However, it raises an error of syntax . </p>
<p>How can use reflection of tagname in react / ES7/ Babel ? </p>
| <p>You can assign the tag name to a variable and use that variable as the HTML tag.</p>
<p>For example:</p>
<pre><code>render(){
const CustomTag = this.props.tagName //assign it to the variable
return <CustomTag
onClick={this.props.onClick}>
{this.props.children}
</CustomTag>
</code></pre>
<p>Demo: <a href="https://jsfiddle.net/88honb0z/" rel="nofollow">https://jsfiddle.net/88honb0z/</a></p>
|
Is there a way to create a global setter? <p>What I need is to have a function, which is called every time an assignments is performed, so for example when there is : </p>
<pre><code>var a = b;
c = d;
// or even
for(var i=3...){}
</code></pre>
<p>I could have a function like : </p>
<pre><code>function assigned(nameL, valL, nameR, valR){
}
</code></pre>
<p>I don't have high hopes for that, I also acknowledge that it may speed things down a lot, but I need it only for debugging purposes.</p>
| <blockquote>
<p>Is there a way to create a global setter?</p>
</blockquote>
<p>No. </p>
<p>ECMAScript2015 introduces <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="nofollow">Proxy objects</a> which allows you to do "meta programming" but it doesn't work the way you want. </p>
<blockquote>
<p>The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).</p>
</blockquote>
|
How to cancel a recurring job in firebase job dispatcher <p>I have created a recurring job, I want to cancel the recurring job when some conditions met.</p>
<pre><code>final Job.Builder builder = dispatcher.newJobBuilder()
.setTag("myJob")
.setService(myJobService.class)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(30, 60));
</code></pre>
<p>How can i cancel a job in firebase ?</p>
| <p>The readme on GitHub says:</p>
<blockquote>
<p>Driver is an interface that represents a component that can schedule,
cancel, and execute Jobs. The only bundled Driver is the
GooglePlayDriver, which relies on the scheduler built-in to Google
Play services.</p>
</blockquote>
<p>So cancelling is part of the driver you are using. Inspecting <a href="https://github.com/firebase/firebase-jobdispatcher-android/blob/master/jobdispatcher/src/main/java/com/firebase/jobdispatcher/Driver.java" rel="nofollow">the code of the driver interface</a> there are two methods to cancel a job:</p>
<pre><code>/**
* Cancels the job with the provided tag and class.
*
* @return one of the CANCEL_RESULT_ constants.
*/
@CancelResult
int cancel(@NonNull String tag);
/**
* Cancels all jobs registered with this Driver.
*
* @return one of the CANCEL_RESULT_ constants.
*/
@CancelResult
int cancelAll();
</code></pre>
<p>So in your case you have to call:</p>
<pre><code>dispatcher.cancel("myJob");
</code></pre>
<p>or</p>
<pre><code>dispatcher.cancelAll();
</code></pre>
<p>The dispatcher will call the corresponding method of the driver for you. If you want you can also call the methods directly on your driver <code>myDriver.cancelAll()</code> <a href="https://github.com/firebase/firebase-jobdispatcher-android/blob/master/testapp/src/main/java/com/firebase/jobdispatcher/testapp/CentralContainer.java#L109" rel="nofollow">like it is done in the sample app which comes with the GitHub project.</a></p>
<p>The chosen method will return one of the following constants:</p>
<blockquote>
<pre><code>public static final int CANCEL_RESULT_SUCCESS = 0;
public static final int CANCEL_RESULT_UNKNOWN_ERROR = 1;
public static final int CANCEL_RESULT_NO_DRIVER_AVAILABLE = 2;
</code></pre>
</blockquote>
|
java.lang.NoClassDefFoundError: com.amazonaws.mobileconnectors.apigateway.ApiResponse <p>I made a few changes to my android application, and now I'm getting this. I'm thinking it might be caused by updating the autogenerated ApiGateway SDK that I'm using in my app. But maybe it's something else? I'm not even sure where to start debugging.</p>
<p><code>build.gradle:</code></p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '24.0.2'
defaultConfig {
applicationId "com.johndoe.supercoolsoftware"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
// compile fileTree(include: ['*.jar'], dir: 'app/libs')
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services:9.2.0'
compile 'com.google.android.gms:play-services-auth:9.2.0'
compile 'com.facebook.android:facebook-android-sdk:4.14.1'
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.0'
compile 'com.amazonaws:aws-android-sdk-core:2.2.22'
compile 'com.amazonaws:aws-android-sdk-s3:2.2.22'
compile 'com.amazonaws:aws-android-sdk-cognitoidentityprovider:2.2.22'
compile 'com.amazonaws:aws-android-sdk-cognito:2.2.22'
compile 'com.amazonaws:aws-android-sdk-apigateway-core:2.2.22'
compile 'com.google.code.gson:gson:2.2.4'
//used for API Gateway SDK generated classes
compile files('libs/Api-alpha-0.51.jar') #<- autogenerated SDK
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
| <p>Okay I figured it out. AWS just updated their Android core. So now when you build it's using a newer version (v2.3.2 now) where the old one was v2.22.2. Once I updated my android application to use v2.3.2 by changing my gradel file, everything worked.</p>
<pre><code>compile 'com.amazonaws:aws-android-sdk-core:2.3.2'
compile 'com.amazonaws:aws-android-sdk-s3:2.3.2'
compile 'com.amazonaws:aws-android-sdk-cognitoidentityprovider:2.3.2'
compile 'com.amazonaws:aws-android-sdk-cognito:2.3.2'
compile 'com.amazonaws:aws-android-sdk-apigateway-core:2.3.2'
</code></pre>
|
How to do custom python imports? <p>Is there a way to have custom behaviour for import statements in Python? How? E.g.:</p>
<pre><code>import "https://github.com/kennethreitz/requests"
import requests@2.11.1
import requests@7322a09379565bbeba9bb40000b41eab8856352e
</code></pre>
<p>Alternatively, in case this isn't possible... Can this be achieved in a standard way with function calls? How? E.g.:</p>
<pre><code>import gitloader
repo = gitloader.repo("https://github.com/kennethreitz/requests")
requests = repo.from_commit("7322a09379565bbeba9bb40000b41eab8856352e")
</code></pre>
<p>There are two reasons for why I would like to do this. The first reason is convenience (Golang style imports). The second reason is that I need cryptographic verification of plugin modules for a project. I'm using Python 3.x</p>
| <p>What you're essentially asking is customization of the import steps. This was made possible with <a href="https://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 302</a> which brought about certain hooks for for customization. </p>
<p>That PEP is currently not the source from which you should learn how importing works; rather, look at the <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">documentation for the <code>import</code> statement</a> for reference. There <a href="https://docs.python.org/3/reference/import.html#finders-and-loaders" rel="nofollow">it states</a>:</p>
<blockquote>
<p>Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate frozen modules. A third default finder searches an import path for modules. The import path is a list of locations that may name file system paths or zip files. <em>It can also be extended to search for any locatable resource, such as those identified by URLs.</em></p>
<p><em>The import machinery is extensible, so new finders can be added to extend the range and scope of module searching</em>.</p>
</blockquote>
<p>In short, you'll need to define the appropriate finder (to find the modules you're looking for) and an appropriate loader for loading these. </p>
|
Not able to install Elasticsearch as different user <p>I have downloaded elasticsearch rpm 2.3.1 on centos machine. I want to install it as other then elasticsearch user. By default ES_USER is set as elasticsearch. Can someone please help me if we can override ES_USER with other user while installing rpm or how to reset elasticsearch default username?</p>
<p>Thanks</p>
| <p>You can change the user running Elasticsearch via the <code>/etc/sysconfig/elasticsearch</code> file under the <code>ES_USER</code> environment variable.</p>
|
DELETE MethodNotAllowedHttpException with IIS, AngularJS and Laravel <p>I am learning AngularJS 1.5.8 + Laravel 5.3.17 + PHP 7 hosted on IIS/Windows 10, following this <a href="https://scotch.io/tutorials/build-a-time-tracker-with-laravel-5-and-angularjs-part-2" rel="nofollow">tutorial</a>.</p>
<p>While sending a HTTP AngularJS $resource.delete() to Laravel, I get an error: <code>405 Method Not Allowed</code> and the below Laravel error message:</p>
<p><a href="http://i.stack.imgur.com/C4ok8.png" rel="nofollow"><img src="http://i.stack.imgur.com/C4ok8.png" alt="enter image description here"></a></p>
<p><code>php artisan route:list</code> gives me the following routes table. I expect DELETE to route to <code>time.destroy</code>.</p>
<p><a href="http://i.stack.imgur.com/d57d0.png" rel="nofollow"><img src="http://i.stack.imgur.com/d57d0.png" alt="enter image description here"></a></p>
<p>On IIS, I have tried to set PHP to handler to accept all HTTP verbs to no avail.</p>
<p><a href="http://i.stack.imgur.com/9h06c.png" rel="nofollow"><img src="http://i.stack.imgur.com/9h06c.png" alt="enter image description here"></a> </p>
<p>IIS request filtering to explicitly allow DELETE also not working.</p>
<p><a href="http://i.stack.imgur.com/IS4rz.png" rel="nofollow"><img src="http://i.stack.imgur.com/IS4rz.png" alt="enter image description here"></a></p>
<p>HTTP GET and PUT verbs works fine. How can I enable DELETE verb?</p>
<p>Thanks in advance!</p>
| <p>I found the reason is because i was passing id:null value to Laravel, accidentally.</p>
<pre><code>var Time = $resource('api/time/:id'); //using angular-resource.js
Time.delete({id:null}).$promise.then(function(success) {
console.log(success);
}, function (error) {
console.log(error); // HTTP error 405, Method Not Allowed
});
</code></pre>
<p>The 405 error message return is indeed misleading. I wonder how I can override this behaviour and return a more meaningful error message.</p>
<p>Hope this helps other poor souls to look at the correct places without wasting 2 days of searching web server docs!</p>
|
Edge Existence (to find if an edge exists or not) <p>Question is:
You have been given an undirected graph consisting of <em>N</em> nodes and <em>M</em> edges. This graph can consist of self-loops as well as multiple edges. In addition , you have also been given <em>Q</em> queries. For each query, you shall be given 2 integers <em>A</em> and <em>B</em>. You just need to find if there exists an edge between node <em>A</em> and node <em>B</em>. If yes, print "YES" (without quotes) else , print "NO"(without quotes).</p>
<p>My code:</p>
<pre><code>#include<bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
vector< vector<int> > v;
int a,b;
vector<int>temp;
while(m--)
{
cin>>a>>b;
temp.push_back(a);
v.push_back(temp);
v[a].push_back(b);
temp.clear();
}
int q;
cin>>q;
while(q--)
{
cin>>a>>b;
int flag=0;
for(int i=0;i<v[a].size();i++)
{
if(v[a][i]==b)
{
cout<<"YES"<<endl;
flag=1;
break;
}
}
if(flag!=1)
cout<<"NO"<<endl;
}
return 0;
}
</code></pre>
<p>I am getting <em>segmentation fault</em>. What am I doing wrong?</p>
| <p>For example when you want to add the edge <code>(3,5)</code> you push 3 into an empty vector ( <code>temp</code> ) and then you <code>push_back</code> temp into <code>v</code>. So now size of <code>v</code> is 1. Then you try to <code>push_back</code> 5 to <code>v[3]</code>:</p>
<pre><code>v[a].push_back(b);
</code></pre>
<p><code>v[3]</code> doesn't exist because your <code>v</code> only has 1 item. Hence the <em>segmentation fault</em>.</p>
<p><em>What should I do?</em><br>
Because you know the number of the nodes beforehand (<code>n</code>) you can initialize your <code>v</code> with the number of nodes ( <code>n+1</code> if you want to use 1-indexing). So <code>v</code> will have <code>n</code> empty <code>vector</code>s. Then you can safely <code>push_back</code> items into <code>v[a]</code>. Also because your graph is undirected for every edge <em>(a,b)</em> you should do both <code>v[a].push_back(b)</code> and <code>v[b].push_back(a)</code>.</p>
<p>Here is a working example:</p>
<pre><code>int n,m;
cin>>n>>m;
vector< vector<int> > v(n+1); // initialize v with (n+1) empty vectors
// because we want to use 1-indexing
int a,b;
while(m--)
{
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
</code></pre>
|
how to implement OAuth 1.0a using retrofit for woocomerce Api in android <p>Hi am currently working on a woocommerce api, i need to integrate the api using retrofit. The web site is in <strong>HTTP</strong> so HTTP Basic authentication cannot be used over plain HTTP as the keys are susceptible to interception. The API uses OAuth 1.0a âone-leggedâ authentication to ensure your API keys cannot be intercepted. i have gone through <a href="https://www.skyverge.com/blog/using-woocommerce-rest-api-introduction/" rel="nofollow">this artical</a> to understand which OAuth methord to be used on http.</p>
<p>i have successfully implemented the api using <a href="https://github.com/scribejava/scribejava" rel="nofollow">Scribe</a> but i want to implement the api using retrofit, after goggling i found Interceptor be Jake Wharton <a href="https://gist.github.com/JakeWharton/f26f19732f0c5907e1ab" rel="nofollow">Oauth1SigningInterceptor</a>. </p>
<p>so i implemented that in retrofit for Authentication but the api call return</p>
<pre><code>{"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}
</code></pre>
<p>The same api if i call using <strong>Scribe</strong> Return a successful Response</p>
<p>The below is how i call the Api</p>
<p><strong>BasicAuthInterceptor.java</strong>(modified from jake wharton Oauth1SigningInterceptor)</p>
<pre><code>public class BasicAuthInterceptor implements Interceptor {
private static final Escaper ESCAPER = UrlEscapers.urlFormParameterEscaper();
private static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key";
private static final String OAUTH_NONCE = "oauth_nonce";
private static final String OAUTH_SIGNATURE = "oauth_signature";
private static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
private static final String OAUTH_SIGNATURE_METHOD_VALUE = "HMAC-SHA1";
private static final String OAUTH_TIMESTAMP = "oauth_timestamp";
private static final String OAUTH_VERSION = "oauth_version";
private static final String OAUTH_VERSION_VALUE = "1.0";
private final String consumerKey;
private final String consumerSecret;
private final Random random;
private BasicAuthInterceptor(String consumerKey, String consumerSecret, Random random) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.random = random;
}
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(signRequest(chain.request()));
}
public Request signRequest(Request request) throws IOException {
byte[] nonce = new byte[32];
random.nextBytes(nonce);
String oauthNonce = ByteString.of(nonce).base64().replaceAll("\\W", "");
String oauthTimestamp = String.valueOf(System.currentTimeMillis());
String consumerKeyValue = ESCAPER.escape(consumerKey);
SortedMap<String, String> parameters = new TreeMap<>();
parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue);
parameters.put(OAUTH_NONCE, oauthNonce);
parameters.put(OAUTH_TIMESTAMP, oauthTimestamp);
parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE);
parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE);
HttpUrl url = request.url();
for (int i = 0; i < url.querySize(); i++) {
parameters.put(ESCAPER.escape(url.queryParameterName(i)),
ESCAPER.escape(url.queryParameterValue(i)));
}
RequestBody requestBody = request.body();
Buffer body = new Buffer();
if (requestBody != null) {
requestBody.writeTo(body);
}
while (!body.exhausted()) {
long keyEnd = body.indexOf((byte) '=');
if (keyEnd == -1) throw new IllegalStateException("Key with no value: " + body.readUtf8());
String key = body.readUtf8(keyEnd);
body.skip(1); // Equals.
long valueEnd = body.indexOf((byte) '&');
String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd);
if (valueEnd != -1) body.skip(1); // Ampersand.
parameters.put(key, value);
}
Buffer base = new Buffer();
String method = request.method();
base.writeUtf8(method);
base.writeByte('&');
base.writeUtf8(ESCAPER.escape(request.url().newBuilder().query(null).build().toString()));
base.writeByte('&');
boolean first = true;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (!first) base.writeUtf8(ESCAPER.escape("&"));
first = false;
base.writeUtf8(ESCAPER.escape(entry.getKey()));
base.writeUtf8(ESCAPER.escape("="));
base.writeUtf8(ESCAPER.escape(entry.getValue()));
}
String signingKey =
ESCAPER.escape(consumerSecret);// + "&" + ESCAPER.escape(accessSecret);
SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
Mac mac;
try {
mac = Mac.getInstance("HmacSHA1");
mac.init(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
byte[] result = mac.doFinal(base.readByteArray());
String signature = ByteString.of(result).base64();
String authorization = "OAuth "
+ OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", "
+ OAUTH_NONCE + "=\"" + oauthNonce + "\", "
+ OAUTH_SIGNATURE + "=\"" + ESCAPER.escape(signature) + "\", "
+ OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", "
+ OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", "
+ OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\"";
Log.d("message","--"+authorization);
return request.newBuilder()
.addHeader("Authorization", authorization)
.addHeader("Content-Type", "application/json;charset=UTF-8")
.addHeader("Accept", "application/json;versions=1")
.build();
}
public static final class Builder {
private String consumerKey;
private String consumerSecret;
private Random random = new SecureRandom();
public Builder consumerKey(String consumerKey) {
if (consumerKey == null) throw new NullPointerException("consumerKey = null");
this.consumerKey = consumerKey;
return this;
}
public Builder consumerSecret(String consumerSecret) {
if (consumerSecret == null) throw new NullPointerException("consumerSecret = null");
this.consumerSecret = consumerSecret;
return this;
}
public Builder random(Random random) {
if (random == null) throw new NullPointerException("random == null");
this.random = random;
return this;
}
public BasicAuthInterceptor build() {
if (consumerKey == null) throw new IllegalStateException("consumerKey not set");
if (consumerSecret == null) throw new IllegalStateException("consumerSecret not set");
}
}
}
</code></pre>
<p><strong>Remote Api Call</strong></p>
<pre><code>public final class RemoteApiCalls {
private static final String TAG = "RemoteApiCalls";
public static final class Builder {
RemoteRetrofitInterfaces mService;
Retrofit mRetrofit;
public Builder remoteApiCall(String url,Context mContext) {
return remoteApiCall(mContext,url, 40, 40, 40);
}
BasicAuthInterceptor oauth1 = new BasicAuthInterceptor.Builder()
.consumerKey("keyhere")//i have added keys
.consumerSecret("secert here")//i have added secertkeys
.build();
public Builder remoteApiCall(Context mContext, String url, int connectionTimeout, int readTimeout, int writeTimeout) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).addInterceptor(interceptor).addInterceptor(oauth1)
.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(url).addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
mService = mRetrofit.create(RemoteRetrofitInterfaces.class);
return this;
}
public void getProductCatogry()
{
Call<ProductCategoryResponse> mApiCall = mService.getListCategory();
mApiCall.enqueue(new Callback<ProductCategoryResponse>() {
@Override
public void onResponse(Call<ProductCategoryResponse> call, Response<ProductCategoryResponse> response) {
if (response.isSuccessful()) {
} else {
}
}
@Override
public void onFailure(Call<ProductCategoryResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
}
}
</code></pre>
<p><strong>RemoteRetrofitInterfaces.java</strong></p>
<pre><code>public interface RemoteRetrofitInterfaces {
@GET("products")
Call<ProductCategoryResponse> getListCategory();
}
</code></pre>
<p><strong>in Main Activity i call</strong></p>
<pre><code> new RemoteApiCalls.Builder().remoteApiCall("http://mywebsite.com/wp-json/wc/v1/",getApplicationContext()).getProductCatogry();
</code></pre>
<p>still am getting the 401 error</p>
<pre><code>{"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}
</code></pre>
<p>Woo commerce version used is Version 2.6.4
APi Version is v1</p>
<p>can any one help me to fix this issue i want to implement this with retrofit itself.</p>
| <p>Finally i found the solution hope this will help some other</p>
<p>i go through various documents</p>
<p>1)<a href="https://www.skyverge.com/blog/using-woocommerce-rest-api-introduction/" rel="nofollow">Using the WooCommerce REST API â Introduction</a></p>
<p>2)<a href="https://github.com/woocommerce/woocommerce-rest-api-docs/blob/master/source/includes/v2/_introduction.md" rel="nofollow">woocommerce-rest-api-docs
</a></p>
<p>3)<a href="https://github.com/scribejava/scribejava" rel="nofollow">Scribe</a></p>
<p>4)<a href="http://grepcode.com/snapshot/repo1.maven.org/maven2/org.scribe/scribe/1.3.5" rel="nofollow">scribe:1.3.5</a></p>
<p>After referring above documents and Source codes finally i created a library which do the OAuth 1.0a âone-leggedâ authentication for woocommerce HTTP android</p>
<p>The full description has added in the read me section of my library</p>
<p>Check The Library Here</p>
<p><a href="https://github.com/rameshvoltella/WoocommerceAndroidOAuth1" rel="nofollow">WoocommerceAndroidOAuth1 LIBRARY
</a></p>
|
Android: SQLiteOpenHelper class- What are all the Exceptions that the SQL queries produce? <p>I have the following class named <code>DatabaseHandler</code></p>
<pre><code>public class DatabaseHandler extends SQLiteOpenHelper {
// Database Name
private static final String DATABASE_NAME="contacts_provider";
// Database Version
private static final int DATABASE_VARSION=1;
// Table Name
private static final String TABLE_NAME="contacts";
// Column Names
private static final String COL_CONTACT_ID="contact_id";
private static final String COL_NAME="name";
private static final String COL_PHONE="phone";
public DatabaseHandler(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VARSION);
}
@Override
public void onCreate(SQLiteDatabase db){}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){}
public void addContact(Contact contact){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COL_NAME,contact.getName());
values.put(COL_PHONE,contact.getPhone());
db.insert(TABLE_NAME,null,values);
db.close();
}
public List<Contact> getAllContacts(){
SQLiteDatabase db=getReadableDatabase();
List<Contact> list=new ArrayList<>();
String sql="SELECT * FROM "+TABLE_NAME;
Cursor cursor=db.rawQuery(sql,null);
if(cursor!=null){
if(cursor.moveToFirst()){
do{
int contact_id=Integer.parseInt(cursor.getString(0));
String name=cursor.getString(1);
String phone=cursor.getString(2);
Contact contact=new Contact(contact_id,name,phone);
list.add(contact);
}while(cursor.moveToNext());
}
cursor.close();
}
db.close();
return list;
}
}
</code></pre>
<p>As you can can observe, I have not created the <code>contacts</code> table in the onCreate() method.</p>
<p>Here are my observations,</p>
<ol>
<li><p>When I execute addContact(Contact contact) method the following things happen:
a. <code>SQLiteException</code> gets produced.
logcat shows, <code>android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: INSERT INTO contacts(phone,name) VALUES (?,?)</code>
b. The app doesn't get crashed on the emulator.</p></li>
<li><p>When I execute getAllContacts() method the following things happen:
a. <code>RuntimeException</code> gets produced.
logcat shows, <code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.sqlite2/com.example.user.sqlite2.SQLite.SQLiteExecution}: android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: SELECT * FROM contacts</code>
b. The app crashes on the emulator</p></li>
</ol>
<p>So my question is, What kind of SQL instructions produce what kind of Exceptions if the table doesn't exist in the SQLite database?</p>
| <p>You must create table in <code>public void onCreate(SQLiteDatabase db)</code> before doing any insertions.</p>
<pre><code>public void onCreate(SQLiteDatabase db) {
db.execSQL(String.format("CREATE TABLE %s(%s ID INT PRIMARY KEY,
%s TEXT,
%s TEXT);",
TABLE_NAME,
COL_CONTACT_ID,
COL_NAME,
COL_PHONE);
}
</code></pre>
|
Creating multiple hubs dynamically using SignalR <p>I am currently using <code>SignalR</code> for chat. I have a form and the user will load a specific order into the form. The scenario is that other <code>staff members</code> may search that order number and therefore i want only those people to be in the chat. Currently if you load the site everyone is in a single <code>hub</code> called <code>ChatHub</code>.</p>
<p><strong>ChatHub.cs:</strong></p>
<pre><code>public class ChatHub: Hub {
public void Send(string name, string message) {
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
}
}
</code></pre>
<p><strong>Chat.cshtml:</strong></p>
<pre><code>@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append(htmlEncode(name)
+ ':' + htmlEncode(message) + '\n');
};
// Get the user name and store it to prepend to messages.
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
<script>
</code></pre>
<p><strong>I have tried to add the following:</strong></p>
<pre><code><script>
$(function () {
var chat = jQuery.connection.chat;
chat.addMessage = function (message, room) {
if ($('#currentRoom').val() == room) {
$('#messagesList').append(message);
}
};
chat.send($('#textboxMessage').val(), $('#currentRoom').val());
$('#textboxMessage').val("");
$.connection.hub.start();
});
</script>
</code></pre>
<p>I am trying to work out a way of getting multiple hubs or chat rooms based on a user loading an order.</p>
| <p>You have to put the users into groups according to the opened order id, change the hub and add a method as below:</p>
<pre><code>public class ChatHub: Hub {
public void Send(string name, string message,string orderId) {
// Call the addNewMessageToPage method to update clients.
Clients.Group(orderId).addNewMessageToPage(name, message);
}
public void JoinOrderGroup(string name,string orderId)
{
Groups.Add(Context.ConnectionId, orderId);
}
}
</code></pre>
<p>Then modify your JavaScript to call the `JoinOrderGroup' when the user opens the page.</p>
<pre><code>@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var orderId = '@Model.Id' //You can change this line to get the orderId from the correct place
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append(htmlEncode(name)
+ ':' + htmlEncode(message) + '\n');
};
// Get the user name and store it to prepend to messages.
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
chat.server.joinOrderGroup($('#displayname').val(),orderId);
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
<script>
</code></pre>
<p>This way, when the page starts and the hub connects, it will send a message to join the group related to the order in the form, and all successive calls to teh send message method will include the order id and it will be propagated to the users in this order only.</p>
|
What is the default value of variable equal to ko.observable()? <p>I have just started learning KnockoutJS. This is code for folder navigation of webmail client.In the view code, a comparision is made whether the reference variable <code>$data</code> and <code>$root.chosenFolderId()</code> point to the same memory location. But I don't understand what will be the initial value of <code>$root.chosenFolderId()</code>?</p>
<p><a href="http://learn.knockoutjs.com/#/?tutorial=webmail" rel="nofollow">Reference</a></p>
<h2>View:</h2>
<pre><code><!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
<li data-bind="text: $data, css : {selected: $data == $root.chosenFolderId()}, click: $root.goToFolder"></li>
</ul>
</code></pre>
<h2>View Model:</h2>
<pre><code>function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
//Operations
self.goToFolder = function(folder){
self.chosenFolderId(folder);
};
};
ko.applyBindings(new WebmailViewModel());
</code></pre>
| <p>You're 90% there. As you stated, the foreach will iterate over the <code>folders</code> array and <code>$data</code> will be the current item in the array.</p>
<p><strong>Picking up the value for chosenFolderId</strong></p>
<p>The click binding which calls <code>goToFolder</code> will pass the item it was bound to as an argument, so the <code>chosenFolderId</code> value will be set to the folder item corresponding to the clicked <li> element.</p>
<p>For example: clicking on the 'Archive' element will fire the click event for the item bound to <code>folders[1]</code> thereby calling <code>goToFolder</code> with the <code>folders[1]</code> value.</p>
<p><strong>Initial value</strong></p>
<p>The initial value of <code>$root.chosenFolderId()</code> will be <code>undefined</code> since you declared it with no argument. On initial view no folders appear selected, if you had:</p>
<pre><code>self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable(self.folders[0]);
</code></pre>
<p>then the 'Inbox' would be initially selected.</p>
<p><strong>Memory location</strong></p>
<p>You asked if <code>$data</code> and <code>$root.chosenFolderId()</code> point to the same memory location. That's mostly correct - if your folders were an array of objects then they would contain the same reference (for the selected item). Technically strings are also references in JS (see explanation <a href="http://stackoverflow.com/a/51193/625200">http://stackoverflow.com/a/51193/625200</a>) but its simpler to think of primitives (strings, numbers, booleans) in JS as values and not references.</p>
|
Node&Express:req.flash() requires sessions <p>I have some problems with connect-flash.
Here is my configuration </p>
<pre><code>var flash=require('connect-flash');
var session=require('express-session');
app.use(flash());
app.use(session({
secret:settings.cookieSecret,
key:settings.db,
cookie:{maxAge:60000},
resave:false,
saveUninitialized:true
}));
app.use(function(req,res,next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
</code></pre>
<p>I'm so confused and I don't know how to solve this</p>
| <p>You should declare the <code>flash</code> middleware <em>after</em> declaring the session middleware:</p>
<pre><code>app.use(session({
secret:settings.cookieSecret,
key:settings.db,
cookie:{maxAge:60000},
resave:false,
saveUninitialized:true
}));
app.use(flash());
</code></pre>
<p>Express processes middleware in order of declaration, so when you use the <code>flash</code> middleware the session middleware has to be already declared, otherwise you'll get an error.</p>
|
Create sparse matrix for two columns in a Pandas Dataframe <p>I am trying to create a sparse matrix out of a Pandas Dataset (>10Gb)</p>
<p>Assume I have a dataset of the type</p>
<p>Table: Class</p>
<pre><code> student |teacher
---------------------
0 | abc | a
1 | def | g
</code></pre>
<p>And I have a list of students </p>
<pre><code>students = [ "abc", "def", "ghi", "jkl","mno"]
</code></pre>
<p>and list of teachers </p>
<pre><code>teachers = ["a","b","c","d","e","f","g"]
</code></pre>
<p>My goal is to create a sparse matrix out of them such that there is a boolean 1 if there is a corresponding relationship between student-teacher in table Class.</p>
<p>The dense matrix should look like this:</p>
<pre><code> a b c d e f g
abc 1 0 0 0 0 0 0
def 0 0 0 0 0 0 1
ghi 0 0 0 0 0 0 0
jkl 0 0 0 0 0 0 0
mno 0 0 0 0 0 0 0
</code></pre>
<p>Now in my real dataset I have 700K values of students and another 100K values of teachers. </p>
<p>Initially I tried to construct a simple dense matrix and then convert it to a sparse matrix using scipy. However, 700k*100k bytes = ~70GB and as you can realize it didn't work.</p>
<p>So I tried to assign unique values to both students and teachers and then append those values to rows and columns and tried to create a sparse matrix in Coordinate format.</p>
<p>Code:</p>
<pre><code># Get unique value for each student and teacher
dictstudent = {}
count = 0
for i in rows:
dictstudent[i] = count
count +=1
dictteacher ={}
count = 0
for i in cols:
dictteacher[i] = count
count +=1
</code></pre>
<p>Now that each teacher and student has a numeric number associated with it. Store numeric value of student if it appears in the table class and numeric value of teacher in r and c.</p>
<pre><code>r = []
c = []
for row,col in zip(student,teacher):
r.append(dictstudent[row])
c.append(dictteacher[col])
values = [1] * class["student"].size #From the pandas dataframe class
</code></pre>
<p>Then load it to make a sparse matrix</p>
<pre><code>a = sparse.coo_matrix((values,(r,c)),shape=(len(students),len(teachers)))
</code></pre>
<p>This worked fine for my small test dataset. However for my actual large dataset it crashed.</p>
<p>Is there a better way to do this?</p>
| <p>You can convert the columns to category type and then use the <code>codes</code> to create the <code>coo_matrix</code> object:</p>
<pre><code>import numpy as np
import string
import random
import pandas as pd
from scipy import sparse
lowercase = list(string.ascii_lowercase)
students = np.random.choice(lowercase, size=[20, 3]).view("<U3").ravel().tolist()
teachers = np.random.choice(lowercase, 8).tolist()
df = pd.DataFrame({"student": [random.choice(students) for _ in range(30)],
"teacher": [random.choice(teachers) for _ in range(30)]})
df = df.apply(lambda s:s.astype("category"))
arr = sparse.coo_matrix((np.ones(df.shape[0]),
(df.student.cat.codes, df.teacher.cat.codes)))
</code></pre>
<p>You can get the labels by <code>df.student.cat.categories</code> and <code>df.teacher.cat.categories</code>.</p>
|
How can make the ships to move in the direction they are facing after rotated them? <p>In the script i have 20 space ships. I store each ship start position and then check if each ship moved and travlled 50 distance i rotate the ship. This part is working fine.</p>
<p>Now i want to make that if i rotate each ship by 180 degrees once the ship rotated move to this direction. The problem is that the ship keep moving to the original direction even after rotated.</p>
<p>In the top of the script:</p>
<pre><code>private float distanceTravelled;
public bool updateOn = true;
private Vector3 lastPosition;
List<bool> hasRotated = new List<bool>();
List<float> distanceTraveled = new List<float>();
List<Vector3> lastPositions = new List<Vector3>();
</code></pre>
<p>In the Start function i'm adding the start positions of all the childs and also set each child to false:</p>
<pre><code>private void Start()
{
UpdateSpheres ();
spheres = GameObject.FindGameObjectsWithTag("MySphere");
for(int index = 0; index < spheres[0].transform.childCount;index++)
{
Transform child = spheres[0].transform.GetChild(index);
lastPosition = new Vector3(child.transform.position.x,child.transform.position.y,child.transform.position.z);
lastPositions.Add (lastPosition);
hasRotated.Add(false);
distanceTraveled.Add(0f);
}
}
</code></pre>
<p>In the Update function i create the ships that's the UpdateSpheres and then move and roate them with the MoveShips:</p>
<pre><code>private void Update()
{
UpdateSpheres();
MoveShips ();
}
</code></pre>
<p>Then in the MoveShips i'm trying to change the moving direction of each spaceship once it was rotated:</p>
<p>This is the original MoveShips function code:</p>
<pre><code>private void MoveShips()
{
for (int index = 0;index < spheres[0].transform.childCount;index++)
{
Transform oneChild = spheres[0].transform.GetChild(index);
lastPositions[index] = oneChild.transform.position;
oneChild.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
}
if (updateOn == true) {
for(int index =0;index < spheres[0].transform.childCount;index++)
{
Transform child = spheres[0].transform.GetChild(index);
distanceTraveled[index] += Vector3.Distance (child.transform.position, lastPositions [index]);
if (distanceTraveled[index] >= 50 && !hasRotated[index])
{
child.transform.Rotate (new Vector3 (0f, 180f, 0f));
hasRotated[index] = true;
}
}
}
}
</code></pre>
<p>Then i changed the MoveShips function and tried to use the line:</p>
<pre><code>oneChild.transform.position -= oneChild.transform.forward * Time.deltaTime * moveSpeed;
</code></pre>
<p>Or</p>
<pre><code>child.transform.position += child.transform.forward * Time.deltaTime * moveSpeed;
</code></pre>
<p>But in all cases the ships keep moving the original direction then never change the movement according to where they are facing after the rotation.</p>
<p>If i will rotate them by 1 degree by 20 degrees or by 180 i want them to move to the direction they are now facing after the rotation. Even if i change the rotation on the X axis Y axis or Z axis then move up down right left forward depending what axis i rotate on. But what i want to do now first is to rotate them 180 degrees so they will change direction after rotation and move to this direction. Now to move reverse but to the face direction.</p>
<p>So i'm trying to use the child transform forward instead the Vector3.forward but no success so far.</p>
<pre><code>private void MoveShips()
{
for (int index = 0;index < spheres[0].transform.childCount;index++)
{
Transform oneChild = spheres[0].transform.GetChild(index);
lastPositions[index] = oneChild.transform.position;
//oneChild.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
if (distanceTraveled [index] >= 50 && !hasRotated [index]) {
oneChild.transform.position -= oneChild.transform.forward * Time.deltaTime * moveSpeed;
} else
{
oneChild.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
}
}
if (updateOn == true) {
for(int index =0;index < spheres[0].transform.childCount;index++)
{
Transform child = spheres[0].transform.GetChild(index);
distanceTraveled[index] += Vector3.Distance (child.transform.position, lastPositions [index]);
if (distanceTraveled[index] >= 50 && !hasRotated[index])
{
child.transform.Rotate (new Vector3 (0f, 180f, 0f));
hasRotated[index] = true;
//child.transform.position += child.transform.forward * Time.deltaTime * moveSpeed;
}
}
}
}
</code></pre>
<p>Update:</p>
<p>The TurnShip turn them smooth but they are keep moving to the original direction and not changing the direction after the turn.</p>
<p>At top of script added:</p>
<pre><code>public float smooth = 1f;
private Vector3 targetAngles;
</code></pre>
<p>This is how my MoveShips looks like now:</p>
<pre><code>private void MoveShips()
{
for (int index = 0;index < spheres[0].transform.childCount;index++)
{
Transform oneChild = spheres[0].transform.GetChild(index);
lastPositions[index] = oneChild.transform.position;
oneChild.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
}
if (updateOn == true) {
for(int index =0;index < spheres[0].transform.childCount;index++)
{
Transform child = spheres[0].transform.GetChild(index);
distanceTraveled[index] += Vector3.Distance (child.transform.position, lastPositions [index]);
if (distanceTraveled[index] >= 50 && !hasRotated[index])
{
targetAngles = child.transform.eulerAngles + 180f * Vector3.up;
StartCoroutine (TurnShip (child.transform, child.transform.eulerAngles, targetAngles, smooth));
hasRotated[index] = true;
}
}
}
}
</code></pre>
<p>And the TurnShip function:</p>
<pre><code>IEnumerator TurnShip(Transform ship, Vector3 startAngle, Vector3 endAngle, float smooth)
{
float lerpSpeed = 0;
while(lerpSpeed < 1)
{
ship.eulerAngles = Vector3.Lerp(startAngle, endAngle, lerpSpeed);
lerpSpeed += Time.deltaTime * smooth;
yield return null;
}
}
</code></pre>
| <p>Have you tried Translate?</p>
<pre><code>// Example Forwards
child.transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
// Example Backwards
child.transform.Translate(Vector3.back * Time.deltaTime * moveSpeed);
// you could use: left, right, up, down, forward, back
</code></pre>
<p>Documentation : <a href="https://docs.unity3d.com/ScriptReference/Transform.Translate.html" rel="nofollow">https://docs.unity3d.com/ScriptReference/Transform.Translate.html</a></p>
|
GROUP BY & COUNT with multiple parameters <p>I have a simple configuration :
2 tables linked in a many-to-many relation, so it gave me 3 tables. </p>
<p>Table author:</p>
<pre><code>idAuthor INT
name VARCHAR
</code></pre>
<p>Table publication: </p>
<pre><code>idPublication INT,
title VARCHAR,
date YEAR,
type VARCHAR,
conference VARCHAR,
journal VARCHAR
</code></pre>
<p>Table author_has_publication:</p>
<pre><code>Author_idAuthor,
Publication_idPublication
</code></pre>
<p>I am trying to get all the authors name that have published at least 2 papers in conference SIGMOD and conference PVLDB.
Right now I achieved this but I still have a double result. My query :</p>
<pre><code>SELECT author.name, publication.journal, COUNT(*)
FROM author
INNER JOIN author_has_publication
ON author.idAuthor = author_has_publication.Author_idAuthor
INNER JOIN publication
ON author_has_publication.Publication_idPublication = publication.idPublication
GROUP BY publication.journal, author.name
HAVING COUNT(*) >= 2
AND (publication.journal = 'PVLDB' OR publication.journal = 'SIGMOD');
</code></pre>
<p>returns </p>
<pre><code>+-------+---------+----------+
| name | journal | COUNT(*) |
+-------+---------+----------+
| Renee | PVLDB | 2 |
| Renee | SIGMOD | 2 |
+-------+---------+----------+
</code></pre>
<p>As you can see the result is correct but doubled, as I just want 1 time the name. </p>
<p>Other question, how to modify the number parameter for only one conference, for example get all the author that published at least 3 SIGMOD and at least 1 PVLDB ? </p>
| <p>If you don't care about the <code>journal</code> , don't select it, it is splitting your results. Also, normal filters need to be placed in the <code>WHERE</code> clause, not the <code>HAVING</code> clause :</p>
<pre><code>SELECT author.name, COUNT(*)
FROM author
INNER JOIN author_has_publication
ON author.idAuthor = author_has_publication.Author_idAuthor
INNER JOIN publication
ON author_has_publication.Publication_idPublication =
publication.idPublication
WHERE publication.journal IN('PVLDB','SIGMOD')
GROUP BY author.name
HAVING COUNT(CASE WHEN publication.journal = 'SIGMOD' THEN 1 END) >= 2
AND COUNT(CASE WHEN publication.journal = 'PVLDB' THEN 1 END) >= 2;
</code></pre>
<p>For the second question, use this <code>HAVING()</code> clause :</p>
<pre><code>HAVING COUNT(CASE WHEN publication.journal = 'SIGMOD' THEN 1 END) >= 3
AND COUNT(CASE WHEN publication.journal = 'PVLDB' THEN 1 END) >= 1;
</code></pre>
|
MacOS and Swift 3 with CIAffineClamp filter <p>I need to use <code>CIAffineClamp</code> in order to extend the image and prevent Gaussian Blur from blurring out edges of the image. I have the following code working in Swift 2:</p>
<pre><code>let transform = CGAffineTransformIdentity
let clampFilter = CIFilter(name: "CIAffineClamp")
clampFilter.setValue(inputImage, forKey: "inputImage")
clampFilter.setValue(NSValue(CGAffineTransform: transform), forKey: "inputTransform")
</code></pre>
<p>In Swift 3 <code>CGAffineTransformIdentity</code> was renamed to <code>CGAffineTransform.identity</code>. My code compiles however I get the following error message in the console:</p>
<pre><code>[CIAffineClamp inputTransfom] is not a valid object.
</code></pre>
<p>Documentation on Apple's websites states that <code>inputTransform</code> parameter on MacOS takes <em>an <code>NSAffineTransform</code> object whose attribute type is <code>CIAttributeTypeTransform</code>.</em> but I'm unsure how to use it.</p>
<p>Any help would be appreciated.</p>
| <p>Seems <code>NSAffineTransform</code> has an initializer <code>NSAffineTransform.init(transform:)</code> which takes <code>AffineTransform</code>.</p>
<p>Please try this:</p>
<pre><code>let transform = AffineTransform.identity
let clampFilter = CIFilter(name: "CIAffineClamp")!
clampFilter.setValue(inputImage, forKey: "inputImage")
clampFilter.setValue(NSAffineTransform(transform: transform), forKey: "inputTransform")
</code></pre>
<p>Or the last line can be:</p>
<pre><code>clampFilter.setValue(transform, forKey: "inputTransform")
</code></pre>
<p><a href="https://developer.apple.com/reference/foundation/nsaffinetransform" rel="nofollow">NSAffineTransform</a></p>
<blockquote>
<h2>Important</h2>
<p>The Swift overlay to the Foundation framework provides the
<code>AffineTransform</code> structure, which bridges to the <code>NSAffineTransform</code>
class. The <code>AffineTransform</code> value type offers the same functionality as
the <code>NSAffineTransform</code> reference type, and the two can be used
interchangeably in Swift code that interacts with Objective-C APIs.
This behavior is similar to how Swift bridges standard string,
numeric, and collection types to their corresponding Foundation
classes.</p>
</blockquote>
|
Issue while running "lektor server" command on windows <p>Python version : 2.7</p>
<p>Showing the following error on lektor server command</p>
<pre><code>Traceback (most recent call last):
File "/Users/item4/Projects/lektor/lektor/devserver.py", line 49, in build
builder.prune()
File "/Users/item4/Projects/lektor/lektor/builder.py", line 1062, in prune
for aft in build_state.iter_unreferenced_artifacts(all=all):
File "/Users/item4/Projects/lektor/lektor/builder.py", line 371, in iter_unreferenced_artifacts
and is_primary_source''', [artifact_name])
ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.
</code></pre>
| <p>Finally I got the answer. It may helpful</p>
<p>I have edited /Users/item4/Projects/lektor/lektor/builder.py and added a single line</p>
<pre><code>con.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')
</code></pre>
<p>after the following line</p>
<pre><code>con = sqlite3.connect(self.buildstate_database_filename,
timeout=10, check_same_thread=False)
</code></pre>
<p>Ref Link : <a href="http://hakanu.net/sql/2015/08/25/sqlite-unicode-string-problem/" rel="nofollow">http://hakanu.net/sql/2015/08/25/sqlite-unicode-string-problem/</a></p>
|
Creating a Open File Dialog Function to be used multiple times <p>I have this piece of code that I would like to make it into a function so I can reuse it by changing some parameters.</p>
<p>So this is what I have so far</p>
<pre><code>Sub OpenFiles(InFile As IO.StreamReader, verifytheFileName As String,dialogBoxTitle As String)
Dim result As DialogResult
Dim FilePath As String
Dim FileName As String
Try
dialogBox1.Title = dialogBoxTitle
dialogBox1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
result = dialogBox1.ShowDialog 'Open This Dialog Box
FilePath = dialogBox1.FileName 'Gets the Path of the file and stores it in File Path Varible
FileName = dialogBox1.SafeFileName 'Gets the name of the file and stores it in File Name Varible
If Not FileName = verifytheFileName Then
MessageBox.Show("Please Select " &verifytheFileName)
dialogBox1.Reset()
Else
InFile = IO.File.OpenText(FilePath)
End If
Catch ex As Exception
MessageBox.Show("ERROR")
End Try
End Sub
</code></pre>
<p>So the only thing I am unable to do is to change the <code>dialogBox1</code> text in to <code>dialogBox2</code> or <code>dialogBox3</code>.</p>
<p>Please advice on how can I get this done</p>
| <p>Pass the dialogbox in parameters function</p>
<pre><code>Sub OpenFiles(InFile As IO.StreamReader, verifytheFileName As String,dialogBoxTitle As String, dialogBox1 as System.Windows.Forms.SaveFileDialog)
Dim result As DialogResult
Dim FilePath As String
Dim FileName As String
Try
dialogBox1.Title = dialogBoxTitle
dialogBox1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
result = dialogBox1.ShowDialog 'Open This Dialog Box
FilePath = dialogBox1.FileName 'Gets the Path of the file and stores it in File Path Varible
FileName = dialogBox1.SafeFileName 'Gets the name of the file and stores it in File Name Varible
If Not FileName = verifytheFileName Then
MessageBox.Show("Please Select " &verifytheFileName)
dialogBox1.Reset()
Else
InFile = IO.File.OpenText(FilePath)
End If
Catch ex As Exception
MessageBox.Show("ERROR")
End Try
End Sub
</code></pre>
|
Why is the integer not displayed when an exception occurred? <p>I have the following code:</p>
<pre><code>int main()
{
int i = 0;
cout << i; //why is i not printed even though it is before the exception?
int j = 1 / i; //divide by 0
j++;
cout << i << j;
return 0;
}
</code></pre>
<p>Why is <code>i</code> not printed? It should be printed, because it is before the exception occurs.</p>
<p>But nothing is getting printed, I just get the exception.</p>
<p>Any ideas?</p>
| <p>That's probably because the stream isn't flushed. On some platforms, it is flushed after every output, but on others, it is not.</p>
<p>So, if you flush it you'll get <code>0</code> as output:</p>
<pre><code>cout << i << flush; // 'flush' flushes the stream = displays everything immediately
</code></pre>
|
How to properly handle a variable with the same type as the class it belongs to? <p>I am using the two files below for my project. The variable I am referring to, <code>Node parent</code>, was originally not a pointer, but I quickly found out this doesn't work for obvious reasons (memory). </p>
<p>So I turned it into a pointer. The problem is that <code>parent</code> appears to not be properly handled in my code, so I end up with my application crashing when I execute a function like getParent(). What modifications would fix this problem?</p>
<p>Node.h</p>
<pre><code>#include <string>
#include <vector>
#include <iostream>
#include "Action.h"
class Node
{
</code></pre>
<p>Node.cpp</p>
<pre><code>#include "stdafx.h"
</code></pre>
| <p>You should check if <code>parent</code> is <code>nullptr</code> or not:</p>
<pre><code>bool Node::getParent( Node& node )
{
if ( parent )
{
node = *parent;
return true;
}
else
{
return false;
}
}
</code></pre>
<p>Note that you have to implement the proper copy-constructor of <code>Node</code> is needed.
A possible solution is to return the pointer or the reference of the parent node but in several implementation it is dangerous because you allow access directly to an internal member. Decide what is good for you.</p>
<p>Just a suggestion: if you use std::sharer_ptr or std::unique_ptr, some implementation would be much easier. </p>
|
Not good print HTML after load page <p>For example you're booking this hotel, after select room[s] hotel You must fill out the form[s].</p>
<p>This example, You have selected a room.</p>
<pre><code>lenHotel = 1;
plusCapacity = 2;
</code></pre>
<p>âScript:</p>
<pre><code>$(function () {
for(var i = 0; i < lenHotel; i++) {
$("#Step-02").find('#information-box').append(
"<h4>" + (i + 1) +" .Room Name</h4>" +
"<div class=\"box-content\">" +
"<div class=\"field-row clearfix\"> " +
"<input type=\"text\" placeholder=\"name\" id=\"name\"> " +
"</div><div class=\"field-row clearfix\">" +
"<div class=\"col-xs-6\"><select id=\"country\">" +
"<option value=\"0\">Select Country</option><option value=\"1\">Country name</option><option value=\"2\">Country name</option>" +
"</select></div>" +
"<div class=\"col-xs-6\">" );
if(hotel[i]['plusCapacity'] != 0) {
$("#Step-02").find('.col-xs-6').append(
"<select id=\"addPeople\">" +
"<option value=\"0\">add people</option>"
);
for(var j = 0; j < hotel[i]['plusCapacity']; j++) {
$(".col-xs-6").find('#addPeople').append(
"<option value=\"' + j + '\">' + j + '</option>"
);
}
} else {
$("#Step-02").find('#information-box').append(
"<div class=\"col-xs-6\"><select id=\"addPeople\" disabled>" +
"<option value=\"0\"> The opt-out add </option>"
);
}
$("#Step-02").find('#information-box').append("</select></div></div></div><hr />");
}
})
</code></pre>
<p>I just want to this HTML:</p>
<pre><code><div id="information-box">
<h4>1. Room name</h4>
<div class="box-content">
<div class="field-row clearfix">
<input type="text" placeholder="name" id="name">
</div>
<div class="field-row clearfix">
<div class="col-xs-6">
<select id="country">
<option value="0">Select Country</option>
<option value="1">country name</option>
<option value="2">country name</option>
</select>
</div>
<div class="col-xs-6">
<select id="addPeople">
<option value="0">add people</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
</div>
</div>
</code></pre>
<p>But, after print from script:</p>
<pre><code><div id="information-box">
<h4>1. Room name</h4>
<div class="box-content">
<div class="field-row clearfix">
<input id="name" placeholder="name" type="text">
</div>
<div class="field-row clearfix">
<div class="col-xs-6">
<select id="country">
<option value="0">Select country</option>
<option value="1">country name </option>
<option value="2">country name</option>
</select><select id="addPeople">
<option value="0">add people</option>
</select>
</div>
<div class="col-xs-6">
<select id="addPeople">
<option value="0">add people</option>
</select>
</div>
</div>
</div>
<hr>
</div>
</code></pre>
<p>Twice! print <code>addPeople</code> ... what is the problem?</p>
| <p>First look shows me few problems in your code. </p>
<p>You should make jQuery understand that where exactly you're trying to append the code. Because jQuery finds the fist element and append there only.</p>
<p>Use <code>.eq()</code> to find the index of <code>col-xs-6</code>. </p>
<p><code>$("#Step-02").find('.col-xs-6:eq(1)')</code> instead of </p>
<pre><code>$("#Step-02").find('.col-xs-6').append(
"<select id=\"addPeople\">" +
"<option value=\"0\">add people</option>"
);
</code></pre>
<p>Still, I would not suggest you to manipulate your DOM in loop. You should use a variable as a String and do concatenation in loop and then append it.</p>
<p><strong>Example</strong></p>
<pre><code>for(var i = 0; i < lenHotel; i++) {
var tempString = "";
tempString += "<div>";
tempString += "<select></select>";
tempString += "</div>";
//Append to the container
$('.container').append(tempString);
}
</code></pre>
<p>FYI, this is just an example about how to append long HTML in for loop, you can make necessary changes as per your need.</p>
|
structuring element to remove 1 pixel connection <p>I have been thinking and searching for this but could found anything! can anyone help me on this to finding the structuring element</p>
<p>Image is attached :
<img src="http://i.stack.imgur.com/2eYq1.png" alt="link to image "></p>
<p>Thanks</p>
| <p>What you want to do is to use a <a href="http://homepages.inf.ed.ac.uk/rbf/HIPR2/hitmiss.htm" rel="nofollow">hit or miss transformation</a>/operation, it's the operation used in most of <a href="https://en.wikipedia.org/wiki/Hit-or-miss_transform" rel="nofollow">skeleton/thinning transformation</a>. You look for a really specific pattern, and when you find it, you erase the central pixel.</p>
<p>In your case, you need to use structuring element like that:</p>
<pre><code>? 1 ? ? 0 ?
0 1 0 or 1 1 1
? 1 ? ? 0 ?
</code></pre>
<p>with 0 and 1 meaning black and with pixels respectively, and ? is wild.</p>
|
Cannot downcast from 'UIViewController' to a more optional type 'SubclassOfUIViewController<NSString>' <p>I have a Subclass of UIViewController that is defined as follows</p>
<pre><code>@interface SubclassOfViewController<__covariant Type> : UIViewController
@end
@implementation SubclassOfViewController @end
</code></pre>
<p>I am sending this subclass as a segue from screen change.</p>
<p>Now in prepareForSegue I am trying to do the following</p>
<pre><code> public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "embeddedScroll"){
if let vc = segue.destinationViewController as? SubclassOfViewController<NSString>!{
vc.dataSource = genericDataSource
}
}
}
</code></pre>
<p>And receiving the following message:</p>
<pre><code>Cannot downcast from 'UIViewController' to a more optional type 'SubclassOfViewController<NSString>!'
</code></pre>
<p>putting question marks instead of exclamation marks does not help.</p>
<p>How can I fix it?</p>
| <p>You usually do not use Optional types for <code>as?</code> casting.</p>
<p>Try just removing that <code>!</code>.</p>
<pre><code> if let vc = segue.destinationViewController as? SubclassOfViewController<NSString> {
</code></pre>
|
Pyomo Ipopt does not return solution <p>my script is:</p>
<pre><code> from __future__ import division
import numpy
import scipy
from pyomo.environ import *
from pyomo.dae import *
from pyomo.opt import SolverFactory
m=ConcreteModel()
m.x3=Var(within=NonNegativeReals)
m.u=Var(within=NonNegativeReals)
def _con(m):
return m.x3 >=3
m.con=Constraint(rule=_con)
def _con2(m):
return 4 >= m.u >=1
m.con2=Constraint(rule=_con2)
m.obj=Objective(expr=m.x3*m.u)
opt = SolverFactory("Ipopt", executable = "/Ipopt-3.12.6/bin/ipopt")
results = opt.solve(m)
results.write()
</code></pre>
<p>Although this is a very simple problem and although the program states that
it has found the optimal solution,
the number of solutions is 0 and there is not any solution displayed.</p>
<p>Any ideas??</p>
<p>Thanks a lot.</p>
| <p>In the most recent versions of Pyomo, the solution is loaded into the model by default. The results object should be used to check status information. If you want to interrogate the solution you can do so by accessing the model components directly and checking their value, or you can do the following:</p>
<pre><code>m.solutions.store_to(results)
results.write()
</code></pre>
|
Rails 4, Rspec and Factory Girl: URI::InvalidURIError (Multitenancy) <p>Im following a tutorial on Rails 4 and Multitenancy, but am getting an error when trying to test if a user can sign in as an owner and redirect to a created subdomain. </p>
<p>This is the test error:</p>
<pre><code>Failures:
1) User sign in signs in as an account owner successfully
Failure/Error: visit root_url
URI::InvalidURIError:
bad URI(is not URI?): http://#{account.subdomain}.example.com
# /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/rack_test/browser.rb:71:in `reset_host!'
# /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/rack_test/browser.rb:21:in `visit'
# /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/rack_test/driver.rb:43:in `visit'
# /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/session.rb:240:in `visit'
# /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/dsl.rb:52:in `block (2 levels) in <module:DSL>'
# ./spec/features/users/sign_in_spec.rb:9:in `block (3 levels) in <top (required)>'
Finished in 0.56981 seconds (files took 1.26 seconds to load)
11 examples, 1 failure, 6 pending
</code></pre>
<p>This is the test:</p>
<pre><code>require "rails_helper"
feature "User sign in" do
extend SubdomainHelpers
let!(:account) { FactoryGirl.create(:account) }
let(:sign_in_url) {"http://#{account.subdomain}.example.com/sign_in"}
let(:root_url) {"http://#{account.subdomain}.example.com/"}
within_account_subdomain do
scenario "signs in as an account owner successfully" do
visit root_url
expect(page.current_url).to eq(sign_in_url)
fill_in "Email", :with => account.owner.email
fill_in "Password", :with => "password"
click_button "Sign in"
expect(page).to have_content("You are now signed in.")
expect(page.current_url).to eq(root_url)
end
end
end
</code></pre>
<p>Here are the factories:</p>
<p>Account:</p>
<pre><code>FactoryGirl.define do
factory :account, :class => Subscribe::Account do
sequence(:name) { |n| "Test Account ##{n}" }
sequence(:subdomain) { |n| "test#{n}" }
association :owner, :factory => :user
end
end
</code></pre>
<p>User: </p>
<pre><code>FactoryGirl.define do
factory :user, :class => Subscribe::User do
sequence(:email) { |n| "test#{n}@example.com" }
password "password"
password_confirmation "password"
end
end
</code></pre>
<p>I am really not familiar with BDD, please let me know if you need me to post anything further.</p>
| <p>So I solved this:</p>
<p>The problem was in my SubdomainHelpers file </p>
<pre><code>module SubdomainHelpers
def within_account_subdomain
### This Line Is the original line
let(:subdomain_url) { 'http://#{account.subdomain}.example.com' }
### Changed it to this
let(:subdomain_url) { "http://#{account.subdomain}.example.com" }
before { Capybara.default_host = subdomain_url }
after { Capybara.default_host = 'http://www.example.com' }
yield
end
end
</code></pre>
<p>For some reason using single quotes was keeping <code>account.subdomain</code> as a string; as soon as I changed to double quotes the test passed! </p>
<p>Thanks. </p>
|
"Add as Library" button missing? <p>Trying to add external library jars to my project, but imports still don't work. Tutorials keep telling me to click "Add as library", but I don't have that option:</p>
<p><a href="http://i.stack.imgur.com/jQVkc.png" rel="nofollow"><img src="http://i.stack.imgur.com/jQVkc.png" alt="Missing Add as Library button"></a></p>
<p>But I did add them through Module Settings...</p>
<p><a href="http://i.stack.imgur.com/4kVQd.png" rel="nofollow"><img src="http://i.stack.imgur.com/4kVQd.png" alt="Module Settings"></a></p>
<p>I also added the 2 .jar files to: /src/main/libs/ and added this to build.gradle inside 'app'.</p>
<pre><code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.1'
compile 'de.hdodenhof:circleimageview:1.3.0'
--> compile files('src/main/libs/jsonbeans-0.5.jar')
--> compile files('src/main/libs/kryo-2.23.1-SNAPSHOT-all-debug.jar')
}
</code></pre>
<p>What else can I try to fix this?
I don't understand why imports just don't work since the files are included in my build.gradle.</p>
<p><strong>Edit: After changing the directory from <code>/src/main/libs/</code> to <code>/libs/</code> directly, nothing changed. Imports still do not work.</strong></p>
| <p>The <code>libs</code> folder should be a subfolder of <code>app</code>. Instead you have it buried in <code>app/src/main</code>. Note that you already have a dependency for the <code>libs</code> folder if you put it in the correct place.</p>
<p>When you use a file manager or the command line to move files to your Android Studio project, you sometimes need to synchronize the folder structure by right clicking in the Project pane and clicking Synchronize in the popup menu.</p>
|
avoiding circular inclusion when having to pass back values <p>what is the best way to handle circular inclusions in the situation where I have a class that communicates with another class, like an API and gets callbacks from that class.</p>
<p>Assume I have a class</p>
<p>.h</p>
<pre><code>class Requestor;
class Api
{
public:
Api();
void Request();
int DoStuff();
private:
Requestor *p_rq_;
};
</code></pre>
<p>.cpp</p>
<pre><code>#include "api.h"
#include "requestor.h"
Api::Api()
{
}
void Api::Request() {
this->DoStuff();
}
void Api::ReturnRequestId( int id ) {
this->p_rq->SetLastRequestId( id );
}
</code></pre>
<p>and</p>
<p>.h </p>
<pre><code>class Api;
class Requestor
{
public:
Requestor();
void MakeRequest();
void SetLastRequestId( int );
private:
Api api_;
int last_request_id_;
};
</code></pre>
<p>.cpp</p>
<pre><code>#include "requestor.h"
#include "api.h"
Requestor::Requestor()
{
}
void Requestor::MakeRequest() {
this->api_.Request();
}
void Requestor::SetLastRequestId( int id ) {
this->last_request_id_ = id;
}
</code></pre>
<p>In case requestor sends a request and at some point the api gets an id and wants to pass that back to the requestor, how can I do that without including each others .h file which would lead to circular inclusion?
Assume that I cant simply have the function MakeRequest return the id as I dont want to hold that thread until api gets the id?</p>
<p>I am fairly new to c++ and programming, so I may miss the obvious solution. Since I need to call member functions of each other, it is my understanding that forward declaration does not work here.</p>
<p>Also, Api and Requestor should be separate libraries, so I can't make them one class.</p>
| <p>Use </p>
<pre><code>#ifndef __filex__
#define __filex__
</code></pre>
<p>At the beginning of each .h and </p>
<pre><code>#endif
</code></pre>
<p>At the end. </p>
<p>This way, the .h file is read only once</p>
|
powershell cmdlet C#? <p>I'm tired to search about way to use powershell in C#, this first time to use Powershell and I don't know how to add it in C#, i have my codes working in Powershell any help to add in C#?</p>
<pre><code>New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts"
New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"
New-ItemProperty -path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" -name BigBear -value "0" -propertyType DWord
</code></pre>
<p>(BigBear) it's name and I want to change it with textbox</p>
<p>i tried this</p>
<pre><code> private void Shell()
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
// using (var powerShell = PowerShell.Create())
// {
// powerShell.Runspace = runspace;
// powerShell.AddScript(@"Hidden.ps1");
// //powerShell.AddParameter("UserName", UserName.Text);
// powerShell.Invoke();
// }
using (var powerShell = PowerShell.Create())
{
powerShell.Runspace = runspace;
powerShell.AddCommand("New-Item -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\"");
powerShell.AddCommand("New-Item -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList\"");
powerShell.AddCommand("New-ItemProperty -path \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList\" -name " + UserName.Text + " -value \"0\" -propertyType DWord");
//powerShell.AddParameter("ParamA", varA);
var results = powerShell.Invoke();
// Do whatever with results
}
}
</code></pre>
| <p>What have you tried?</p>
<p>Here are some links that describes how it can be done. But your question is not very detailed on your requirements... The last one have code you can download and try/modify!</p>
<p><a href="https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/" rel="nofollow">https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/</a></p>
<p><a href="http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C" rel="nofollow">http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C</a></p>
|
Get records created after a particular time of day <p>Say I have an <code>Event</code> model with a <code>date_time</code> field representing the date time the event is held, and I want to see all Events that are held, say, 'after 10pm', or 'before 7am' across multiple dates. How could I do this? </p>
<hr>
<p>My first thought was something like this: </p>
<p><code>scope :after_time ->(time){ where("events.date_time::time between ?::time and '23:59'::time", time) }
</code></p>
<p>But this doesn't work because dates are stored in UTC and converted to the app's timezone by ActiveRecord. </p>
<p>So let's say I'm searching for Events after 5pm, from my local Adelaide time. The eventual query is this: </p>
<p><code>WHERE (events.date_time::time between '2016-10-09 06:30:00.000000'::time and '23:59'::time)
</code></p>
<p>That is, because my timezone is +10:30 (Adelaide time), it's now trying to calculate between 6:30am and midnight, where it really needs to be finding ones created between 6:30am and 1:30pm utc. </p>
<p>Now, for this example in particular I could probably hack something together to work out what the 'midnight' time needs to be given the time zone difference. But the <code>between <given time> and <midnight in Adelaide></code> calculation isn't going to work if that period spans midnight utc. So that solution is bust. </p>
<hr>
<p>UPDATE:</p>
<p>I <em>think</em> I've managed to get the result I want by trial and error, but I'm not sure I understand exactly what's going on.</p>
<p><code>scope :after_time, ->(time) {
time = time.strftime('%H:%M:%S')
where_clause = <<-SQL
(events.date_time at time zone 'UTC' at time zone 'ACDT')::time
between ? and '23:59:59'
SQL
joins(:performances).where(where_clause, time)
}</code></p>
<p>It's basically turning everything into the one time zone so the query for each row ends up looking something like <code>WHERE '20:30:00' between '17:00:00' and '23:59:59'</code>, so I'm not having to worry about times spanning over midnight. </p>
<p>Even still, I feel like there's probably a proper way to do this, so I'm open to suggestions. </p>
| <p>Check if this works for you,</p>
<pre><code>s = DateTime.now.change(hour: 6, min: 30).utc
e = Date.today.end_of_day.utc
Event.where("date_time::time between ?::time and ?::time", s, e)
</code></pre>
|
FilesMatch - how to make every file downloadable attachment? <p>I have the following FilesMatch directive in my .htaccess:</p>
<pre><code><FilesMatch "\.(?i:mp4|pdf)$">
Header set Content-Disposition attachment
</FilesMatch>
</code></pre>
<p>I cannot find the right expression to have <strong>every</strong> single file to be downloadable - and I don't want to add all the extensions ... </p>
<p>How can I make this work for all files?</p>
| <p>You can try this</p>
<pre><code><FilesMatch "(?i)\.(mp4|pdf)$">
Header set Content-Disposition attachment
</FilesMatch>
</code></pre>
<p>But if you mean to allow all file extension then you can try this:</p>
<pre><code><FilesMatch "\.+$">
Header set Content-Disposition attachment
</FilesMatch>
</code></pre>
|
Which could be the best way for communication of Micro-services without any HARD-CODE <p>I having a bunch of microservices which communicates with each other using <code>RestTemplate</code>. All the communication of microservices is from API gateway.</p>
<p>I am doing as following,</p>
<pre><code> public List<ServiceInstance> serviceInstancesByApplicationName(String applicationName) {
return this.discoveryClient.getInstances(applicationName);
}
//some Other logic
List<ServiceInstance> apigatewaymsInstanceList = discoveryClient.getInstances(apigatewaymsName);
ServiceInstance apigatewaymsInstance = apigatewaymsInstanceList.get(0);
//and
restTemplate.exchange(apigatewaymsInstance.getUri().toString() + plmpayloadprocessmsResource, HttpMethod.POST,
entity, String.class);
</code></pre>
<p>But here it appears like a hard code. Is there some another approach I am missing? What could be the best way ?</p>
<p>Likewise, I am asking is there any method available so that I can pass the name of application and eureka return me its full URI no need to do <code>applicationgetInstaceId(0);</code></p>
| <p>Try using Feign - it is a declarative REST client. It does not require any boilerplate that you mentioned. Checkout spring-cloud-netflix documentation for more details. In short, your REST client would look like this:</p>
<pre><code>@FeignClient(name = "service-name", path = "/base-path")
public interface MyClient{
@RequestMapping(method = RequestMethod.GET, value = "/greeting")
String getGreeting();
}
</code></pre>
<p>Invoking <strong>getGreeting</strong> method would result in sending GET request to a service named <strong>service-name</strong> and url <strong>/base-path/greeting</strong></p>
|
Implicit library linking and GetModuleHandle/GetProcAdress <p>We are trying to understand some of the finer details of locating a symbol at runtime. I've already reviewed Jeffrey Richter's <a href="http://rads.stackoverflow.com/amzn/click/1572319968" rel="nofollow">Programming Applications for Microsoft Windows</a>, Chapters 19 (<em>DLL Basics</em>) and 20 (<em>DLL Advanced</em>). Richter is a bit more comprehensive and more cohesive than MSDN.</p>
<p>We are trying to combine implicit library linking with dynamic symbol location. We want to avoid calls to <code>LoadLibrary</code> because of some of the potential security hazards. We are also trying to avoid loader lock issues <em>if</em> a user wanders into doing too much in a <code>DllMain</code> function.</p>
<pre class="lang-cxx prettyprint-override"><code>#include <windows.h>
#pragma comment(lib, "kernel32")
extern "C" {
typedef BOOL (WINAPI * PFN_GOR)(HANDLE, LPOVERLAPPED, LPDWORD, BOOL);
typedef BOOL (WINAPI * PFN_GORX)(HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL);
}
int main(int argc, char* argv[])
{
HINSTANCE hInst = GetModuleHandle("kernel32");
PFN_GOR pfn1 = hInst ? (PFN_GOR)GetProcAddress(hInst, "GetOverlappedResult") : NULL;
PFN_GORX pfn2 = hInst ? (PFN_GORX)GetProcAddress(hInst, "GetOverlappedResultEx") : NULL;
std::cout << "kernel32: " << std::hex << (void*)hInst << std::endl;
std::cout << "GetOverlappedResult: " << std::hex << (void*)pfn1 << std::endl;
std::cout << "GetOverlappedResultEx: " << std::hex << (void*)pfn2 << std::endl;
return 0;
}
</code></pre>
<p>We kind of got lucky with <code>GetOverlappedResult</code> and <code>GetOverlappedResultEx</code> because <code>kernel32.dll</code> provides both of them regardless of the platform. <code>kernel32.dll</code> has another nice property because every Windows application links to it, and there's no way to disgorge it.</p>
<p>Random numbers from the platform appear to be a little more troublesome. On Windows 7 and below we have <code>CryptGenRandom</code> from <code>advapi32.dll</code>; while Windows 10 and above uses <code>BCryptGenRandom</code> from <code>bcrypt.dll</code>. Windows 8 is a grey area because some versions, like Windows Phone 8, do not offer anything. We believe we can guard inclusion of a library based on <code>WINVER</code> or <code>_WINNT_VER</code>.</p>
<p>I feel like the pattern of implicit library linking combined with <code>GetModuleHandle</code> and <code>GetProcAdress</code> is unusual but it meets our requirements. Its unusual because it uses implicit linking and <code>GetModuleHandle</code> rather than <code>LoadLibrary</code>. I also cannot find text that forbids implicit linking and <code>GetModuleHandle</code>.</p>
<p>It meets our requirements because we will not be responsible for insecure library loading due to binary planting and other DLL redirection tricks. We will also avoid DoS'es from accidental mis-use by doing too much in a <code>DLLmain</code>.</p>
<p>My question is, is the code a legal combination or pattern. If its a defective pattern, then what is the defect?</p>
<hr>
<p>We support Windows XP and Visual Studio .Net through Windows 10/Phone 10/Store 10 using Visual Studio 2015.</p>
<p>On Windows XP the code produces the following result:</p>
<pre class="lang-none prettyprint-override"><code>>cl.exe /TP /EHsc test.cxx /Fetest.exe
...
>.\test.exe
kernel32: 7D4C0000
GetOverlappedResult: 7D52E12C
GetOverlappedResultEx: 00000000
</code></pre>
<p>On Windows 7 the code produces the following result:</p>
<pre class="lang-none prettyprint-override"><code>>cl.exe /TP /EHsc test.cxx /Fetest.exe
...
>.\test.exe
kernel32: 772A0000
GetOverlappedResult: 772CCC69
GetOverlappedResultEx: 00000000
</code></pre>
<p>On Windows 8 the code produces the following result (Windows 10 is similar):</p>
<pre class="lang-none prettyprint-override"><code>>cl.exe /TP /EHsc test.cxx /Fetest.exe
...
>.\test.exe
kernel32: 74FD0000
GetOverlappedResult: 74FEF8C0
GetOverlappedResultEx: 7675C4D0
</code></pre>
<p>On Windows 8 and 10 we can only test the cross-compile and link with ARM Developer Prompt. We test the compile for Desktop, Phone and Store using the following additional <code>CXXFLAGS</code>:</p>
<ul>
<li>To test Desktop app, add the following <code>CXXFLAGS</code>:
<ul>
<li><code>/DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP</code></li>
</ul></li>
<li>To test Windows Store app, add the following <code>CXXFLAGS</code>:
<ul>
<li><code>/DWINAPI_FAMILY=WINAPI_FAMILY_APP</code></li>
</ul></li>
<li>To test Windows Phone, add the following <code>CXXFLAGS</code>:
<ul>
<li><code>/DWINAPI_FAMILY=WINAPI_FAMILY_PHONE_APP</code></li>
</ul></li>
<li>To test Surface RT (ARM tablet), add the following <code>CXXFLAGS</code>:
<ul>
<li><code>/D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1 /DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP</code></li>
</ul></li>
</ul>
<hr>
<p>I'm finding lots of hits like <a href="http://stackoverflow.com/q/4794032">Implicit vs. Explicit linking to a DLL</a>, but I have not been able to find one that examines some of the security issues that <code>LoadLibrary</code> can impose, and how to avoid <code>LoadLibrary</code> altogether. </p>
| <p>Not much to say here. It is perfectly legal to use <code>GetProcAddress</code> with a module handle obtained by calling <code>GetModuleHandle</code>. </p>
<p><strong>Update</strong>: I wrote this based on the original form of the question which did not make it clear that the question is meant to cover mobile platforms as well as desktop. </p>
|
How to pass JSON Data Using PHP CURL in WePay API? <p>I want to use WePay reports API for reporting purpose to show WePay transaction and withdrawal information in my custom application . When I call Wepayreports api I have faced some issues in passing JSON Data using PHP CURL.</p>
<p>My Code like below:</p>
<pre><code><?php
$data = array(
"type" => "merchant_transactions",
"resource" => array(
"object_type" => "account",
"object_id" => 634303761
)
);
$ch = curl_init('https://stage.wepayapi.com/v2/report/create'); // URL of the call
CURL_SETOPT($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8');
// execute the api call
$result = curl_exec($ch);
// display the json response
echo '<pre>';
print_r(json_decode($result, true));
echo '</pre>';
?>
</code></pre>
<p>When i am trying to call this in API Calls receive data like below</p>
<pre><code>{"{\"type\":\"merchant_transactions\",\"resource\":{\"object_type\":\"account\",\"object_id\":\"1776251645\"}}":""}
</code></pre>
<p>But i need to send data like below:</p>
<pre><code>{"type":"merchant_transactions","resource":{"object_type":"account","object_id":"1776251645"}}
</code></pre>
<p>For you kind reference here is the link of WePay API Documantation.<a href="https://developer.wepay.com/api-calls/reports" rel="nofollow">WePay Reports API</a></p>
<p>If you have any other alternative solution for solving this issue please let me know.</p>
<p>Can anyone help me on this regards?Any kind of help appreciated.
Thanks in advance.</p>
| <p>Quoting from <a href="https://developer.wepay.com/general/api-call" rel="nofollow">https://developer.wepay.com/general/api-call</a></p>
<blockquote>
<p>Call arguments should be passed as JSON in the body of the request
with content-type HTTP header set to application/json. Make sure to
set a valid User-Agent header (our SDKs do this for you). The
User-Agent can be anything, but keep it informative. For example:
âWePay v2 PHP SDK v0.0.9â.</p>
</blockquote>
<p>And your answer lies here:
<a href="http://stackoverflow.com/questions/21271140/curl-and-php-how-can-i-pass-a-json-through-curl-by-put-post-get">Curl and PHP - how can I pass a json through curl by PUT,POST,GET</a></p>
<pre><code><?php
$data = array(
"type" => "merchant_transactions",
"resource" => array(
"object_type" => "account",
"object_id" => 634303761
)
);
$data_json = json_encode($data);
$ch = curl_init('https://stage.wepayapi.com/v2/report/create'); // URL of the call
CURL_SETOPT($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8');
// execute the api call
$result = curl_exec($ch);
// display the json response
echo '<pre>';
print_r(json_decode($result, true));
echo '</pre>';
?>
</code></pre>
|
try to find the shortest path between two points in a (x,y) coordinate system in C++. Got 11db erro <p>This is part of my homework which is to find the shortest path between two points in a x,y graph (the size of the graph is 640*340.). THE PATH SHOULD ONLY GO THROUGH THE POINTS WHERE (X,Y)VALUES ARE INTEGERS. I am new to C++, but the teacher told us we have code it in C++. My code is as follows:</p>
<pre><code>#include <iostream>
#include <unordered_map>
#include <utility>
#include <array>
#include <cmath>
using namespace std;
class nodePoint {
public:
int x;
int y; // the x, y cordinates of each point
nodePoint * prevPostion; // a pointer towards the previous point in the path leading to it.
int distance; // how many "points" away from the starting point.
};
void findshortest (nodePoint start,nodePoint end){
for (int i=-1; i<2; i++) {
for (int j=-1; j<2; j++) {
nodePoint *nextNode=new nodePoint();
nextNode->x=start.x+i;
nextNode->y=start.y+i;// iterate all the neighboring points of the point.
if (nextNode->x <= 640 && nextNode->y <=360 && nextNode->x >=0 &&nextNode->y>=0 )// check to see if the point is out of the bound
{
if (nextNode->x==end.x && nextNode->y==end.y) // the point is the ending points.
{
if (end.distance>start.distance+1) {
end.prevPostion=&start;
end.distance=start.distance+1;
}
}else{
findshortest(*nextNode, end);
}
}
}
}
}
int main()
{
nodePoint *one=new nodePoint();// "one" is the starting point
one->x=1;
one->y=2; //just for testing.
one->distance=0;
nodePoint *two=new nodePoint();// "two" is the end point
two->x=3;
two->y=4; // just for testing.
two->distance=pow(two->distance, 10);//set the initial distance value of the end point. It should be a very big number, so that it will be replaced later.
findshortest(*one, *two); //look for the shortest path using the function we just defined.
nodePoint *printer=new nodePoint(); // set a node to iterate over the shortest path through the previous node.
printer=two;
while (two->prevPostion!=NULL) {
printf("%d,%d",printer->x,printer->y); // print out the (x,y) value of each of the point on the path.
printer=two->prevPostion;
}
return 0;
}
</code></pre>
| <p>I dont really understand what you're trying to do here but i know u should use floats or doubles instead of ints if you want to get a decimal anwser.</p>
<p>By the way isn't the shortest past just Pythagorean Theorem?</p>
<p>The shortest path for the points (Ax, Ay) and (Bx, By) should be sqrt( (Bx-Ax)^2 + (By-Ay)^2 )</p>
|
Android :: Camera widget example <p>I have been looking for a widget that contain a camera inside without opening the camera app itself.</p>
<p>here is the only example i found:
<a href="https://www.youtube.com/watch?v=QOJF4eZjzhU" rel="nofollow">https://www.youtube.com/watch?v=QOJF4eZjzhU</a></p>
<p>Any help or advice is really appreciated.</p>
| <p>You can do this with <code>SurfaceView</code> as described <a href="https://developer.android.com/reference/android/hardware/camera2/package-summary.html" rel="nofollow">here</a>.</p>
|
WPF Change the object opacity in Circular way <p>For the sake of example lets assume I have Captain America's two shields as displayed in image. I am laying new image underneath the old. Now upon some interaction like a button click, I want an animation effect</p>
<p><a href="http://i.stack.imgur.com/CR1yf.png" rel="nofollow"><img src="http://i.stack.imgur.com/CR1yf.png" alt="enter image description here"></a></p>
<p>In my images the center part like the star in the middle is same, so animation should go from there, and then it should give effect like blue stripe change then silver then blue.</p>
<p>What I think would go is the older image, loses its opacity in a circular way so the shield underneath it should unfold.</p>
| <p>From my understanding, you have two images, one placed on top on the other. Then you want the top image to turn completely transparent, starting at the center and then spreading out to the perimeter until the entire top image is no longer visible and the bottom image shows through.</p>
<p>To do this, I would advise you use an <a href="https://msdn.microsoft.com/en-us/library/ms743320(v=vs.110).aspx" rel="nofollow">OpacityMask</a> with a <a href="https://msdn.microsoft.com/en-us/library/bb979781(v=vs.95).aspx" rel="nofollow">RadialGradientBrush</a> as the <code>OpacityMask</code>. I would then animate the <code>Offset</code> property of the <code>GradientStop</code> elements as described <a href="http://stackoverflow.com/questions/11842825/animate-a-linear-brush-using-a-data-trigger">here</a> and <a href="https://msdn.microsoft.com/en-us/library/ms748815(v=vs.110).aspx" rel="nofollow">here</a>.</p>
<p>Here's a full example of how you could achieve this. I've used a <code>ToggleButton</code> here just to give me something to bind to.</p>
<pre><code><ToggleButton>
<ToggleButton.Template>
<ControlTemplate>
<Grid Background="Transparent">
<Image Source="Resources/ShieldTwo.png"/>
<Image Source="Resources/ShieldOne.png">
<Image.OpacityMask>
<RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">
<GradientStop Color="Transparent" Offset="0"/>
<GradientStop Color="Transparent" Offset="0.0"/>
<GradientStop Color="Black" Offset="0.0"/>
<GradientStop Color="Black" Offset="1"/>
</RadialGradientBrush>
</Image.OpacityMask>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource FindAncestor, AncestorType=ToggleButton}}" Value="true">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="OpacityMask.(RadialGradientBrush.GradientStops)[1].(GradientStop.Offset)"
From="0"
To="1"
Duration="0:0:1"/>
<DoubleAnimation Storyboard.TargetProperty="OpacityMask.(RadialGradientBrush.GradientStops)[2].(GradientStop.Offset)"
From="0"
To="1"
Duration="0:0:1"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="OpacityMask.(RadialGradientBrush.GradientStops)[1].(GradientStop.Offset)"
From="1"
To="0"
Duration="0:0:1"/>
<DoubleAnimation Storyboard.TargetProperty="OpacityMask.(RadialGradientBrush.GradientStops)[2].(GradientStop.Offset)"
From="1"
To="0"
Duration="0:0:1"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</code></pre>
<p>And here's what the final product would look like. The images aren't perfectly lined up, but you get the point.</p>
<p><a href="http://i.stack.imgur.com/U8Evd.gif" rel="nofollow"><img src="http://i.stack.imgur.com/U8Evd.gif" alt="enter image description here"></a></p>
<p>Let me know if you need any further help.</p>
|
Eclipse import a plugin as source project but it's not include src folder <p>I want to modify the plugin org.eclipse.jface.text's source code and build my own plugin.I opened the Plug-ins window(<code>Window > Show View > Plug-ins</code>),found org.eclipse.jface.text,<code>right click > Import as > Source Project</code>. Serveal seconds later, I can find the project org.eclipse.jface.text on Package Explorer. However,this project does not include src folder and I can't find any <code>.java</code> files, it's a Binary Project.<br/>
<p>My Eclipse Info:<br/>
Type: Eclipse Java EE IDE for Web Developers.<br/>
Version: Indigo Service Release 2<br/>
Build id: 20120216-1857
<p>Can someone give me a solusion to solve this problem?</p>
| <p>I think that you should try importing the plugin with the source using the dedicated wizard(<code>File > Import... > Plug-in Development > Plug-ins</code>) as shown in <a href="http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.pde.doc.user%2Fguide%2Ftools%2Fimport_wizards%2Fimport_plugins.htm" rel="nofollow">this page</a> of the official Eclipse documentation.</p>
|
How to fetch data from mongodb using nodejs, expressjs <p><strong>Here is my code
file name student.js</strong></p>
<pre><code>var mongoose = require('mongoose');
var studentSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
rollno:{
type: Number,
required: true
},
grade:{
type: String,
required: true
},
result:{
type: String,
required: true
}
});
var Student = module.exports = mongoose.model('Student',studentSchema);
module.exports.getStudents = function (callback){
Student.find(callback);
}
**filename app.js**
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var PORT= process.env.PORT || 3000;
Student = require('./models/student');
mongoose.connect('mongodb://localhost/register');
var db= mongoose.connection;
app.get('/api/student', function (req,res){
Student.getStudents(function (err, student){
if(err){
throw err;
}
res.json(student);
});
});
app.listen(PORT);
console.log('Running app on port:' + PORT);
</code></pre>
| <p>If you have an existing collection that you want to query using Mongoose, you should pass the name of that collection to the schema explicitly:</p>
<pre><code>var studentSchema = new mongoose.Schema({ ... }, { collection : 'student' });
</code></pre>
<p>If you don't, Mongoose will generate a collection name for you, by lowercasing <em>and pluralizing</em> the model name (so documents for the model <code>Student</code> will be stored in the collection called <code>students</code>; notice the trailing <code>-s</code>).</p>
<p>More documentation <a href="http://mongoosejs.com/docs/guide.html#collection" rel="nofollow">here</a>.</p>
|
What are core algorithms behind Deepmind? <p>I am wondering what kind of algorithmic strategy is used in <a href="https://deepmind.com/" rel="nofollow">Deepmind</a> and Alpha Go. Is is better than other AI algorithmic approaches?</p>
| <p>The algorithm which is used by DeepMind is called "neural pushdown automata". That is a stackmachine like Forth or Java-Virtual-Machine with the addition that the code is generated by a neural network. <a href="https://arxiv.org/pdf/1605.06640.pdf" rel="nofollow">Programming with a Differentiable Forth Interpreter</a>. A neural stackmachine instead of a neural register-machine was chosen, because stackmachines are easier to implement and the hope is, that the neural network can faster optimize the weights.</p>
|
Static methods with __construct <p>I need to use static methods with <code>__construct()</code> method to instantiate the <code>Client</code> object but the as far as I know there is no way to use the <code>__construct()</code> since the object is not instantiated when using static methods.</p>
<p>I thought I can use an init method.</p>
<pre><code>class API
{
static $client;
public static function init()
{
$settings = [
'username' => 'user1',
];
self::$client = new Client($settings);
}
public static function foo( )
{
self::$client->action('Foo text');
}
}
API::init();
</code></pre>
<p>Then I can load the above class in other places and do the below.</p>
<pre><code>API::foo();
</code></pre>
<p><strong>My Questions:</strong> </p>
<ol>
<li>Is there anything wrong with the way I wrote the class? </li>
<li>Does the above codes cause performance issue?</li>
<li>Is there any better way?</li>
</ol>
<p>Any help is appreciated.</p>
| <p>As an approach this method is fine, but to be more <a href="https://en.m.wikipedia.org/wiki/SOLID_(object-oriented_design)" rel="nofollow">SOLID</a> here I would pass <code>Client</code> in <code>init()</code> function like <code>init(Client $client)</code> rather than instantiating it right in class. So do and <code>$settings</code>, better pass as an argument or preserve in some <code>private</code> variable rather than hardcoding in initializer.</p>
<p>It refers to <strong><a href="https://en.m.wikipedia.org/wiki/Dependency_inversion_principle" rel="nofollow">D</a></strong> and <strong><a href="https://en.m.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">L</a></strong> letter, the <a href="https://en.m.wikipedia.org/wiki/Dependency_inversion_principle" rel="nofollow">Dependency Inversion Principle</a> and <a href="https://en.m.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">Liskov Substitution Principle</a></p>
<p>No performance issues, but only an architectural approach. But as to me I don't see any preconditions here for avoiding constructor and use <code>$api = new API($client, $settings);</code> rather than static invocation.</p>
<p>And constructor (<em>or initializer</em>) signature would look like</p>
<pre class="lang-php prettyprint-override"><code>public function __construct(Client $client, array $settings);
</code></pre>
|
ElasticSearch group and distribute to buckets <p>I am quite new to elasticsearch but it seems that there is no easy way to create aggregation and distribute doc_count to buckets once previous aggregation is done.
For example I have below set of data and I would like to create 4 buckets and group profiles that have specific numbers of transactions between the buckets.</p>
<p>Total number of profiles should be distributed to below buckets, where each bucket outlines min and max number of transactions that one profile could have.</p>
<p>number of profiles that has 0-1 transaction</p>
<p>number of profiles that has 2-5 transactions</p>
<p>number of profiles that has 6-20 transactions</p>
<p>number of profiles that has 20+ transactions</p>
<pre><code>[
{
"profileId": "AVdiZnj6YuzD-vV0m9lx",
"transactionId": "sdsfsdghfd"
},
{
"profileId": "SRGDDUUDaasaddsaf",
"transactionId": "asdadscfdvdvd"
},
{
"profileId": "AVdiZnj6YuzD-vV0m9lx",
"transactionId": "sdsacfsfcsafcs"
}
]
Below request would show number of transactions per each profile but additional bucket grouping is required in order to group profiles to respective buckets using doc_cont.
{ "size":0,
"aggs" : {
"profileTransactions" : {
"terms" : {
"field" : "profileId"
}
}
}
}
"buckets": [
{
"key": "AVdiZnj6YuzD-vV0m9lx",
"doc_count": 2
},
{
"key": "SRGDDUUDaasaddsaf",
"doc_count": 1
}
]
</code></pre>
<p>Any Ideas?</p>
| <p>You could do additional grouping with the help of <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-selector-aggregation.html" rel="nofollow">pipeline bucket selector aggregation</a>. The <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html" rel="nofollow">value count aggregation</a> is used since bucket aggregation is checked against a numeric field. This query will require <strong>ES 2.x</strong> version.</p>
<pre><code>{
"size": 0,
"aggs": {
"unique_profileId0": {
"terms": {
"field": "profileId"
},
"aggs": {
"total_profile_count": {
"value_count": {
"field": "profileId"
}
},
"range_0-1_bucket": {
"bucket_selector": {
"buckets_path": {
"totalTransaction": "total_profile_count"
},
"script": "totalTransaction < 2"
}
}
}
},
"unique_profileId1": {
"terms": {
"field": "profileId"
},
"aggs": {
"total_profile_count": {
"value_count": {
"field": "profileId"
}
},
"range_2-5_bucket": {
"bucket_selector": {
"buckets_path": {
"totalTransaction": "total_profile_count"
},
"script": "totalTransaction >= 2 && totalTransaction <= 5"
}
}
}
},
"unique_profileId2": {
"terms": {
"field": "profileId"
},
"aggs": {
"total_profile_count": {
"value_count": {
"field": "profileId"
}
},
"range_6-20_bucket": {
"bucket_selector": {
"buckets_path": {
"totalTransaction": "total_profile_count"
},
"script": "totalTransaction >= 6 && totalTransaction <= 20"
}
}
}
},
"unique_profileId3": {
"terms": {
"field": "profileId"
},
"aggs": {
"total_profile_count": {
"value_count": {
"field": "profileId"
}
},
"range_20_more_bucket": {
"bucket_selector": {
"buckets_path": {
"totalTransaction": "total_profile_count"
},
"script": "totalTransaction > 20"
}
}
}
}
}
}
</code></pre>
<p>You need to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html#enable-dynamic-scripting" rel="nofollow">enable dynamic scripting</a> for this to work, add following two lines to the YML file</p>
<pre><code>script.inline: on
script.indexed: on
</code></pre>
<p>and <strong>restart</strong> each node.</p>
<p>Hope it helps!</p>
|
QSQLITE driver not loaded <p>Im trying to make a program in Qt that uses a SqlLite database, but i can not get it to work...<br><br>
When i try to execute a query i get the error:<br>
Driver not loaded Driver not loaded<br><br>
But when i print out the drivers that are available i get:<br>
("QSQLITE", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7")<br><br>
I have downloaded the SqlLite dll for both 32 bit & 64 bit and when put ether of them in my release folder (after using windeployqt) i still get the same error..<br><br>
So it should be available for use or am i missing some thing? </p>
| <p>You need to create folder <code>sqldrivers</code> near the executable and copy there the files from folder <code>plugins/sqldrivers</code> from where your Qt system is installed. (at least qsqlite4.dll or 5 or so on dependently from your Qt version)</p>
<p>I do not meet necessity to download SqlLite dll to make sqlite database work in my projects in Qt4.</p>
|
PhoneGap/Cordova app notifications <p>I am new to PhoneGap/Cordova, i am looking to add some notifications to my app.</p>
<ol>
<li><p>Push notification - so when a new article is released on app it will alert the users.</p></li>
<li><p>Local Notifications - On set intervals (date and time) I can prompt the user of the latest articles on my app. </p></li>
</ol>
<p>I had done a lot of searching but unable to find a working example that I can import straight into a project and then modify. </p>
<p>I have tried the following plugin in but was unable to get it working
<a href="https://github.com/katzer/cordova-plugin-local-notifications/" rel="nofollow">https://github.com/katzer/cordova-plugin-local-notifications/</a></p>
| <p>Steps for enabling push notifications in project.</p>
<ol>
<li><p>create a project in <a href="https://console.developers.google.com/" rel="nofollow">https://console.developers.google.com/</a> with your project name.</p></li>
<li><p>Refer the below link for push plugin installation
<a href="https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/INSTALLATION.md" rel="nofollow">https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/INSTALLATION.md</a></p></li>
<li><p>Code in your push.js file
Refer <a href="https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md" rel="nofollow">https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md</a></p>
<p>//code: push notification initialization and registration. </p>
<pre><code>if (!$window.PushNotification) {
return;
}
var push = $window.PushNotification.init({
android: {
senderID: "Include your app sender ID XXXXXXXâ
},
ios: {
alert: "true",
badge: true,
sound: 'false'
},
windows: {}
});
push.on('registration', function(data) {
// this gives the unique deviceId, Or you can maintain array of deviceIds to register multiple devices.
// if have specified single deviceId for example
// save this deviceId in database for further operations, i.e. push messages to those ids.
console.log(data.registrationId);
});
push.on('notification', function(data) {
console.log(data.message);
});
push.on('error', function(e) {
console.log(e.message);
});
push.off('notification', function(e) {
console.log('off notify');
});
</code></pre></li>
<li><p>There are several ways to send push notification. Here I'm taking help of gcm-server to notify.
You will need to install node-gcm.
Create a new server.js file.</p>
<pre><code> var gcm = require('node-gcm');
var message = new gcm.Message();
//API Server Key
var sender = new gcm.Sender('GIVE_YOUR_SERVER_API_KEY');
var registrationIds = [];
// Value the payload data to send...
message.addData('message',"\u270C Peace, Love \u2764 and PhoneGap \u2706!");
message.addData('title','Push Notification Sample' );
message.addData('msgcnt','3'); // Shows up in the notification in the status bar
message.addData('soundname','beep.wav'); //Sound to play
message.timeToLive = 3000;
</code></pre>
<p>// At least one reg id required
// Here use the registration Ids that you got during device registration.</p>
<p>registrationIds.push('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');</p>
<p>sender.send(message, registrationIds, 4, function (result) {
console.log(result);
});</p></li>
</ol>
<p>Refer <a href="http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/" rel="nofollow">http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/</a> for clear understanding of sending notification via gcm-server. This will show the notification on the device.</p>
<p>You can also make use of firebase instead of gcm.</p>
<p>Steps for enabling local notification:
Add plugin to your project using <code>cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications</code></p>
<p>Invoke the local notification as shown in the link <a href="https://github.com/katzer/cordova-plugin-local-notifications/" rel="nofollow">https://github.com/katzer/cordova-plugin-local-notifications/</a></p>
|
Relative layout overlapping Linear layout <p>I have the following snippet of code:</p>
<pre><code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:fillViewport="true"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/activity_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="nishs.com.simpleblog.PostActivity">
<ImageButton
android:id="@+id/imageSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:contentDescription="@string/add_image_description"
android:cropToPadding="false"
android:scaleType="centerCrop"
android:src="@drawable/click_here_to_add_image" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/imageSelect"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<EditText
android:id="@+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/input_outline"
android:hint="@string/post_title"
android:inputType="textCapWords"
android:maxLines="1"
android:padding="@dimen/input_padding"
android:textColorHint="@color/grey" />
<EditText
android:id="@+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@drawable/input_outline"
android:hint="@string/post_description"
android:inputType="textMultiLine|textCapSentences"
android:padding="@dimen/input_padding"
android:textColorHint="@color/grey" />
</LinearLayout>
<Button
android:id="@+id/submitBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
android:text="@string/post_button"
android:textColor="@color/white"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
</code></pre>
<p>The description EditText is overlapped by the submit button as shown in the image linked. Is there any way I can make LinearLayout appear above the RelativLayout's Submit Post button ?</p>
<p><a href="http://i.stack.imgur.com/Mk9Yl.png" rel="nofollow">Link to the image</a></p>
| <p>There are 2 things you can try and see what fits better for your needs.</p>
<p>You can align button below the EditTexts</p>
<pre><code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:id="@+id/activity_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="nishs.com.simpleblog.PostActivity">
<ImageButton
android:id="@+id/imageSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:contentDescription="@string/add_image_description"
android:cropToPadding="false"
android:scaleType="centerCrop"
android:src="@drawable/click_here_to_add_image" />
<LinearLayout
android:id="@+id/edit_text_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/imageSelect"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<EditText
android:id="@+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/input_outline"
android:hint="@string/post_title"
android:inputType="textCapWords"
android:maxLines="1"
android:padding="@dimen/input_padding"
android:textColorHint="@color/grey" />
<EditText
android:id="@+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@drawable/input_outline"
android:hint="@string/post_description"
android:inputType="textMultiLine|textCapSentences"
android:padding="@dimen/input_padding"
android:textColorHint="@color/grey" />
</LinearLayout>
<LinearLayout
android:id="@+id/button_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="@id/edit_text_container"
android:adjustViewBounds="true"
android:gravity="bottom">
<Button
android:id="@+id/submitBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:text="@string/post_button"
android:textColor="@android:color/white"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
</code></pre>
<p></p>
<p>Or you can put button outside the ScrollView:</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<RelativeLayout
android:id="@+id/activity_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="nishs.com.simpleblog.PostActivity">
<ImageButton
android:id="@+id/imageSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:contentDescription="@string/add_image_description"
android:cropToPadding="false"
android:scaleType="centerCrop"
android:src="@drawable/click_here_to_add_image" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/imageSelect"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<EditText
android:id="@+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/input_outline"
android:hint="@string/post_title"
android:inputType="textCapWords"
android:maxLines="1"
android:padding="@dimen/input_padding"
android:textColorHint="@color/grey" />
<EditText
android:id="@+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@drawable/input_outline"
android:hint="@string/post_description"
android:inputType="textMultiLine|textCapSentences"
android:padding="@dimen/input_padding"
android:textColorHint="@color/grey" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
<Button
android:id="@+id/submitBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
android:text="@string/post_button"
android:textColor="@color/white"
android:textStyle="bold" />
</code></pre>
<p></p>
|
Why my font color will chang when div transition? <p>Here is also on jsfiddle
<a href="https://jsfiddle.net/phmttrsh/" rel="nofollow">https://jsfiddle.net/phmttrsh/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#btn {
font-size: 16px;
height: 34px;
width: 120px;
border: 1px solid #20ACB3;
text-align: center;
line-height: 34px;
background-color: #20ACB3;
color: #ffffff;
border-radius: 5px;
transition: transform 200ms cubic-bezier(0.25, 0.39, 0.39, 2.01);
}
#btn:hover {
cursor: pointer;
transform: scale(1.05);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="btn">Click</div></code></pre>
</div>
</div>
</p>
<p>When on hover on button the font color will also change very short time and it only happened on safari.</p>
<p>Why this happened?</p>
| <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#btn {
font-size: 16px;
height: 34px;
width: 120px;
border: 1px solid #20ACB3;
text-align: center;
line-height: 34px;
background-color: #20ACB3;
color: #ffffff;
border-radius: 5px;
-webkit-transition : transform 200ms cubic-bezier(0.25, 0.39, 0.39, 2.01) , color 200ms;
-moz-transition : transform 200ms cubic-bezier(0.25, 0.39, 0.39, 2.01) , color 200ms;
-o-transition : transform 200ms cubic-bezier(0.25, 0.39, 0.39, 2.01) , color 200ms;
transition : transform 200ms cubic-bezier(0.25, 0.39, 0.39, 2.01) , color 200ms;
}
#btn:hover {
cursor: pointer;
transform: scale(1.05);
color:#fff
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="btn">Click</div></code></pre>
</div>
</div>
</p>
|
Looking for JsonParser dependency <p>I have worked out that JsonParser is in javax.json.stream but i have no idea where i can get a hold of it. Can anyone help me?</p>
<p><a href="https://docs.oracle.com/javaee/7/api/javax/json/stream/package-summary.html" rel="nofollow">https://docs.oracle.com/javaee/7/api/javax/json/stream/package-summary.html</a></p>
<p>That's the library i am looking for.</p>
<p>I have tried looking at the maven repositories and found something similar called <code>javax.json-api</code> but it does not contain JsonParser. </p>
| <p>If you are using maven, you can add the following dependency</p>
<pre><code><dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
</code></pre>
<p>you can also download the artefact manually here </p>
<p><a href="http://central.maven.org/maven2/javax/javaee-api/7.0/javaee-api-7.0.jar" rel="nofollow">http://central.maven.org/maven2/javax/javaee-api/7.0/javaee-api-7.0.jar</a></p>
<p>For Gradle, use</p>
<pre><code>compile group: 'javax', name: 'javaee-api', version: '7.0'
</code></pre>
<p>The site <a href="https://mvnrepository.com" rel="nofollow">https://mvnrepository.com</a> shows you the different dependencies for different build systems. </p>
<p>Please note that this is only one possible dependency. You can certainly find smaller dependencies, which only contain the classes you want. Simply search for it on google or mavencentral.</p>
|
Splitting a wav file in Matlab <p>I previously asked a question, which is related to my actual problem. I converted a mp3 file to a wav file, by using the program audacity. Th duration of the wav-file is about 10 seconds. I want to split it in 10 parts, which means, each part takes 1 second. How can i make it happen? Please apologize my ignorance, even though the community provided me some answer. </p>
<pre><code>[y,fs]=wavread('UnchainMyHeart');
t=linspace(0,length(y)/fs,length(y));
plot(t,y)
</code></pre>
<p>The code here, shows my wav file in the time domain, but you probably can't see it, since you don't have the wav file. Doesn't matter. Now, is it possibly to continue from there, concering my question? I believe it has somthing to do with matrix...
Unfortunatley I lack the knowledge, therefore I always appreciate your help!</p>
| <p>It depends on what you want to do next. The easiest way to get part of signal is:</p>
<pre><code>part=y(1:Fs);
</code></pre>
<p>you probaly want array of this things so use FOR, or WHILE sructure, smth like this:</p>
<pre><code>%in loop
part(i)=(i*Fs:i*Fs+Fs);
i=i+1;
</code></pre>
<p>be aware of array length</p>
|
How to save Foreign Key text input in Django model form <p>My view passes an id to my form. This id is a foreign key from another table. I am not able to save the id in the database table.
(id : voucher_id, table in which i am saving the form : TmpPlInvoicedet)</p>
<p><strong>What i want to do</strong></p>
<p><strong>Send voucher_id from (View) to ---> TmpFormDetForm (Form) ---> TmpPlInvoicedet (DB)</strong></p>
<p>Trying to get instance from the table 'TmpPlInvoice' (which has voucher_id as PK) and save it in the form gives me </p>
<p><strong>DoesNotExist at /new/ TmpPlInvoice matching query does not exist</strong></p>
<p>What am i doing wrong?</p>
<p><strong>Views.py</strong></p>
<pre><code>def new_invoic(request):
# Create a voucher id according to my criteria
temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct()
if not temp_vid:
voucher_id = str(1).zfill(4)
else:
voucher_id = str(int(max(temp_vid)) + 1).zfill(4)
# POST METHOD TRying to show the voucher_id in the form in readonly format
if request.method == 'POST':
form_pk = TmpForm(request.POST or None, voucher_id=voucher_id,initial={'voucher_id': voucher_id})
if form.is_valid():
form_pk.save()
form = TmpFormDetForm(request.POST or None, voucher=voucher_id, initial={'voucher': voucher_id})
# My assumption is that since i have save the voucher_id in the TmpInvoice table so i can get the PK voucher_id value and save it in the TmpInvoiceDetForm
form.save()
return HttpResponseRedirect('/new/')
else:
return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request))
else:
form_pk = TmpForm(voucher_id=voucher_id,initial={'voucher_id': voucher_id})
form = TmpFormDetForm(voucher=voucher_id, initial={'voucher': voucher_id})
return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request))
</code></pre>
<p><strong>Forms.py</strong></p>
<pre><code># This form contains the FK. This one is giving errors while saving.
class TmpFormDetForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
voucher = kwargs.pop('voucher', None)
super(TmpFormDetForm, self).__init__(*args, **kwargs)
self.fields['voucher'].initial = TmpPlInvoice.objects.get(voucher_id=voucher)
voucher = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
class Meta:
model = TmpPlInvoicedet
exclude = ['emp_id','particulars','qty', 'rate' , 'itemtot', 'stock_code' ]
widgets = {
'voucher': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required': 'False', 'name': 'voucher','readonly': 'readonly'}),
'lineitem': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Total', 'required': 'False', 'blank': 'True'})}
# This form takes the PK. I save the PK here first.
class TmpForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
voucher_id = kwargs.pop('voucher_id', None)
super(TmpFor, self).__init__(*args, **kwargs)
self.fields['voucher_id'].initial = voucher_id
pos_code = MyModelChoiceField(queryset=Positions.objects.all(), widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'}))
cust = MyModelChoiceField(queryset=Custodian.objects.all(), to_field_name='acct_id',widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'}))
acct = MyModelChoiceField(queryset=Item.objects.all(), to_field_name='stock_code',widget=forms.Select(attrs={'class':'select2_single form-control', 'blank': 'True'}))
voucher_date = forms.DateField(widget=forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}))
class Meta:
model = TmpPlInvoice
exclude = ['net_amt', 'post_date', 'address', 'posted']
widgets = {
'voucher_id': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required':'False', 'name': 'voucher_id', 'readonly': 'readonly'}),
'voucher_date': forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}),
'particulars': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Particulars', 'required':'False'}),
}
</code></pre>
<p><strong>Models.py</strong></p>
<pre><code>class TmpPlInvoicedet(models.Model):
stock_code = models.CharField(max_length=13, blank=True, null=True)
voucher = models.ForeignKey(TmpPlInvoice, db_column='voucher_id')
lineitem = models.CharField(max_length=6)
particulars = models.CharField(max_length=200, blank=True, null=True)
qty = models.FloatField(blank=True, null=True)
rate = models.FloatField(blank=True, null=True)
itemtot = models.FloatField(blank=True, null=True)
emp_id = models.CharField(max_length=8, blank=True, null=True)
class Meta:
managed = False
db_table = 'tmp_pl_invoicedet'
unique_together = (('voucher', 'lineitem'),)
</code></pre>
| <p>You seem to be creating a new invoice ID and then, in your form, attempting to get the invoice matching that ID. But that invoice doesn't exist yet, of course, because you haven't created it.</p>
<p>You might want to use <code>get_or_create</code> to ensure that the invoice is created if it doesn't exist.</p>
|
How to register REST client in WSO2 API Manager <p>I've been looking through the doc of wso2 apim.
<a href="https://docs.wso2.com/display/AM1100/apidocs/store/index.html#guide" rel="nofollow">https://docs.wso2.com/display/AM1100/apidocs/store/index.html#guide</a></p>
<p>And found the curl request:</p>
<pre><code>curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Content-Type: application/json" -d @payload.json http://localhost:9763/client-registration/v0.9/register
</code></pre>
<p>With payload:</p>
<pre><code>{
"callbackUrl": "www.google.lk",
"clientName": "rest_api_store",
"tokenScope": "Production",
"owner": "admin",
"grantType": "password refresh_token",
"saasApp": true
}
</code></pre>
<p>But I got and 403 error response.
As expected I should get the correct response payload like:</p>
<pre><code>{
"callBackURL": "www.google.lk",
"jsonString":
"{
\"username\":\"admin\",
\"redirect_uris\":\"www.google.lk\",
\"tokenScope\":[Ljava.lang.String;@3a73796a,
\"client_name\":\"admin_rest_api_store\",
\"grant_types\":\"authorization_code password refresh_token iwa:ntlm
urn:ietf:params:oauth:grant-type:saml2-bearer client_credentialsimplicit\"
}",
"clientName": null,
"clientId": "HfEl1jJPdg5tbtrxhAwybN05QGoa",
"clientSecret": "l6c0aoLcWR3fwezHhc7XoGOht5Aa"
}
</code></pre>
<p>I have not idea what's going on, I just followed the doc above and without any changes.
Will be appreciated if anyone can help.
Thanks.</p>
| <p>Looks like your DCR call is being blocked by some security filter. May be because you're reaching a wrong endpoint. </p>
<p>I believe you're using APIM 2.0.0. If yes, your DCR url should be this. (note version <code>v0.10</code>)</p>
<pre><code>http://localhost:9763/client-registration/v0.10/register
</code></pre>
<p>Try and see if this solves your issue.</p>
<p>Update: Looks like this URL is wrong on <a href="https://docs.wso2.com/display/AM200/apidocs/store/#guide" rel="nofollow">2.0.0 docs</a>. I'll reach WSO2 Docs team to fix it.</p>
|
Laravel 5.3 How does bootstrap interpret and display items without internet <p>I'm still learning Laravel 5.3 and started studying it a few days ago. One tutorial project I'm following made use of <code>Fontawesome</code> and <code>Bootstrap</code> where bootstrap link and <code>fontawesome</code> link was included within the <code><head></head></code> tag. </p>
<p>So I thought that if I disconnect the internet connection, it will fail to display the icons from <code>fontawesome</code> since no library file was downloaded and imported to project. But I was surprised that it still was able to display the <code>fontawesome</code> icons.</p>
<p>That's when I of thought of asking this simple question since I'm a beginner with <code>Laravel</code> and web programming. (<code>Java</code> programmer)</p>
<pre><code><head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>@yield('title')</title>
<!-- bootstrap link -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- fontawesome link -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<!-- app.css link -->
<link rel="stylesheet" href="{{ URL::to('css/app.css') }}">
@yield('styles')
</head>
</code></pre>
<p>I read something from <code>Laravel 5.3</code> documentation about the bootstrap directory that stores <code>cached</code> information. Is the caching the reason the <code>fontawesome</code> icons still displays even when it is not connected to the internet?</p>
<blockquote>
<p>The Bootstrap Directory</p>
<p>The bootstrap directory contains files that bootstrap the framework
and configure autoloading. This directory also houses a cache
directory which contains framework generated files for performance
optimization such as the route and services cache files.</p>
</blockquote>
<p>I'd appreciate any explanation to this so I can better understand how it works.</p>
| <p>Your browser has cache too. Do <a href="http://superuser.com/questions/220179/how-can-i-do-a-cache-refresh-in-google-chrome">hard refresh / reload</a> - in Chrome you can do this by opening inspector and then right click on refresh button and click what suits you the most.</p>
<p><a href="http://i.stack.imgur.com/UdZsS.png" rel="nofollow"><img src="http://i.stack.imgur.com/UdZsS.png" alt="hard-reload"></a></p>
<blockquote>
<p>Describing what is actually going on would be too long for an answer.</p>
</blockquote>
<p>Good description what is going on is <a href="https://thesocietea.org/2016/05/how-browser-caching-works/" rel="nofollow">here</a>. </p>
<p>Google search terms: <code>browser cache</code>, <code>web browser cache</code></p>
<hr>
<p>If you use build system (gulp) you will most likely end up with large <code>*.css</code> file which contains bootstrap, font-awesome definitions etc.</p>
<p>More on that is right in <a href="https://laravel.com/docs/5.3/elixir#installation" rel="nofollow">documentation</a>.</p>
|
The JSON sent by Firebase is invalid <pre><code>{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
</code></pre>
<p>This code is returned by Firebase and I'm getting the error <code>No JSON object could be decoded</code>. I think this has to do something with the validity of the JSON format.</p>
<p>I'm getting this JSON data using the Firebase Node.JS SDK. Then I'm passing it to Python using Pyshell. When I use the <code>json.loads</code> in python, tt says:</p>
<pre><code>C:\Python27>node firebase2.js
{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
C:\Python27\firebase2.js:40
if (err) throw err;
^
Error: ValueError: No JSON object could be decoded
at PythonShell.parseError (C:\Python27\node_modules\python-shell\index.js:183:17)
at terminateIfNeeded (C:\Python27\node_modules\python-shell\index.js:98:28)
at ChildProcess.<anonymous> (C:\Python27\node_modules\python-shell\index.js:88:9)
at emitTwo (events.js:87:13)
at ChildProcess.emit (events.js:172:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
----- Python Traceback -----
File "my_script.py", line 3, in <module>
myjson = json.loads(myinput)
File "C:\Python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
</code></pre>
| <p>This is not a valid JSON and I think that your <code>firebase2.js</code> is at fault here.</p>
<p>Instead of this:</p>
<pre><code>{ name: 'anonymous', text: 'Hello' }
{ name: 'anonymous', text: 'How are you' }
{ name: 'anonymous', text: 'I am fine' }
</code></pre>
<p>It should output this:</p>
<pre><code>[
{ "name": "anonymous", "text": "Hello" },
{ "name": "anonymous", "text": "How are you" },
{ "name": "anonymous", "text": "I am fine" }
]
</code></pre>
<p>All strings (including object keys) have to be quoted with double quotes. Arrays have to be included in square brackets and array elements need to be delimited with commas.</p>
<p>Check out your <code>firebase2.js</code> program and see how it generates its output. If it uses anything else than a single:</p>
<pre><code>console.log(JSON.stringify(SOME_VARIABLE));
</code></pre>
<p>Then here's your problem.</p>
<p>In any case, I am more than sure that Firebase is not returning
<code>{a:'b'}{c:'d'}</code> instead of <code>[{"a":"b"},{"c":"d"}]</code> - this is a typical error of beginners who don't know the JSON format, something hard to believe in the case of one of the biggest API providers in the world.</p>
<p>If you want to know what is the real response then use <code>curl</code>:</p>
<pre><code>curl -v https://example.com/some/endpoint -H 'auth header' ...
</code></pre>
<p>and if you see invalid JSON there, then it's time to contact Firebase support.</p>
<p>The JSON format is explained on <a href="http://json.org/" rel="nofollow">http://json.org/</a> - this is the simplest data format in existence.</p>
|
Save base64 JPG to disk in R - Shiny <p>I have the following data frame which can be downloaded from <a href="https://drive.google.com/open?id=0B-PuDZ6SYpScMW5CdXhvLVpJQkk" rel="nofollow">here</a>. The column <code>image_path</code> has jpg files in base64 format. I want to extract the image and store it in a local folder. I tried using the code given <a href="http://stackoverflow.com/questions/36708191/convert-base64-to-png-jpeg-file-in-r">here</a> and <a href="http://stackoverflow.com/questions/39761336/how-to-display-images-retrieved-from-mysql-in-r-shiny/39763698#39763698">here</a>.</p>
<p>While the second one perfectly opens the image in the browser, I couldn't figure out how to save the file locally. I tried the following code:</p>
<pre><code>library(shiny)
for (i in 1:length(df)){
file <- paste(df$id[i])
png(paste0(~images/file, '.png'))
tags$img(src = df$image_path[i])
dev.off()
}
</code></pre>
<p>The following just runs but doesn't create any image files and no errors are shown. When I tried running <code>tags$img(src = df$image_path[1])</code> to see if it generates the image, it doesn't. I understand tags$img is a function within shiny and works when I pass it inside ui (as suggested by @daatali), but not sure how do I save the files locally.</p>
<p>What I want is to run a for loop from inside a server environment of shiny and save the images locally as jpg using id numbers as filename, which can be rendered with various other details captured in the survey.</p>
<p>I have never worked with images and please bear with me if this is completely novice.</p>
| <p>This creates your images from the base64 strings and saves the files <strong>to your current working directory, subfolder "/images/"</strong>. <a href="http://shiny.rstudio.com/articles/persistent-data-storage.html#local" rel="nofollow">This article describes pretty well how to save files locally in Shiny.</a></p>
<pre><code>library(shiny)
library(base64enc)
filepath <- "images/"
dir.create(file.path(filepath), showWarnings = FALSE)
df <- read.csv("imagefiletest.csv", header=T, stringsAsFactors = F)
for (i in 1:nrow(df)){
if(df[i,"image_path"] == "NULL"){
next
}
testObj <- strsplit(df[i,"image_path"],",")[[1]][2]
inconn <- testObj
outconn <- file(paste0(filepath,"image_id",df[i,"id"],".png"),"wb")
base64decode(what=inconn, output=outconn)
close(outconn)
}
</code></pre>
<p><a href="http://i.stack.imgur.com/c37RE.png" rel="nofollow"><img src="http://i.stack.imgur.com/c37RE.png" alt="enter image description here"></a></p>
|
Android Import java.util.StringJoiner error <p>I tried to import <code>java.util.StringJoiner</code> but I received this message </p>
<p><code>Usage of API documented as @since 1.8+ less... (âF1)
This inspection finds all usages of methods that have @since tag in their documentation. This may be useful when development is performed under newer SDK version as the target platform for production.</code></p>
<p>i'm using :</p>
<p>java version "1.8.0_102"</p>
<p>Java(TM) SE Runtime Environment (build 1.8.0_102-b14)</p>
<p>Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)</p>
<p>How to solve this problem. Thank you all for helping me!!</p>
| <p><code>StringJoiner</code> was added in API Level 24. If your <code>minSdkVersion</code> is 24 or higher (i.e., will only run on Android 7.0+), you are welcome to use it. If your <code>minSdkVersion</code> is lower than 24, either replace your use of <code>StringJoiner</code> entirely or only use it on devices running API Level 24 or higher.</p>
<p>The specific message that you are getting is because not only was this class introduced in API Level 24, but it came from Java 8. Older devices do not support Java 8 classes.</p>
<p>Also, Java 8 functionality requires the Jack compiler, which at the present time is not the default compiler. You will need to follow <a href="https://developer.android.com/guide/platform/j8-jack.html#configure-gradle" rel="nofollow">the instructions to enable Java 8 support in Gradle</a>, adding the <code>jackOptions</code> and <code>compileOptions</code> closures:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
defaultConfig {
applicationId "com.commonsware.myapplication"
minSdkVersion 24
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
jackOptions {
enabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
</code></pre>
|
Update a field 'version' into a table <p>I have this situation:</p>
<p>I have two tables:</p>
<ul>
<li>Table A </li>
<li>Staging_Table A </li>
</ul>
<p>Both tables contain those common columns:</p>
<ul>
<li>Code</li>
<li>Description</li>
</ul>
<p>Into Table A I also have a column <code>Version</code> which identifies the last version of corresponding column <code>Code</code>.</p>
<p>My problem is how to update the column <code>Version</code> once a new <code>Description</code> is stored for the same <code>Code</code> (I fill up the <code>Staging_Table</code> with a bulk Insert from C#. I have a flow of data that change once a week). </p>
<p>I need to insert the new row into Table A which contain the same <code>Code</code>, but a different <code>Description</code>, without deleting the old one.</p>
<p>I insert the rows from Staging table to table A with MINUS operation and I have this mechanism within a stored procedure because I also fill up the staging table with a Bulk Insert from C#.</p>
<p>The result I need to obtain is the following:</p>
<p>TABLE A: </p>
<pre><code>Id Code Description Version End_date
-- ----------------- ------- --------
1 8585 Red Car 1 26-mag-2015
2 8585 Red Car RRRR 2 01-giu-2015
</code></pre>
<p>How can I do that?</p>
<p>I hope the issue is clear</p>
| <p>If I understand correctly process work like that:
1. Data is loaded to staging table Staging_table_A
2. Data is inserted from Staging_table_A itno Table_A with additional column version.</p>
<p>I would do:</p>
<pre><code>with cnt as (select count(*) c, code from Table_A group by code)
Insert into Table_A (select sta.*, nvl(cnt.c,0) + 1 as version
from Staging_table_A sta left outer join cnt on (sta.code = cnt.code));
</code></pre>
<p>This is based on condition that in Table_A versions contains no duplicates.</p>
|
can't return roles in AspNetRoles <p>i need to return all role in identity tabel for create a dropdown list . </p>
<pre><code> public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(RoleStore<IdentityRole> store)
: base(store)
{
}
public static ApplicationRoleManager Create(IOwinContext context)
{
var Store = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
// Configure validation logic for usernames
return new ApplicationRoleManager(Store);
}
}
</code></pre>
<p>how should i do this ? </p>
<p><strong>Edit</strong></p>
<p><a href="http://i.stack.imgur.com/SGW6J.png" rel="nofollow"><img src="http://i.stack.imgur.com/SGW6J.png" alt="enter image description here"></a></p>
<p>/*******************************************************************************************************/</p>
| <p>The process to get all roles via setting up <code>ApplicationRoleManager</code> is the following (as per Identity samples provided by Microsoft found <a href="https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples" rel="nofollow">here</a>).</p>
<p>Add the code below to your IdentityConfig.cs</p>
<pre><code>public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
</code></pre>
<p>Then initialize the single instance per Owin context of your RoleManager in Startup.Auth.cs:</p>
<pre><code>app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
</code></pre>
<p>In your controller where you want to get all roles, do the following:</p>
<pre><code>private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
</code></pre>
<p>After that you can simply use <code>RoleManager.Roles</code> in any of your action methods to get all roles.</p>
<p>This answer contains all the steps you need to get this to work but refer to the link to the nuget package above if you're still unclear on the process.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.