Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2017-11-22T13:16:57Z
Updated: 9 hours 3 min ago

SQL get field from row with max / min field

Mon, 11/20/2017 - 02:08

So there is school project and I completely stuck on last step. There's my code:

SELECT Consumidor.numero, Soma.soma FROM Consumidor JOIN (SELECT compra.consumidor, SUM(Eco.eco*compra.quantidade) as soma FROM compra JOIN (SELECT composto.produto, composto.prodMarca, Produto.nome, sum(Elemento.pegadaEcologica * composto.percentagem/100) AS eco FROM composto JOIN Produto ON composto.produto = Produto.codigo AND composto.prodMarca = Produto.marca JOIN Elemento ON composto.elemento = Elemento.codigo GROUP BY composto.produto, composto.prodMarca) Eco ON compra.produto = Eco.produto AND compra.prodMarca = Eco.prodMarca GROUP BY compra.consumidor) Soma ON Consumidor.numero = Soma.Consumidor

So now I have table like:

Consumidor.number Soma.soma 123 90 456 70 789 70

Expected result should be Consumidor.number (-s) where Soma.soma is min.

I.e. for this table result should be:

Consumidor.number 456 789

There's original schema for all tables used in this query:

Consumidor (PK numero, email, sexo, nascimento) Elemento (PK codigo, nome, pegadaEcologica, saude) Produto (PK codigo, FK PK Marca.numero marca, nome, tipo, comercioJusto) compra (FK PK Produto.codigo produto, FK PK Produto.marca prodMarca, Consumidor.numero, quantidade) composto (FK PK Produto.codigo produto, FK PK Produto.marca prodMarca, FK PK Elemento.codigo elemento, percentagem)

Update. I didnt stuck with solution - there is solution:

SELECT Consumidor.numero, Soma.soma FROM Consumidor JOIN (SELECT compra.consumidor, SUM(Eco.eco*compra.quantidade) as soma FROM compra JOIN (SELECT composto.produto, composto.prodMarca, Produto.nome, sum(Elemento.pegadaEcologica * composto.percentagem/100) AS eco FROM composto JOIN Produto ON composto.produto = Produto.codigo AND composto.prodMarca = Produto.marca JOIN Elemento ON composto.elemento = Elemento.codigo GROUP BY composto.produto, composto.prodMarca) Eco ON compra.produto = Eco.produto AND compra.prodMarca = Eco.prodMarca GROUP BY compra.consumidor) Soma ON Consumidor.numero = Soma.Consumidor WHERE Soma.soma <= ALL (SELECT SUM(Eco.eco*compra.quantidade) as soma FROM compra JOIN (SELECT composto.produto, composto.prodMarca, Produto.nome, sum(Elemento.pegadaEcologica * composto.percentagem/100) AS eco FROM composto JOIN Produto ON composto.produto = Produto.codigo AND composto.prodMarca = Produto.marca JOIN Elemento ON composto.elemento = Elemento.codigo GROUP BY composto.produto, composto.prodMarca) Eco ON compra.produto = Eco.produto AND compra.prodMarca = Eco.prodMarca GROUP BY compra.consumidor)

Simply put whole Soma query onto WHERE clause. With this im getting expected resault. But this looks so ugly and im looking for some more elegant way.

P.S. Don't throw tomatoes - following project statement I'm not able to use sub-queries in FROM clause, but if there are some observations about whole my code I will appreciate.

Python Requests - HTML Form - Detect fields for automated form submission - VicRoads

Mon, 11/20/2017 - 01:47

How to detect required fields for automated form submission on VicRoads Vehicle Registration Check Website?

I am assuming there is some session hidden field in this form. Is there any generalised way to detect all required fields using some existing firefox or chrome developer addons? Any external tool recommendation is fine too.

Once I know which fields to submit, it would be a simple exercise using python-requests module for form POSTing

https://www.vicroads.vic.gov.au/registration/buy-sell-or-transfer-a-vehicle/buy-a-vehicle/check-vehicle-registration/vehicle-registration-enquiry

E.g. I need to check status of car with registration number 'ABC123'

This is required for proof of concept only. Not desired for commercial exploitation of the service

Is there any hope to call a base class method on a variant efficiently?

Mon, 11/20/2017 - 00:29

The way std::variant dispatches to different visitor methods when std::visit is called is pretty reasonable when the variant alternatives are completely different types. Essentially a visitor-specific vtable is built at compile-time and after some error checking1 the appropriate visitor function is looked by indexing the table based the current index() which resolves to something like an indirect jump on most platforms.

If the alternatives share a common base class, however, calling a (non-virtual) member function or accessing state on the base class with a visitor is conceptually much simpler: you are always calling the same method and usually using the same pointer2 to the base class.

Still, the implementation ends up just as slow. For example:

#include <variant> struct Base { int m_base; int getBaseMember() { return m_base; } }; struct Foo : public Base { int m_foo; }; struct Bar : public Base { int m_bar; }; using Foobar = std::variant<Foo,Bar>; int getBaseMemVariant(Foobar& v) { return std::visit([](auto&& e){ return e.getBaseMember(); }, v); }

The generated code on x86 for the most recent version of gcc and clang is similar3 (clang shown):

getBaseMemVariant(std::__1::variant<Foo, Bar>&): # @getBaseMemVariant(std::__1::variant<Foo, Bar>&) sub rsp, 24 mov rax, rdi mov ecx, dword ptr [rax + 8] mov edx, 4294967295 cmp rcx, rdx je .LBB0_2 lea rdx, [rsp + 8] mov qword ptr [rsp + 16], rdx lea rdi, [rsp + 16] mov rsi, rax call qword ptr [8*rcx + decltype(auto) std::__1::__variant_detail::__visitation::__base::__visit_alt<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>, std::__1::__variant_detail::__impl<Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__impl<Foo, Bar>&)::__fmatrix] add rsp, 24 ret .LBB0_2: mov edi, 8 call __cxa_allocate_exception mov qword ptr [rax], vtable for std::bad_variant_access+16 mov esi, typeinfo for std::bad_variant_access mov edx, std::exception::~exception() mov rdi, rax call __cxa_throw decltype(auto) std::__1::__variant_detail::__visitation::__base::__dispatcher<0ul>::__dispatch<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&): # @"decltype(auto) std::__1::__variant_detail::__visitation::__base::__dispatcher<0ul>::__dispatch<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&)" mov eax, dword ptr [rsi] ret decltype(auto) std::__1::__variant_detail::__visitation::__base::__dispatcher<1ul>::__dispatch<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&): # @"decltype(auto) std::__1::__variant_detail::__visitation::__base::__dispatcher<1ul>::__dispatch<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&)" mov eax, dword ptr [rsi] ret decltype(auto) std::__1::__variant_detail::__visitation::__base::__visit_alt<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>, std::__1::__variant_detail::__impl<Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__impl<Foo, Bar>&)::__fmatrix: .quad decltype(auto) std::__1::__variant_detail::__visitation::__base::__dispatcher<0ul>::__dispatch<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&) .quad decltype(auto) std::__1::__variant_detail::__visitation::__base::__dispatcher<1ul>::__dispatch<std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&>(std::__1::__variant_detail::__visitation::__variant::__value_visitor<getBaseMemVariant(std::__1::variant<Foo, Bar>&)::$_0>&&, std::__1::__variant_detail::__base<(std::__1::__variant_detail::_Trait)0, Foo, Bar>&)

The call qword ptr [8*rcx + ... is the actual indirect call to a function pointed to by the vtable (the vtable itself appears at the bottom of the listing). The code before that is first checking the "is empty" state, and then setting up the visit call (I'm not sure what the weirdness with rdi is, I guess it's setting up a pointer to the visitor as the first argument or something).

The actual methods which are pointer to by the vtable and executed by the call are very simple, a single mov to read the member. Critically, both are indentical:

mov eax, dword ptr [rsi] ret

So we have a huge mess. To execute that single mov we have a dozen setup instructions, and more importantly an indirect branch: which if targeting a series of Foobar variant objects with different contained alternatives will mispredict very badly. Finally, the indirect call seems like an insurmountable barrier to further optimization: here will look at a simple call without any surrounding context, but in real use this might be optimized into a larger function with significant opportunities for further optimization - but I think the indirect call will block it.

You can play with the code yourself on godbolt.

Versus a Union

The slowness isn't inherent: here's a very simple "discriminated union" struct that combines the two classes in a union along with an isFoo discriminator that keeps track of what class is contained:

struct FoobarUnion { bool isFoo; union { Foo foo; Bar bar; }; Base *asBase() {return isFoo ? (Base *)&foo : &bar; }; }; int getBaseMemUnion(FoobarUnion& v) { return v.asBase()->getBaseMember(); }

The corresponding getBaseMemUnion function compiles down to a single mov instruction on both gcc and clang:

getBaseMemUnion(FoobarUnion&): # @getBaseMemUnion(FoobarUnion&) mov eax, dword ptr [rdi + 4] ret

Granted, the discriminated union doesn't have to check the "is valueless" error condition, but that's not the main reason for variant slowness and in any case such a condition is impossible with Foo and Bar since none of their constructors throw. Even if you wanted to support such a state, the resulting function with the union is still very efficient - only a small check is added, but the behavior of calling the base class is the same.

Is there anything I can do to make variant efficient here, or is the promise of a zero-cost abstraction just not panning out here? I'm open to a different call pattern, compiler options, whatever.

1 In particular, checking whether the variant is valueless_by_exception due to an earlier assignment that failed.

2 The pointer to the base class doesn't always have the same relationship to the most derived pointer for all alternatives, e.g., when multiple inheritance is involved.

3 Well gcc is a bit worse since it seems to redundantly perform the "is valueless" check both upfront prior to the call to visit and also in each auto-generated method pointed to by the vtable. clang only does it upfront.

SQL syntax , language throwing an error when I try to run in C#

Mon, 11/20/2017 - 00:29

Good afternoon, I have some SQL code I'm executing in a C# console application, it's throwing me a "system.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'TB'.' error. I've tried to change the code multiple times to get it to work properly, but it keeps throwing the same error. Through trying to fix it I've figured out that the last "TB" on the second to last row is responsible for the error, where it says ") TB". Does anyone have an idea why it doesn't like that TB there? Here is the code:

string SQLCode = "SELECT TB.RowType,TB.company,TB.Account,TB.segvalue1,TB.segvalue2,TB.segvalue3,TB.segvalue4,TB.fiscalyear,TB.fiscalperiod,SUM(TB.BalanceAmt) as tbBalanceAmt" + "FROM(SELECT 'Actual' AS RowType,GLJ.company,GLJ.glaccount AS Account,GLJ.segvalue1,GLJ.segvalue2,GLJ.segvalue3,GLJ.SegValue4," + "GLJ.fiscalyear,GLJ.fiscalperiod,GLJ.jedate,GLJ.description,GLJ.vendornum,GLJ.apinvoicenum,SUM(GLJ.debitamount - GLJ.creditamount) as glBalanceAmt,"+ "GLJ.groupid,GLJ.posteddate FROM GLJrnDtl GLJ GROUP BY GLJ.company,GLJ.glaccount,GLJ.segvalue1,GLJ.segvalue2,GLJ.segvalue3,"+ "GLJ.SegValue4,GLJ.fiscalyear,GLJ.fiscalperiod,GLJ.jedate,GLJ.description,GLJ.vendornum,GLJ.apinvoicenum,GLJ.groupid,GLJ.posteddate"+ " UNION ALL SELECT 'Budget' AS RowType,GLB.company,GLB.BalanceAcct AS Account,GLB.segvalue1,GLB.segvalue2,GLB.segvalue3,GLB.segvalue4,GLB.fiscalyear,GLB.fiscalperiod,"+ "GLB.Date01 AS jedate,'' AS description,'' AS vendornum,'' AS apinvoicenum,SUM(GLB.BudgetAmt) as gbBalanceAmt,'' AS groupid,"+ "0 AS posteddate FROM GLBudgetDtl GLB WHERE GLB.segvalue3 <> '' AND GLB.BalanceType = 'D'"+ "GROUP BY GLB.company,GLB.BalanceAcct,GLB.segvalue1,GLB.segvalue2,GLB.segvalue3,GLB.segvalue4,GLB.fiscalyear,GLB.fiscalperiod,GLB.Date01, GLB.BudgetAmt) TB"+ " WHERE tb.Company = NVV AND TB.fiscalyear = '2017' AND tb.fiscalperiod BETWEEN 1 AND 10 and tb.segvalue1 = '4450'";

What's the purpose of using JQuery toggle() within filter()?

Mon, 11/20/2017 - 00:28

I have a search input field and a table. As you type in some words, the table shows the row that matches the words you typed. I saw an example on W3School. They use JQuery toggle() within filter(), which I don't really understand. The code like this

html

<input class='form-control' id='myInput' type='text' placeholder='Search.....'> <table> <thead> table header...... </thead> <tbody id='myTable'> here goes 4 rows </tbody> </table>

JS

$(document).ready(function(){ $('#myInput').on('keyup', function(){ var value = $(this).val().toLowerCase(); $('#myTable tr').filter(function(){ $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1); }); }); });

Anyone could explain the line of code within the filter() function? What's the purpose of that and how it works. Thanks!

spring digest authentication BadCredentialsException Expected response and received response is not the same

Mon, 11/20/2017 - 00:28

I am trying to understand digest authentication using Spring boot.

I have read and closely looked at the following already. -Spring Security Digest Auth using JavaConfig Example -Digest Auth in Spring Security with REST and Javaconfig -Digest authentication with Spring Security, BCrypt and Spring Data Rest

But still I am getting the following error.

2017-11-20 00:05:32.754 DEBUG 29632 --- [nio-8082-exec-1] o.s.s.w.a.w.DigestAuthenticationFilter : Expected response: '868be0095ed0872f2fd2423b40ceec1d' but received: '6866147185928c19e645f5d55a0fac26'; is AuthenticationDao returning clear text passwords? 2017-11-20 00:05:32.755 DEBUG 29632 --- [nio-8082-exec-1] o.s.s.w.a.w.DigestAuthenticationFilter : org.springframework.security.authentication.BadCredentialsException: Incorrect responseorg.springframework.security.authentication.BadCredentialsException: Incorrect response at org.springframework.security.web.authentication.www.DigestAuthenticationFilter.doFilter(DigestAuthenticationFilter.java:206) ~[spring-security-web-5.0.0.RC1.jar:5.0.0.RC1] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-5.0.0.RC1.jar:5.0.0.RC1] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.0.RC1.jar:5.0.0.RC1] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-5.0.0.RC1.jar:5.0.0.RC1] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-5.0.0.RC1.jar:5.0.0.RC1] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]

This is my SecurityConfig (Java Config)

@Configuration @EnableWebSecurity public class SimpleDigestSecurityConfig extends WebSecurityConfigurerAdapter{ @Bean @Override protected UserDetailsService userDetailsService() { //Properties users = new Properties(); //users.setProperty("user", "pwd" + ",USER"); // users.setProperty("admin", "admin" + ",USER,ADMIN"); //return new InMemoryUserDetailsManager(users); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build()); return manager; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()); } @Override protected void configure(HttpSecurity http) throws Exception { DigestAuthenticationEntryPoint authenticationEntryPoint = new DigestAuthenticationEntryPoint(); authenticationEntryPoint.setKey("myKey"); authenticationEntryPoint.setRealmName("example"); DigestAuthenticationFilter filter = new DigestAuthenticationFilter(); filter.setPasswordAlreadyEncoded(true); filter.setAuthenticationEntryPoint(authenticationEntryPoint); filter.setUserDetailsService(userDetailsService()); http.addFilter(filter) .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint) .and() .authorizeRequests() .anyRequest().authenticated(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

This is my spring boot application file.

@SpringBootApplication public class DigestdemoApplication { public static void main(String[] args) { SpringApplication.run(DigestdemoApplication.class, args); } }

And this is my controller class.

@RestController public class MyController { private static final Logger logger = LoggerFactory.getLogger(MyController.class); @RequestMapping(value = "/ping") Answer ping() { logger.info("Ping called from user " + SecurityContextHolder.getContext().getAuthentication().getName()); return new Answer(); } @RequestMapping(value = "/ping", produces = "text/plain") String simplePing() { return ping().value; } @JacksonXmlRootElement(localName = "answer") public static class Answer { @JacksonXmlText @JsonProperty("answer") public String value = "OK"; } }

I understand the error which basic saying expected hash and actual hash is not the same and I do not know how to make it the same.

Really appreciated for your help.

String to Character Array Issue (AP CSA FRQ)

Mon, 11/20/2017 - 00:27

I'm trying to scramble a word under the following conditions:

If the letter is A and the next letter is NOT A then swap the two letters. Otherwise, just leave them as is.

A few examples of how this code should work:

  1. "TAN" ---> "TNA"
  2. "ABRACADABRA" -----> "BARCADABARA"
  3. "EGGS" ---> "EGGS"
  4. "AA" ----> " AA
  5. "" -----> ""

EDIT After letter have been swapped, they cannot be swapped againEDIT Here is my code so far:

package FRQs; public class frq { public static void main (String[] args){ String s = scrambleWord("ABRACADABRA"); System.out.println(s); } public static String scrambleWord(String word){ char[] c = word.toCharArray(); for (int i = 0; i < c.length-1; i++){ if (c[i] == 'A' && c[i+1] != 'A'){ char temp = c[i]; c[i] = c[i+1]; c[i+1] = temp; } } String result = new String(c); return result; } }

Can anyone please tell me why ABRACADABRA is not scrambling correctly?

Thanks for your help.

Smallest value in an array

Mon, 11/20/2017 - 00:27

I have to find the smallest value in an array and print it, I have the code but I can't connect it with my runner file, its telling me "go(int[]) in RaySmallest cannot be applied to (int,int,int,int,int,int,int,int,int,int,int,int)" for all of my 12 samples.

public class RaySmallest { public static int go(int[] ray) { { int[] numbers = {}; int smallest = Integer.MAX_VALUE; for(int i =0;i<numbers.length;i++) { if(smallest > numbers[i]) { smallest = numbers[i]; } } System.out.println("Smallest number in array is : " +smallest); } return 0; } }

Thats my runner file

public class SmallestRunner { public static void main( String args[] ) { RaySmallest.go(-88,1,2,3,4,5,6,7,8,90,10,5); System.out.println(); RaySmallest.go(10,9,8,7,6,5,4,3,2,1,-99); System.out.println(); RaySmallest.go(10,20,30,40,50,-11818,40,30,20,10); System.out.println(); RaySmallest.go(65478); System.out.println(); RaySmallest.go(578,578); System.out.println(); RaySmallest.go(6,13,-98,100,-987,7); System.out.println(); RaySmallest.go(9,9,9,13,567); System.out.println(); RaySmallest.go(-222,1,5,6,9,12,29,1); System.out.println(); RaySmallest.go(9,8,7,6,5,4,3,2,0,-2,6); System.out.println(); RaySmallest.go(12,15,18,21,23,1000); System.out.println(); RaySmallest.go(250,19,17,15,13,11,10,9,6,3,2,1,0); System.out.println(); RaySmallest.go(9,10,-8,10000,-5000,-3000); } }

Error putting contents of a text file into an UITextView

Mon, 11/20/2017 - 00:27

I get an error when I put the contents of a text file into an UITextView. The error is: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value. What am I doing wrong?

AppDelegate:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { let vc = ViewController() vc.urlToOpen = url // put received URL in viewController variable vc.openFile(url: vc.urlToOpen) // use vc method to read the file content return true }

ViewController:

@IBOutlet weak var mainTextField: UITextView! var urlToOpen: URL! func openFile(url: URL) { do { // Read the file contents readString = try String(contentsOf: urlToOpen!) } catch let error as NSError { print("Failed reading) } print(readString) // prints correctly the file content self.mainTextField.text = readString // error }

Operate with large numbers in LibreOffice BASIC

Mon, 11/20/2017 - 00:27

I'm trying to operate the MOD of a number but it returns overflow data type.

This operation works:

VariableDouble = 2147483647 - (97 * (2147483647 \ 97)) MsgBox VariableDouble

This operation returns error:

VariableDouble = 2147483648 - (97 * (2147483648 \ 97)) MsgBox VariableDouble

Shouldn't be Double data type larger than Long one? Of course, variable declaration is as follows: Dim VariableDouble As Double.

It happens the same if I use the built-in operator MOD: a MOD b.

I need to do operations with 10 digits numbers. Is there a way I can do this using BASIC? What is happening?

How to create and remove svgs in a loop in D3

Mon, 11/20/2017 - 00:26

I'm new to javascript and even newer to d3, and I'm trying to create a simple animation to visualize simulated annealing. The way I'd like it to work right now is that the "hill climber," represented as a large blue dot, moves around on a path (defined by a function). Possible solutions are represented by smaller red dots. So the script should start out by generating a starting point, after which a solution will be generated. The algorithm then decides whether to move to that point or not. In either case, that first solution should disappear and a new one should be generated in the vicinity. I don't have the algorithm implemented yet. I'm trying first to create a simpler animation to get the hill climber to move around a few times. However, as my code stands, I'm using a for loop with 5 iterations and all 5 solutions seem to be generated at the same time, while the "remove" call happens afterwards. I know using loops in d3 is not common practice, so I'm wondering if a for loop will work at all or if I'd need to generate all possible solutions first and then in the loop apply a class that shows or reveals the solution and removes the class at the end of that iteration. I hope that's clear. Here's the code so far:

var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 720 - margin.right - margin.left, height = 720 - margin.top - margin.bottom; var xmin = -10, xmax = 10, xRange = d3.range(xmin, xmax, 0.1), hillFunction = function (i) { return ( Math.sin(i) + (3.5 * Math.sin((i * Math.PI) / 2)) + (2 * Math.cos(i/Math.PI)) ); } var data = xRange.map(function(d) { return { x: d, y: hillFunction(d) }; }); var xScale = d3.scale.linear().domain([xmin, xmax]).range([0, width]); var yScale = d3.scale.linear().domain(d3.extent(data.map(function(d){return d.y;}))).range([height, 0]); var line = d3.svg.line() .x(function(d) { return xScale(d.x); }) .y(function(d) { return yScale(d.y); }); var graph = d3.select("#graph") .append("svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); graph.append("path") .attr("d", line(data)); // simulated annealing simulation var temperature = .1, tLow = 1e-4, coolingRate = 0.999999, stepSize = 5, // corresponds to number of points or index in the domain (xRange), not actual domain values best = []; var currentX = xRange[randomInt(0, xRange.length-1)]; var current = [xScale(currentX), yScale(hillFunction(currentX))]; // generate starting point var circle = graph.append("circle") .attr("r", 10) .attr("id", "current") .attr("transform", "translate(" + current[0] + "," + current[1] + ")"); function acceptanceProbability(currentCost, neighborCost, temperature) { if (neighborCost < currentCost) { return 1 } return Math.exp((currentCost - neighborCost)/temperature); } // generate random integer between two values function randomInt(min, max) { return Math.floor(Math.random() * (max-min+1) + min); } // generate x coordinate for neighbor (full coordinates generated on draw) function computeNeighbor(currentX, stepSize) { var currentIndex = xRange.indexOf(currentX); var min = currentIndex - stepSize; var max = currentIndex + stepSize; if (currentIndex > (xRange.length-1-stepSize)) { max = currentIndex; min = currentIndex - (stepSize*2); } if (currentIndex < stepSize) { min = currentIndex; max = currentIndex + (stepSize*2); } return xRange[randomInt(min, max)]; } function simulatedAnnealing(temperature, tLow, coolingRate, stepSize) { //while (temperature > tLow) { for (var i = 0; i < 5; i++) { var neighborX = computeNeighbor(currentX, stepSize), neighbor = [xScale(neighborX), yScale(hillFunction(neighborX))]; graph.append("circle") .attr("class", "neighbor") .attr("r", 5) .transition() .attr("transform", "translate(" + neighbor[0] + "," + neighbor[1] + ")"); // because svg coordinates decrease as you go up the page, we can just use // the scaled y-coordinate as cost if (neighbor[1] < current[1]) { graph.select("#current") .transition() .delay(1000) .attr("transform", "translate(" + neighbor[0] + "," + neighbor[1] + ")"); } else { console.log("cost of neighbor is not less than current"); } setTimeout(function() { graph.select(".neighbor").remove(); }, 5000); temperature *= coolingRate; } //} } simulatedAnnealing(temperature, tLow, coolingRate, stepSize);

Unable to Remove Class for Span Element

Mon, 11/20/2017 - 00:26

I'm trying do remove class "bg-color-disable" for #filenameRPT but nothing I tried work. I have used $("#parentRPT > span#filenameRPT").removeClass("bg-color-disable"); and $("#filenameRPT").removeClass("bg-color-disable"); but no lucks. Any idea?

<div class="two-row mb-3"> <div id="parentRPT" class="input-group bg-color-disable"> <span class="input-group-addon gi data-gi-size gi-file-plus"></span> <span id="filenameRPT" class="bg-color-disable"> Upload REPORT <span class="fa fa-arrow-circle-right text-primary ml-1 mr-1"></span> <a name="rpt" href="#">No File Exists</a <input class="hidden" name="delete_RPT" value="not_deleted" type="text"/> </span> <span id="deleteRPT" class="fa fa-times text-danger hidden" title="Delete"></span> <label class="input-group-addon has-float-label" for="file-uploadRPT"> Browse <input id="file-uploadRPT" name="FileToUploadRPT" type="file" accept="application/pdf"> </label> </div> </div>

Crazy thing is I was able to remove "bg-color-disable" for #parentRPT using $("#parentRPT").removeClass("bg-color-disable"); but using $("#filenameRPT").removeClass("bg-color-disable"); didn't work for element #filenameRPT. Why?

Get variable from an extern website with python

Mon, 11/20/2017 - 00:24

I want to get the variable a from an ajax Object with Python.

The Code is:

$.ajax({ type: 'GET', url: (isMobile ? 'https://securevideotoken' : 'http://videotoken') + '.lala.com/webtv/secure?url=http://lala.net/lala/lala.m3u8&' + Math.floor(Math.random() * 1000000 + 1), success: function (data) { if (data != null) { var playerInstance = jwplayer("player"); playerInstance.setup({ playlist: [{ file: data.Url, title: "Canlı Yayın" }], width: '100%', aspectratio: '16:9', autostart: true, stretching: "uniform", primary: 'html5', androidhls: true, }); } } });

How to get the var url. I cannot change the HTML-Document.

Binding primitives to a controller works only for the constructor

Mon, 11/20/2017 - 00:08

I bound a primitive value to a class.

$this->app->when('App\Http\Controllers\TestController') ->needs('$numPages') ->give(1000);

But this value is injected only to the constructor of the class, and not to other methods.

class TestController extends Controller { public function __construct($numPages = 0) { // $numPages = 1000 WORKS } public function index($numPages = 0) { // $numPages = 0 DOESNT WORK } }

But when I bind a normal class, its instance is injected in all methods. Is it intended behavior?

Display SQL search form results in a table [duplicate]

Sun, 11/19/2017 - 23:44

This question already has an answer here:

I'm trying to pull information from a 'SQL' database via a 'SUBMIT' form. The connection is made I presume as it's the same code as for the entry and that works just fine. I can display the result as a block of items but not integrate it in a table.

For now as the code is, it just returns a blank page...

I find many examples from a couple years ago but things have changed since..

Here is the code on the PHP page that should display the results in a table.

Thank you very much for any hints or errors that would jump out to your eyes. I've tried different ways of integrating the results to a table before coming here for help but all return the same result. I am fairly new to this.

<?php $servername = "localhost"; $username = "root"; $password = "Rmvs03ff"; $dbname = "EmployeeListing"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if (isset($_POST['submit-search'])) { $search = mysqli_real_escape_string($conn, $_POST['search']); $sql = "SELECT * FROM BasicEmployee WHERE EmployeeID LIKE '%$search%' OR FirstName LIKE '%$search%' OR LastName LIKE '%$search%' OR DoB LIKE '%$search%'"; $result = mysqli_query($conn, $sql); $queryResult = mysqli_num_rows($result); echo "<br/>There are " .$queryResult. " matches found"; echo "<table> <tr> <th>Employee I.D.</th> <th>Sex</th> <th>First Name</th> <th>Last Name</th> <th>Date of Birth</th> </tr>"; if ($queryResult > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "<tr>" echo "<td><strong> ".$row['EmployeeID']." </strong></td>" echo "<td> ".$row['Prefix']." </td>" echo "<td><p> ".$row['FirstName']." </p></td>" echo "<td><p> ".$row['LastName']." </p></td>" echo "<td><p> ".$row['DoB']." </p></td>"; echo "</table>"; } } else { echo "<br/>No results found"; } } echo "<br/>Approved"; $conn->close(); ?> </body> </html>

I do have the opening html, head an bodies of course, didn't want to block up space with this...

Embed 2D labelled array in Pandas

Sun, 11/19/2017 - 23:23

I am trying to do operations on a dataframe but I cannot seem to reformat it in the way that I want.

I have:

>>df = pd.DataFrame({ 'person':['Al','Al','Bob','Bob','Bob','Sue','Sue'], 'pet':['Cat','Dog','Fish','Fish','Zebra','Fish','Dog']}) >>df person pet 0 Al Cat 1 Al Dog 2 Bob Fish 3 Bob Fish 4 Bob Zebra 5 Sue Fish 6 Sue Dog

I want to aggregate to the person level and have nested labels like so:

person pet_info pet number 0 Al Cat 1 Dog 1 1 Bob Fish 2 Zebra 1 ....

such that there are two labels/column names within the pet_info column so that:

for row in df: print(row['person']) for stuff in row['pet_info']: print(stuff['pet'])

will output:

Al Cat Dog Bob Fish ...

Any ideas on how to do this? I can't seem to implement this change in this way and I am reasonably familiar with pandas...

Thanks!

PHP is not echoing the data from AJAX

Sun, 11/19/2017 - 21:49

index.js

$(document).on("click", ".player", function(){ var id = $(this).attr("id"); var values = $(id).serialize(); $.post('./connections/lobby.class.php', { data: values }, function(data) { alert(id); }); });

lobby.class.php

public function userPublicInfo() { $stmt = $this->db->prepare("SELECT * FROM account WHERE id='$this->id'"); $stmt->execute(); $rows = $stmt->fetch(PDO::FETCH_ASSOC); echo $rows['UserID']; }

game.php

<?php include_once "connections/db.php"; $lobby->lobbySession(); $lobby->userPublicInfo(); <!DOCTYPE html> <html> <head> Rest of my html code pretty much

When I press on the players name in the lobby, it does catch the ID. For example: https://i.gyazo.com/9187b3d75a4633d564b51b0678444e1c.mp4

So as you can see, the Jquery click function is grabbing the appropriate ID's for the PHP mysql data called.

Now when I pass the id through Ajax, and try to echo the id or use it in a query, it doesn't work. I got this to work in a different project, but in this one it's not.

What am I doing wrong? Need help

How does R know to use a function, if that functions name has been reassigned to a value?

Sun, 11/19/2017 - 21:15

I know it's good practice not to use names from the global namespace when naming variables, but what happens when you do this accidentally?

I thought I would lose the previous object but R seems to have some trickery under the hood:

print(sd) #> function (x, na.rm = FALSE) #> sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), #> na.rm = na.rm)) #> <bytecode: 0x0000000017e687b8> #> <environment: namespace:stats> sd <- 12.2 print(sd) #> [1] 12.2 sd(1:10) #> [1] 3.02765

So now R knows there is both a length one double vector called sd and a stats function sd() in the global namespace?

Or when I call sd(1:10) the interpreter automatically expands this to sd.default()? But how does R know to look for a default method on sd as it's now a vector? So functions and variables stored in different places in memory can be referenced by the same name?

obviously_a_user_defined_variable <- 257 obviously_a_user_defined_variable(1:10) #> Error in obviously_a_user_defined_variable(1:10): could not find # function "obviously_a_user_defined_variable"

Unable to deploy an Ionic Framework app on ios device

Sun, 11/19/2017 - 21:06

I'm developing an ionic framework app with Ionic 2. I can deploy via my MAC to an android device using 'ionic cordova run android'. But when I execute 'ionic cordova run ios' I get the following error:

Code Signing Error: Signing for "App" requires a development team. Select a development team in the project editor. Code Signing Error: Code signing is required for product type 'Application' in SDK 'iOS 11.1'

All of the online answers for this issue only mention signing provisions in xCode but I'm not sure how that would resolve an Ionic app created in Visual Code. I didn't do any development in xCode and it's only installed in order to use the emulator. The solutions say to open the app in xcode for the signing but you can't even open an Ionic app in xCode.

Could someone please help with this, I've had this issue for weeks with ios.

Pages