text
stringlengths
15
59.8k
meta
dict
Q: How will I make this sequence correct in using c program I want to print a sequence of 1 4 9 16 25...n by inputting any number which is equal to the number of terms I want as an output. For example: if I input 4, it should print 1 4 9 16 but I can't seem to get the result I want using this program I have made. The result goes like 0 1 4 9. I want to eliminate the first term zero, Can someone pls help me see what's wrong with my program? int result,n; for (int i = 1; i <= n; i++){ scanf("%d", &n); printf("%d ", result); result = pow(i,2); } A: #include <stdio.h> int main() { int result, i, n; printf("Input n: "); scanf("%d", &n); for(int i = 1; i <= n; i++) { result = i*i; printf("%-3d", result); } } OUTPUT: 1 4 9 16... n^2 Probably, you want this. You should scan the value of n before the loop. Otherwise, the behavior of your program would be unpredictable. Second, it is wise to avoid floating-point calculations when possible and here you want to print the series of square of integers. i.e. 1,4,9,... so you shouldn't use double pow(double a, double b) function. Also as Fred said, "Calculate result before you print it."
{ "language": "en", "url": "https://stackoverflow.com/questions/67708282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ambiguous reference error while compiling I have an Arrays class which contains several utility methods. The two methods in question are: @SafeVarargs public static <T> int indexOf(T needle, T ... haystack) { for (int i = 0; i < haystack.length; i++) { if (needle == null?haystack[i] == null:needle.equals(haystack[i])) return i; } return -1; } public static int indexOf(char needle, char ... haystack) { for (int i = 0; i < haystack.length; i++) { if (needle == haystack[i]) return i; } return -1; } @SafeVarargs public static <T> boolean contains(T needle, T ... haystack) { return indexOf(needle, haystack) != -1; } public static boolean contains(char needle, char ... haystack) { return indexOf(needle, haystack) != -1; } I have another class which makes use of the char version like so: char type = getType(); Arrays.contains(type, 'B', 'C', 'D', 'E'); When compiling with javac, it fails with an error like: [ERROR] /path/to/MyClass.java:[63,30] reference to contains is ambiguous both method <T>contains(T,T...) in Arrays and method contains(char,char...) in Arrays match
{ "language": "en", "url": "https://stackoverflow.com/questions/35756235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make javascript run onclick instead of pageload I have the the following script that runs when the page is loaded: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> How can I execute it when a button is clicked rather then when it loads? A: put it in a function, and call it on an onclick event on an element function myEvent() { j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); } then in your html <input type='button' value='Click Me' onclick='myEvent();' /> A: The code example you have isn't actually running on page load. It's running as it's interpreted by the DOM. But here is a solution to your request. The HTML button must be above the script tag. So you'll want something just like this: <input type="button" value="Click me for action" id="actionButton" /> <script type="text/javascript"> document.getElementById("actionButton").addEventListener("click", function() { j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); }, false); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/14675302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Refer to outer column in inner query Where clause I have two tables Employee and Departament in relation that is shown bellow. For each departament I want to get the fifth best paid employee. How the query should look like if we have for example MySQL? I trying to do something like this but it doesn’t see d.id column in inner select. select d.name, e.id from Employee e join Departament d on d.id = e.dep_id where e.id = ( select s.eid from ( select ee.id as eid, @rowid:=@rowid+1 as rowid from Employee ee, (SELECT @rowid:=0) as init where ee.dep_id = d.id order by ee.salary desc ) s where s.rowid = 5 ) Is it possible to do it in generic way not dependent to any database semantics? How to do it using MySQL and what is the best way to do it? A: Just do the row_id calculation in the from clause: select d.name, e.id from (select ee.*, (@rowid := if(@d = dept_id, @rowid + 1, if(@d := dept_id, 1, 1) ) ) as rowid from Employee ee cross join (SELECT @rowid := 0, @d := NULL) as init order by ee.dept_id, ee.salary desc ) e join Departament d on d.id = e.dept_id where e.rowid = 5; And, yes, there is an ANSI standard way of doing this. In fact, I can readily think of two approaches. But MySQL supports neither window functions not fetch first 1 row only. A: SELECT X.NAME, X.SALARY AS SAL_5 FROM ( SELECT DEPT.NAME,EMP.SALARY, RANK() OVER (PARTITION BY NAME ORDER BY SALARY DESC) RN FROM EMP, DEPT WHERE EMP.DEPT_ID=DEPT.DEPT_ID ) X WHERE X.RN=5;
{ "language": "en", "url": "https://stackoverflow.com/questions/28880245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: drag and drop feature don't work properly I'm making a little utility for dragging and dropping some images inside a table, the thing is that every works correctly until I drop the image inside the table, the image is dropped in a different position to the one had been chosen $(function () { $('td.soccer-field').click(function () { if ($('#dice1').text() != '' && $('#dice2').text() != '') { if ($('td[data-path="begin-path"]').length == 0) { $(this).attr('data-path', 'begin-path'); $(this).off('mouseenter mouseleave'); $(this).addClass('selected-path'); } else if ($('td[data-path="begin-path"]').length && $(this).attr('data-path') != 'begin-path' && $('td[data-path="end-path"]').length == 0) { $(this).attr('data-path', 'end-path'); $(this).addClass('actual-path'); $('.selected-path').addClass('actual-path'); $('.actual-path').removeClass('selected-path'); } else if ($(this).attr('data-path') == 'end-path') { $(this).removeAttr('data-path'); $('.actual-path').addClass('selected-path'); $('.selected-path').removeClass('actual-path'); } ; } }); $('td.soccer-field').hover(function () { if ($('#dice1').text() != '' && $('#dice2').text() != '') { if ($('td[data-path="begin-path"]').length == 0) { $(this).attr('data-path', 'select-begin-path'); } else if ($(this).attr('data-path') != 'begin-path') { var presentCell = $(this).attr('id') + $(this).parent().attr('id'); var cell; if ($(this).attr('data-path') == 'ending') { $('.selected-path').each(function () { cell = $(this).attr('id') + $(this).parent().attr('id'); distance = new Board().calculateDistanceSquares(presentCell, cell); if (distance == 1) { $('[data-path="ending"]').removeClass('selected-path'); $('[data-path="ending"]').removeAttr('data-path'); if ($(this).attr('data-path') != 'begin-path') { $(this).attr('data-path', 'ending'); } return; } }); } else if ($('td[data-path="end-path"]').length == 0) { var actualCell = $(this); var dicesResult = parseInt($('#dice1').text()) + parseInt($('#dice2').text()); $('.selected-path').each(function () { cell = $(this).attr('id') + $(this).parent().attr('id'); distance = new Board().calculateDistanceSquares(presentCell, cell); if (distance == 1 && $('.selected-path').length <= (dicesResult - 1)) { actualCell.attr('data-path', 'ending'); actualCell.addClass('selected-path'); if ($(this).attr('data-path') != 'begin-path') { $(this).removeAttr('data-path'); } ; return; } }); } } } }, function () { if ($(this).attr('data-path') == "select-begin-path") { $(this).removeAttr('data-path'); } }); $('#diceRoller').click(function () { $('#dice1').text(Math.floor(Math.random() * 6) + 1); $('#dice2').text(Math.floor(Math.random() * 6) + 1); $(this).attr('disabled', true); }); $('.drag-container img.draggable').draggable({ cursor: 'move', containment: '#left', revert: 'invalid', refreshPositions: true, opacity: .45, delay: 50 }); $('td.soccer-field').droppable({ accept: 'img.draggable', hoverClass: 'hover-pawn', drop: function (event, ui) { $(this).append(ui.draggable); ui.draggable.draggable("option", "disabled", true); } }); }); //function Board(playerTurn, piecesPosition, gamePhase, gameBegginingType, container) function Board() { this.buildBoard = function (container, gamePhase, playerTurn) { var playerTurn = playerTurn; var gamePhase = gamePhase; var board = $('<table></table>').attr('id', 'board'); if (gamePhase == 0) { var sparePiecesBlack = $('<div></div>').attr('id', 'spare-pieces-black'), img; sparePiecesBlack.addClass('drag-container'); for (var i = 0; i < 5; i++) { img = $('<img>').attr('id', i + 1); img.addClass('black draggable'); img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Chess_pdt45.svg/45px-Chess_pdt45.svg.png'); sparePiecesBlack.append(img); $("#diceRoller").attr('disabled', true); } ; $('#' + container).append(sparePiecesBlack); } ; var row, cell, containerHeight, containerWidth; for (var i = 0; i < 10; i++) { row = $('<tr></tr>').attr('id', i + 1); for (var j = 0; j < 20; j++) { cell = $('<td></td>'); if ((j == 0 || j == 19) && (i >= 3) && (i <= 6)) { cell.addClass('behind-goal'); } else if ((j > 0) && (j < 19)) { cell.attr('id', String.fromCharCode(j + 96)); cell.addClass("soccer-field"); } ; row.append(cell); } board.append(row); } $('#' + container).append(board); if (gamePhase == 0) { var sparePiecesWhite = $('<div></div>').attr('id', 'spare-pieces-white'), img; sparePiecesWhite.addClass('drag-container'); for (var i = 0; i < 5; i++) { img = $('<img>').attr('id', i + 1); img.addClass('white draggable'); img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Chess_pdt45.svg/45px-Chess_pdt45.svg.png'); sparePiecesWhite.append(img); } ; $('#' + container).append(sparePiecesWhite); } ; }; this.calculateHorizontalDistance = function (sq1, sq2) { var column1 = sq1.substring(0, 1).charCodeAt(0); var column2 = sq2.substring(0, 1).charCodeAt(0); return (Math.abs(column1 - column2)); }; this.calculateVerticalDistance = function (sq1, sq2) { var row1 = parseInt(sq1.substring(1)); var row2 = parseInt(sq1.substring(1)); return (Math.abs(row1 - row2)); }; this.calculateDistanceSquares = function (sq1, sq2) { return(this.calculateVerticalDistance(sq1, sq2) + this.calculateHorizontalDistance(sq1, sq2)); } } var board = new Board(); board.buildBoard('left', 0, 'black'); #left table{ border:0.2em solid black; border-collapse:collapse; } #left table tr{ height: 2.5em; } #left table tr td{ width: 3.33em; } td.soccer-field{ border: 0.1em solid black; } td.behind-goal{ background-color: #F8FAB4; } .selected-path.soccer-field, td[data-path="select-begin-path"],.hover-pawn.soccer-field{ border: 0.15em solid #F8FAB4; } .actual-path.soccer-field{ border: 0.15em solid #F72D48; } .drag-container img:hover { cursor: move; } .drag-container{ display: inline-block; } img { width : 3.33em; height: 2.5em } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <div id="boardContainer"> <div id="right"> <p id="dice1"></p><p id="dice2"></p> <button id="diceRoller">Lanzar Dados</button> </div> <div id="left"></div> </div> Any help will be really appreciated Note: I've already tried to do the same with divs. It works the same as works the snippet above
{ "language": "en", "url": "https://stackoverflow.com/questions/30678869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asyncio requests using multithreading I have a large list of companies and am calling a REST API to get daily stock price for each company. Details are stored in a PostgreSQL database. The core function looks as follows: async def get_data_asynchronous(): conn = await asyncpg.connect(**DBConn) path = 'path' source = pd.read_excel(io=path + 'companies.xlsx', sheet_name='data') retries = Retry(total=2, backoff_factor=1, status_forcelist=[404, 502, 503, 504]) dates = pd.date_range('2015-01-01', '2019-12-01', freq='D').strftime("%d-%m-%Y").tolist() with ThreadPoolExecutor(max_workers=10) as executor: with requests.Session() as session: session.mount('https://', HTTPAdapter(max_retries=retries)) loop = asyncio.get_event_loop() for index, inputrow in source.iterrows(): try: if int(inputrow['rowid']) > 0: compid = inputrow['compid'].lower().strip() tasks = [ loop.run_in_executor( executor, fetch, *(session, compid, datetime.datetime.strptime(str(dates[i-1]), '%d-%m-%Y'), datetime.datetime.strptime(str(dates[i]), '%d-%m-%Y')) ) for i in range(len(dates)) ] for content in await asyncio.gather(*tasks): if content is not None: for data in content: compid = data.get('compid', '') date = data.get('date', '') stock_price = data.get('sprice', '') try: await conn.execute(''' INSERT INTO comp_dailyhistory VALUES($1, $2, $3) ''', compid, date, stock_price) except Exception as e: print('ERROR') pass pass except Exception as e: print(str(e)) pass In the above function, I first get the list of companies from am excel worksheet (source) and create a list of dates. Since there are more than 200k companies in my list, I create a ThreadPoolExecutor of up to 10 workers. The aim is to pass each company id (compid) and two consecutive dates from the date range to a 'fetch' function in an asynchronous manner, so as to speed up the whole data collection process. The fetch function looks as follows: def fetch(session, compid, start, stop): base_url = 'baseurl' try: with session.get(base_url + 'compid=' + compid + '&begin=' + str(int(start.timestamp())) + '&end=' + str(int(stop.timestamp())), timeout=None) as data: content = [] if data.status_code == 200: for item in data.json(): ret = {'compid': compid, 'date': str(date), 'sprice': sprice} content.append(ret) return content else: return None except Exception as e: return None The fetch function uses requests.get to get a list of stock prices for the company between start and stop dates, parses the JSON response into a list of key-value pairs, and returns them to the calling function. The returned lists are then are picked up by the asyncio.gather function in the calling function, where each stock price is stored in postgreSQL using asyncpg. The rest of the code is as follows: def main(): loop = asyncio.get_event_loop() future = asyncio.ensure_future(get_data_asynchronous()) loop.run_until_complete(future) main() The main issue with this set up is that the script does not seem to be picking up the full set of prices for a given company. For example, for compid = 1, there should be exactly 600 daily prices. However, I get a different result each time the script is run, which is always lower than the true count. For instance, I get 550 daily prices in the first run, 570 in the second run, 540 in the third run, and so on.... Why is my script unable to pick up the full list of 600 daily prices? Are some of my requests getting dropped somehow? I tried an alternative with aiohttp requests, but haven't made much progress. I have no experience with multithreaded programming, especially with asyncio, and would really appreciate any help in this regard? Thanks in advance for your time. A: I have done several projects involving scraping websites to obtain thousands of stock prices each day. The problem, as dano suggested, is related to your error handling: except Exception as e: return None This does nothing to handle failed requests. You can append the failed urls to a list, and at the end of your script run your "get" function again with those urls. If your information is critical, you can even define a function that tries at least 5-10 times to download the information of a stock before it returns None. More related to the multithreading question, you need to be careful with the number of requests per second/minute/hour and avoid exceeding the API/website rate limit. You can use multiple proxies for that. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/60514129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return max value of each row of a group of columns I have a table of over 10,000 rows and over 400 columns. For columns containing at least the string 'xyz', I need to find the max value of each row (within these 'xyz' columns), and create 2 new columns. The 1st new column would contain the max value of each row of these 'xyz' columns. The 2nd new column would contain the column name from which the max value was retrieved. I'm stuck at creating the 2nd column. I've tried some stuff which doesn't work like; Match = df[CompCol].isin[SpecList].all(axis=1) How should approach the 2nd column? A: another way using 'regex' and 'idmax. df = pd.DataFrame({'xyz1': [10, 20, 30, 40], 'xyz2': [11, 12,13,14],'xyz3':[1,2,3,44],'abc':[100,101,102,103]}) df['maxval']= df.filter(regex='xyz').apply(max, axis=1) df['maxval_col'] = df.filter(regex='xyz').idxmax(axis=1) abc xyz1 xyz2 xyz3 maxval maxval_col 100 10 11 1 11 xyz2 101 20 12 2 20 xyz1 102 30 13 3 30 xyz1 103 40 14 44 44 xyz3 A: Does this work for you? import pandas as pd df = pd.DataFrame([(1,2,3,4),(2,1,1,4)], columns = ['xyz1','xyz2','xyz3','abc']) cols = [k for k in df.columns if 'xyz' in k] df['maxval'] = df[cols].apply(lambda s: max(zip(s, s.keys()))[0],1) df['maxcol'] = df[cols].apply(lambda s: max(zip(s, s.keys()))[1],1) df Out[753]: xyz1 xyz2 xyz3 abc maxval maxcol 0 1 2 3 4 3 xyz3 1 2 1 1 4 2 xyz1
{ "language": "en", "url": "https://stackoverflow.com/questions/30181096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get token expiration with `jsonwebtoken` using typescript I'm using jsonwebtoken to decode a token, and I'm trying to get the expiration date. Typescript is throwing errors regarding the exp property, and I'm not quite sure how to solve them: import jwt from 'jsonwebtoken' const tokenBase64 = 'ey...' /* some valid token */ const token = jwt.decode(tokenBase64) const tokenExpirationDate = token.exp // ^^^ // Property 'exp' does not exist on type 'string | object'. Property 'exp' does not exist on type 'string'. I have installed @types/jsonwebtoken, and looked for a token type to cast token, but did not find any. Suggestions? Using * *@types/jsonwebtoken@7.2.3 *jsonwebtoken@8.1.0 .tsconfig: { "compilerOptions": { "allowJs": true, "baseUrl": ".", "jsx": "Preserve", "moduleResolution": "Node", "module": "ESNext", "sourceMap": true, "removeComments": true, "allowSyntheticDefaultImports": true, "target": "ESNext" } } A: I got the same error message when I used the line import jwt from 'jsonwebtoken' With var jwt = require('jsonwebtoken'); [1] instead it works fine: var jwt = require('jsonwebtoken'); var tokenBase64 = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiZXhwIjoiMTUxMTk1MDcwMyIsImFkbWluIjp0cnVlfQ.wFC-9ZsqA9QuvLkRSkQmVYpUmgH9R-j8M4D0GECuPHY'; const token = jwt.decode(tokenBase64); const tokenExpirationDate = token.exp console.log(tokenExpirationDate); [1] see also https://github.com/auth0/node-jsonwebtoken A: The only way I found to user import is: import { sign, verify } from 'jsonwebtoken'; sign('Hello', 'secret'); But I think the require method is better so that you don't have to explicitly import every single function. A: As of jsonwebtoken 8.3, jsonwebtoken.decode() has the following type definitions: export function decode( token: string, options?: DecodeOptions, ): null | { [key: string]: any } | string; Since Typescript cannot infer the correct type and exp is not known, the simplest way out is to cast the result to any. import jwt from 'jsonwebtoken' const tokenBase64 = 'ey...' /* some valid token */ const token: any = jwt.decode(tokenBase64) const tokenExpirationDate = token.exp A: I think import * as jwt from 'jsonwebtoken'; should work as expected. A: import * as jwt from 'jsonwebtoken' const { authorization } = ctx.req.headers const token = authorization.replace('Bearer ', '') const decoded = jwt.verify(token, 'APP_SECRET') const userId = (decoded as any).userId Of course you can type decoded the way you use the token instead of any A: The return type of jwt.verify and jwt.decode is 'string | object'. In your case, you have some additional information that Typescript does not have about the type of the return type. So you can add it like this: const token = jwt.decode(tokenBase64) as {exp: number} const tokenExpirationDate = token.exp Of course you can add any other value in the object as well. While it's reasonable to assume that exp is present, other keys might not be present. Make sure that the token you are decoding actually includes them or add it as an optional value: ({exp: number; random?: string}) A: This is how I am using decode with TS import jwt from 'jsonwebtoken'; export const isTokenExpired = (token: string): boolean => { try { const { exp } = jwt.decode(token) as { exp: number; }; const expirationDatetimeInSeconds = exp * 1000; return Date.now() >= expirationDatetimeInSeconds; } catch { return true; } }; Not needed but here you go as well import 'jest'; import jwt from 'jsonwebtoken'; import { isTokenExpired } from 'path-to-isTokenExpired/isTokenExpired'; describe('isTokenExpired', () => { it('should return true if jwt token expired', () => { const currentTimeInSecondsMinusThirtySeconds = Math.floor(Date.now() / 1000) - 30; const expiredToken = jwt.sign({ foo: 'bar', exp: currentTimeInSecondsMinusThirtySeconds }, 'shhhhh'); expect(isTokenExpired(expiredToken)).toEqual(true); }); it('should return false if jwt token not expired', () => { const currentTimeInSecondsPlusThirtySeconds = Math.floor(Date.now() / 1000) + 30; const notExpiredToken = jwt.sign({ foo: 'bar', exp: currentTimeInSecondsPlusThirtySeconds }, 'shhhhh'); expect(isTokenExpired(notExpiredToken)).toEqual(false); }); it('should return true if jwt token invalid', () => { expect(isTokenExpired('invalidtoken')).toEqual(true); }); }); A: I found myself creating a helper for this (class based solution - can be used as separate function of course): import { JwtPayload, verify } from "jsonwebtoken"; export class BaseController { // ... static decodeJWT = <T extends { [key: string]: any }>(token: string) => { return verify(token, process.env.JWT_ACCESS_TOKEN!) as JwtPayload & T; // this typing allows us to keep both our encoded data and JWT original properties }; } used in controllers like: import { BaseController } from "./BaseController"; export class UserController extends BaseController { static getUser = async ( // ... ) => { // get token // username may or may not be here - safer to check before use const payload = this.decodeJWT<{ username?: string }>(token); // no error here, we can extract all properties defined by us and original JWT props const { username, exp } = payload; // do stuff... }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/47508424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: LValue required - Reason and solution for my first program I am doing my 1st year engineering. I am beginner to programming. I have program where I get the error - LValue required on the lines - 30,31 and 32 (marked in the code below). What is the reason for the error? #include<stdio.h> #include<conio.h> struct employee { char empname[30]; int leave; }; main() { struct employee a[1000]; int bp=5000,salary,x,i,j,k; char w[30]; int t; x=(bp*120)/100; salary=bp+x; printf("Enter the number of employees:"); scanf("%d",&j); for(i=0;i<j;i++) { printf("Enter employee name and number of days he/she took leave:"); scanf("%s%d",&a[i].empname, &a[i].leave); } for(i=0;i<j;i++) { for(k=i+1;k<j;k++) { if(a[i].empname[0]>a[k].empname[0]) { w= a[i].empname; // Line 30 a[i].empname=a[k].empname; // Line 31 a[k].empname=w; // Line 32 t=a[i].leave; a[i].leave=a[k].leave; a[k].leave=t; } } } for(i=0;i<j;j++) { if(a[i].leave>10) salary=salary-((a[i].leave-10)*366); } for(i=0;i<j;i++) { printf("Employee name = %s\nNumber of days leave = %d\nSalary = %d\n",a[i].empname,a[i].leave,salary); } getch(); } A: It looks like you want to make string copy for permutation in these lines w= a[i].empname; a[i].empname=a[k].empname; a[k].empname=w; you can not make string copy in this way in C you have to use strcpy() instead char * strcpy ( char * destination, const char * source ); so you can make the permutation in this way strcpy(w, a[i].empname); strcpy(a[i].empname, a[k].empname); strcpy(a[k].empname, w); A: Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and its value will be the address of the first element in the array. This converted expression is not an lvalue, meaning it may not be the target of an assignment. If you want to copy the contents of one array to another, you'll need to use a library function. For C strings (arrays of char with a terminating 0 value) use strcpy or strncpy. For other array types, use memcpy. So, those lines should be strcpy( w, a[i].empname ); strcpy( a[i].empname, a[k].empname ); strcpy( a[k].empname, a[i].empname );
{ "language": "en", "url": "https://stackoverflow.com/questions/20219612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What information can I get from the android browser JavaScript? I know I can get screen width/height in a browser, can I get any other information about the device? Device name, OS, carrier, etc? A: It seems as though the only additional resources you're provided with have to do with screen density and resolution: http://developer.android.com/guide/webapps/index.html. However, if you are going to display this page in a WebView, you can utilize the Java-Javascript bridge to access any information available to the standard Java API (or non standard if you want to get creative and use reflection ;-) ) A: Edit: Oops, didn't see you meant from the browser javascript >< disregard information below. android.os.Build provides a lot of information. Try: String s="Debug-infos:"; s += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")"; s += "\n OS API Level: " + android.os.Build.VERSION.SDK; s += "\n Device: " + android.os.Build.DEVICE; s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")";
{ "language": "en", "url": "https://stackoverflow.com/questions/4851986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: NOT IN in Hive QL I'm converting a SQL Server stored procedure to HiveQL. How can I convert something like: SELECT * FROM table1 WHERE id NOT IN (7,6,5,4,2,12) A: NOT IN is now supported in Hive. See https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF. A: Try this: SELECT * FROM table1 WHERE NOT array_contains(array(7,6,5,4,2,12), id) A: According to the documentation it says you can use not in: The negated forms can be written as follows: from DomesticCat cat where cat.name not between 'A' and 'B' from DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' ) Are you getting an error when you try your query in the question? Please try based on the references as well. * *Reference 1. *NOT IN Clause in HQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/14224335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Are `System.MulticastDelegate`'s thread-safe? I'm looking for someone that might know more about this, my gut tells me that the answer is "no, it is not thread-safe" but I want to be sure. In order to illustrate my question, I have provided some context with this class public class MyContext { private readonly object _lock = new object(); public delegate bool MyDelegate(MyContext context); private MyDelegate _multicastDelegate; public MyContext() { _multicastDelegate = null; } public void AddDelegate(MyDelegate del) { lock(_lock) { _multicastDelegate += del; } } public void RemoveDelegate(MyDelegate del) { lock(_lock) { _multicastDelegate += del; } } public void Go() { _multicastDelegate.Invoke(this); } } Edit: I added locks to the example above, but it's really not the point of my question. I am trying to understand better if the array that holds the invocation list is thread-safe. Frankly, I am not clearly seeing how this all gets put together and some help would be appreciated. According to documentation I have found, the only quote that provides no real insight is the following: A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. If an error occurs during execution of the list then an exception is thrown. https://msdn.microsoft.com/en-us/library/system.multicastdelegate.aspx Thanks in advance. A: Delegates are immutable. You never change a delegate. Any method that appears to mutate a delegate is in fact creating a new instance. Delegates are immutable; once created, the invocation list of a delegate does not change. There is thus no cause for concern that the invocation list may be updated whilst a delegate is being invoked. What you do have to guard against, however, and have failed to do in your method is when the delegate may in fact be null. (new MyContext()).Go(); will cause an exception. You used to have to guard against this by reading the value into a local variable, testing it for null and then invoking using it. It can now more easily be resolved as: public void Go() { _multicastDelegate?.Invoke(this); } A: The definition of thread-safe as used by MSDN documentation means code that is properly synchronized. It usually doesn't state on what it synchronizes, but it can be the class object for static members, the instance object for instance members, or it can be some inner object, such as SyncRoot in many collection types. Although delegates are immutable, you must still synchronize properly. .NET and C#, unlike Java, don't guarantee safe publication, so if you don't guarantee synchronization, you can observe a partially initialized object in other threads1. To turn your code thread-safe, you just need to use _lock when reading from the delegate field as well, but you can call Invoke outside the lock, landing onto the delegate the responsibility to keep its own thread safety. public class MyContext { private readonly object _lock = new object(); public delegate bool MyDelegate(MyContext context); private MyDelegate _delegate; public MyContext() { } public void AddDelegate(MyDelegate del) { lock (_lock) { _delegate += del; } } public void RemoveDelegate(MyDelegate del) { lock (_lock) { // You had a bug here, += _delegate -= del; } } public void Go() { MyDelegate currentDelegate; lock (_lock) { currentDelegate = _delegate; } currentDelegate?.Invoke(this); } } * *Microsoft's .NET Framework implementation always makes volatile writes (or so they say), which kind of gives you safe publication implicitly, but I personally don't rely on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/48683134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The output shows zero, variable doesn't store the value The main class: package tdm; import java.util.Scanner; /** * * @author abbas */ public class TDM { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("** WHAT DO YOU WANT TO FIND? **"); System.out.println("1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame"); System.out.println("2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate"); System.out.println("3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame"); System.out.println("4. Find everything!!"); int choice; System.out.println(); System.out.print("Enter your choice: "); choice = input.nextInt(); switch (choice) { case 1: { Ex1 ex1 = new Ex1(); ex1.calculateEx1(); break; } } } } The Ex1 class /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tdm; import java.util.Scanner; /** * * @author abbas */ public class Ex1 { public void calculateEx1() { Scanner input = new Scanner(System.in); int connectionsNum, dataRate, bitMultiplexed; System.out.print("Enter number of connections: "); connectionsNum = input.nextInt(); System.out.print("Enter the data rate (Kbps) for each connection: "); dataRate = input.nextInt(); System.out.print("Enter number of bit(s)"); bitMultiplexed = input.nextInt(); System.out.println("** Your question is **"); System.out.println("The data rate for each one of the " + connectionsNum + " connections is " + dataRate + " Kbps. If " + bitMultiplexed + " bit at time is multiplexed, what is (A) The duration of each" + " input slot, (B) duration of each output slot and (C) duration " + "of each frame"); System.out.println("** The answer is **"); int inputSlot = (bitMultiplexed / (dataRate * 1000)); int outputSlot = ((1 / connectionsNum) * inputSlot); int frameDuration = (connectionsNum * outputSlot); System.out.println(inputSlot); System.out.println(outputSlot); System.out.println(frameDuration); } } The output: run: ** WHAT DO YOU WANT TO FIND? ** 1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame 2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate 3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame 4. Find everything!! Enter your choice: 1 Enter number of connections: 3 Enter the data rate (Kbps) for each connection: 1 Enter number of bit(s): 1 ** Your question is ** The data rate for each one of the 3 connections is 1 Kbps. If 1 bit at time is multiplexed, what is (A) The duration of each input slot, (B) duration of each output slot and (C) duration of each frame ** The answer is ** 0 0 0 BUILD SUCCESSFUL (total time: 14 seconds) As you can see, the three variables inputSlot, outputSlot and frameDuration should store the result of the expression. But as you can see in the output it shows 0. I think this is weird!! This is the first time something like this happen to me. I suppose it's a small problem but I can't figure out what it's!! A: Enter the data rate (Kbps) for each connection: 1 Okay, so dataRate = 1. Enter number of bit(s): 1 And bitMultiplexed = 1. System.out.println(1 / (1000 * 1)); // 0 Need to cast to a float/double somehow, for example. System.out.println(1 / (1000.0 * 1)) // 0.001 A: As you program/answer suggests. inputSlot = 1 / 10000 = 0; output = (1/3)*0 = 0; frameDuration = 3 * 0 = 0; Since these are int. It will strip the decimal part. Use BigDecimal or double for this purpose A: The variables have to be floats instead of Integers. Integers can only store integers as the name sais. Floats can store point nubers like 0.0002. If u divide the int 20 by 11 and store this as a int Java will put 1 as the result. So if your result is 1.9 it is 1.0 as int. That is the Problem here. It looks like this float inputSlot = (bitMultiplexed / (dataRate * 1000)); float outputSlot = ((1 / connectionsNum) * inputSlot); int frameDuration = (connectionsNum * outputSlot); System.out.println(inputSlot); System.out.println(outputSlot); System.out.println(frameDuration); If you have a question ask me :) A: The problem arises due to these 3 fields being initialized as ints. If you make them double your problem will be solved because when you declare them as ints, it will take just the integer part. So for example if you have 0.588 it will take just the 0 which is what is happening as of now. int inputSlot = (bitMultiplexed / (dataRate * 1000)); int outputSlot = ((1 / connectionsNum) * inputSlot); int frameDuration = (connectionsNum * outputSlot); In order to solve this, you need to change the int to double.
{ "language": "en", "url": "https://stackoverflow.com/questions/41211534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to add button (onclick event) on tabs but not switch the panes - semantic UI I want to add a button on top of list of tabs configured with semantic UI. Currently I have 2 tabs which can switch to panes when they are selected and I have third tab - I don't want it to switch when user click on it but rather dispatch an event (to expand the UI) or lets say a alert message. How to achieve this ? Current code example.js import React from 'react' import { Label, Menu, Tab } from 'semantic-ui-react' const panes = [ { menuItem: { key: 'users', icon: 'users', content: 'Users' }, render: () => <Tab.Pane>Tab 1 Content</Tab.Pane>, }, { menuItem: ( <Menu.Item key='messages'> Messages<Label>15</Label> </Menu.Item> ), render: () => <Tab.Pane>Tab 2 Content</Tab.Pane>, }, ] const TabExampleCustomMenuItem = () => <Tab panes={panes} /> export default TabExampleCustomMenuItem index.js import React from "react"; import ReactDOM from "react-dom"; import { Container, Header, List } from "semantic-ui-react"; import pkg from 'semantic-ui-react/package.json' import Example from "./example"; const App = ({ children }) => ( <Container style={{ margin: 20 }}> <Header as="h3">This example is powered by Semantic UI React {pkg.version} </Header> <List bulleted> <List.Item as="a" content=" Official documentation" href="https://react.semantic-ui.com/" target="_blank" /> <List.Item as="a" content=" StackOverflow" href="https://stackoverflow.com/questions/tagged/semantic-ui-react?sort=frequent" target="_blank" /> </List> {children} </Container> ); // TODO: Switch to https://github.com/palmerhq/the-platform#stylesheet when it will be stable const styleLink = document.createElement("link"); styleLink.rel = "stylesheet"; styleLink.href = "https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css"; document.head.appendChild(styleLink); ReactDOM.render( <App> <Example /> </App>, document.getElementById("root") ); A: You need to make use of controlled state to achieve similar result. Take a look at the following example: example.js import React, { useState } from "react"; import { Label, Menu, Tab } from "semantic-ui-react"; const panes = [ { menuItem: { key: "users", icon: "users", content: "Users" }, render: () => <Tab.Pane>Tab 1 Content</Tab.Pane> }, { menuItem: ( <Menu.Item key="messages"> Messages<Label>15</Label> </Menu.Item> ), render: () => <Tab.Pane>Tab 2 Content</Tab.Pane> }, { menuItem: <Menu.Item key="open">Open</Menu.Item> } ]; const TabExampleCustomMenuItem = () => { const [activeIndex, setActiveIndex] = useState(0); return ( <Tab panes={panes} activeIndex={activeIndex} onTabChange={(e, data) => { if (data.activeIndex === 2) { alert(`You've clicked on the "Open" tab!`); return; } setActiveIndex(data.activeIndex); }} /> ); }; export default TabExampleCustomMenuItem;
{ "language": "en", "url": "https://stackoverflow.com/questions/74439945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with httpclient and selfsigned certificates I am sure this has been discussed in this group, but I couldn't find that thread, so bear with it, or if possible merge it with the original. I am using httpclient for my android app and I have a local site which has a few https pages. Since default httpclient doesnot allow self-signed certificates I am using "EasySSLFactory" and "EasyX509TrustManager", which are mentioned in httpclient documentation. client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", new EasySSLSocketFactory(), 443)); The problem is if I use this SSLFactory in my android app, I am getting correct response from my site's https pages, but I get "SSL handshake failure: I/O error during system call, Unknown error: 0" for sites such as "gmail.com", "ymail.com". If I don't use "EasySSLSocketFactory" I get response from these sites but get exception for my site. The funny thing is that this page fetch code works fine as a standalone java application. What could be the problem. Please help me with this. Thanks and Regards A: Solved it for now, since I had just one certificate I put it in emulator's keystore. If somebody has better solution, please let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/3117896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I create an instance of a class from the child of a Mirror object in Swift I am trying to understand why I am unable to create an instance of a class using a mirror in Swift. In the playground, everything seems fine until the very last line of code below. So, here's the first example with the use of type(of:): // First Example var s = String( "Foo" ) // Playground Output: Foo type(of: s) // Playground Output: String.Type var typeClone = type( of: s ).init() // Playground Output: "" (as expected) Everything works as expected. Now, when I try to do this same sort of thing with a child found in a mirror object, the playground complains: // Second Example class FooContainer { var s : String = "Foo" } var t = FooContainer() var tMirror = Mirror( reflecting: t ) // Output: Mirror for FooContainer tMirror.children.first! // Output: {some "s"}, value "Foo") type( of: tMirror.children.first!.value ) // Output: String.Type var typeClone2 = type( of: tMirror.children.first!.value ).init() The line with "typeClone2" is the one that fails. If I break down the expressions and inspect things, it seems like all of the types and values are similar, as in the first example. But in the second case, the playground emits this error: Playground execution failed: error: Type Playground.playground:12:18: error: 'init' is a member of the >type; use 'type(of: ...)' to initialize a new object of the same dynamic >type var typeClone2 = type( of: tMirror.children.first!.value ).init() ^ type(of: ) What do I have to do to make this work? Thanks in advance! A: Your code won't work but the error you get is wrong so you should ignore it. The real problem is you can't just blindly call init() on the type of an Any. There are a lot of types that don't have an init() at all. It works on type(of: s) in your first example because the compiler knows at compile-time that the type is String (and that String has an init()). But if you wrap it in Any then it fails as well: let s = String("Foo") as Any let typeClone = type(of: s).init() Unfortunately this means there's no way to do what you're trying to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/46551253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create element and set custom attribute to map a simple type class property @XmlRootElement(name="flowPane") public class Image implements Serializable { public String name; public String description; } Bound to <flowPane> <label text="name"/> <label text="description"/> </flowPane> Tried simply placing @XmlAttribute and @XmlElement annotations on the name and description properties but neither is the solution that I'm looking for. A: You must wrap the fields with a new class @XmlRootElement(name="flowPanel") public class Image implements Serializable { public static class Label { @XmlAttribute() public String text; public Label(){} public Label(String text) { this.text = text; } } @XmlElement(name="label") public Label name; @XmlElement(name="label") public Label description; } A: Using Standard JAXB APIs In order to get the same element to appear multiple times in an XML document you are going to need a List property. Note in the example below label will have a property mapped to the text attribute. @XmlRootElement(name="flowPanel") @XmlAccessorType(XmlAccessType.FIELD) public class Image implements Serializable { @XmlElement(name="label"). private List<Label> labels; } @XmlPath extension in EclipseLink JAXB (MOXy) If you are using EclipseLink MOXy as your JAXB (JSR-222) provider then you could leverage the @XmlPath extension we added for this use case. @XmlRootElement(name="flowPane") public class Image implements Serializable { @XmlPath("label[1]/@text") public String name; @XmlPath("label[1]/@text") public String description; } For More Information I have written more about this on my blog: * *http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
{ "language": "en", "url": "https://stackoverflow.com/questions/26182517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot run web app published with dnx I have an app based on the preview template of ASP.NET 5 RC1 final. I publish the app by running dnu publish --no-source --runtime active --configuration Release The resulting package contains the runtime "dnx-clr-win-x64.1.0.0-rc1-final". When I copy the package to another Windows machine and try to run the web command in the output\approot directory, I receive the following error: Error: Unable to load application or execute command 'Microsoft.AspNet.Server.WebListener'. Available commands: web, webListener. System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information. at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence) at System.Reflection.Assembly.LoadFile(String path) at Microsoft.Dnx.Runtime.Loader.LoadContext.LoadFile(String assemblyPath) at Microsoft.Dnx.Runtime.Loader.PackageAssemblyLoader.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext) at Microsoft.Dnx.Host.LoaderContainer.Load(AssemblyName assemblyName) at Microsoft.Dnx.Runtime.Loader.AssemblyLoaderCache.GetOrAdd(AssemblyName name, Func`2 factory) at Microsoft.Dnx.Runtime.Loader.LoadContext.ResolveAssembly(Object sender, ResolveEventArgs args) at System.AppDomain.OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName) I have tried both Kestrel and WebListener, same error message. The package works on my machine. Is there anything else that needs to be done to make the app run on another machine? A: To selfhost an application, I have: * *deployed to the file-system (to c-drive of my dev machine) *changed the entry Localhost:5000 (default) in Hosting.ini (C:[app-name]\approot\src[app-name]\ to the IP-Address of my machine *opened the port 5000 in the windows-firewall of my machine then, I was able to load the application from another machine over the LAN. Note you have to start the web.cmd as admin After doing that, I have done the same on our intranet-server (copied the whole deployed directory to the c:-drive of the intranet-server, changed the IP in hosting.ini to the server-ip and opened the port 5000 on the Windows Firewall on the intranet-server). Then I have started web.cmd as admin on the intranet-server and the app is reachable in the LAN (Server-IP:5000 or DNS-name:5000). Note: I have just updated to RC1 and there seems to be various changes to the project-template (therefore, I have re-created my small example-project from scratch). Especially the Hosting.ini-file (where I have changed the Localhost-entry to the machine-IP) is no loger generated / supported. I don't have found any description yet, how exactly the IP has to be changed instead (according to MS, new in the hosting.json-file), but find-out, that it's possible to change it in the project.json-file. I have changed: "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" }, to "commands": { "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://172.16.1.7:5000", "ef": "EntityFramework.Commands" }, Now, it works again. But attention! I'm sure that should be done on another way (according to MS in the hosting.json-file) but - as I wrote - I don't have found any description to the entry in hosting.json-file but found a hint on the Internet to an older version how to do it in the project.json-file. So only take this as temporary workaround, until we know, how to do it correct! And do that only in the deployed directory (not in the VS-project, as else, the local dev-is won't run anymore! A: The problem could be solved by extracting the ZIP file with 7-zip instead of the Windows Explorer, see also: .net local assembly load failed with CAS policy Thanks to @Kiran Challa for the link. A: An alternative to using 7-zip as suggested by @martin klinke you can use the streams -s -d *.* command from sysinternals / technet. This will unblock files marked as being 'unsafe' (see the link provided by Martin). This will unblock files recursively (run it in the root of what was your zip).
{ "language": "en", "url": "https://stackoverflow.com/questions/33807582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: React Componet - Element | undefined Implementing an Ionic Modal as a React Component I got this message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type 'FC<{ onClose: any; tipo: number; }>'. Type 'Element | undefined' is not assignable to type 'ReactElement<any, any> | null'. Type 'undefined' is not assignable to type 'ReactElement<any, any> | null'.ts(2322) I don't see the problem because the component returns elements. So it is not a function return problem. This is the code in question. const MyModal: React.FC<{ onClose: any; tipo: number }> = ({ onClose, tipo }) => { if (tipo === 0) { return ( <> <IonHeader> <IonToolbar> <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver" > {" "} </IonIcon> </IonToolbar> </IonHeader> <IonContent> <div id="contenedor-central"> <IonGrid> <IonRow> <strong id="elementos">Usuario no registrado</strong> </IonRow> <IonRow> <IonButton href="/registro" id="elementos"> Registrarse </IonButton> </IonRow> </IonGrid> </div> </IonContent> </> ); } if (tipo === 1) { return ( <> <IonHeader> <IonToolbar> <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver" ></IonIcon> </IonToolbar> </IonHeader> <IonContent> <div id="contenedor-central"> <strong>Usuario no registrado</strong> </div> <IonButton href="/registro">Registrarse</IonButton> <IonItem>Click List Item To Return Selected Value</IonItem> </IonContent> </> ); } if (tipo === 2) { return ( <> <IonHeader> <IonToolbar> <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver" > {" "} </IonIcon> </IonToolbar> </IonHeader> <IonContent> <div id="contenedor-central"> <IonGrid> <IonRow> <strong id="elementos">Categorías</strong> </IonRow> <IonRow> <IonButton href="/registro" id="elementos"> Registrarse </IonButton> </IonRow> </IonGrid> </div> </IonContent> </> ); } }; A: if typo has only three possible values define it like so type Typo = 1 | 2 | 3; const MyModal: React.FC<{onClose: any; tipo: Typo;}> Your error must vanish :)
{ "language": "en", "url": "https://stackoverflow.com/questions/64920593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Launched application settings but updating app permission crashing the app I have launched application settings using UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil) I am using this to enable camera when the user has denied this once. In settings app, when I enable camera, the application is crashed. Is there any way I can fix it? A: No you can't... Any change in any of your app permission (from the settings) Your app is killed and next time when you launch your application either from app switcher or from the app icon it starts a new process. This is how it works in IOS. Also See this answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/44115930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Postgres convert PATH type to ARRAY Is there any way to convert Postgres PATH type to an ARRAY in order to have index access to it's points? A: There is no way to do that with PostgreSQL alone - you'd have to write your own C function. With the PostGIS extension, you can cast the path to geometry and perform the operation there: SELECT array_agg(CAST(geom AS point)) FROM st_dumppoints(CAST(some_path AS geometry)); A: Try a variant of this.. CREATE OR REPLACE FUNCTION YADAMU.YADAMU_make_closed(point[]) returns point[] STABLE RETURNS NULL ON NULL INPUT as $$ select case when $1[1]::varchar = $1[array_length($1,1)]::varchar then $1 else array_append($1,$1[1]) end $$ LANGUAGE SQL; -- CREATE OR REPLACE FUNCTION YADAMU.YADAMU_AsPointArray(path) returns point[] STABLE RETURNS NULL ON NULL INPUT as $$ -- -- Array of Points from Path -- select case when isClosed($1) then YADAMU.YADAMU_make_closed(array_agg(point(v))) else array_agg(point(v)) end from unnest(string_to_array(left(right($1::VARCHAR,-2),-2),'),(')) v $$ LANGUAGE SQL; -- Eg yadamu=# select * from unnest(YADAMU.YADAMU_asPointArray(Path '((0,1),(1,0),(4,0))')); unnest -------- (0,1) (1,0) (4,0) (3 rows)
{ "language": "en", "url": "https://stackoverflow.com/questions/60389921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: onCreate Intent Strait to URL without seeing a User Interface Ok, so I am new to Developing any kinds of Apps and have limited programming experience but I am trying to show my team a basic android app that skips strait to a website. I figured out the onCreate and using Intent. At this point I am trying to skip the UI completely (where it opens a blank screen with a title). I know everyone says to use webview but the site we are sending the users to is not specifically made to be mobile friendly but does work in on the Chrome mobile browser. Also the users I deal with are very basic and if I can just have them press one button and it takes them to something familiar, it is the best option. Currently this is what I have: public class Launcher_Some_Website extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String url = "https://www.google.com/"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://www.google.com/")); startActivity(i); The app has been tested and is working like this. I am have tried to search for my answer but I am probably not using the correct key words. I know there are websites to make these apps but I need a very bare bones app and need to know exactly what code is in the apk. The purpose is to show that the app does not have to be complex and that it is an option. I will work on making the app more secure once I can make it do what I said I could make it do. A: I think this is not possible but you can make better UI via progress dialog until web site open.You can use AsyncTask for this. That code works for me ; public class MainActivity extends AppCompatActivity { ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new OpenSite().execute(); } private class OpenSite extends AsyncTask<Void,Void,Void>{ @Override protected void onPreExecute() { super.onPreExecute(); progressDialog=new ProgressDialog(MainActivity.this); progressDialog.setMessage("Please Wait..."); progressDialog.setIndeterminate(false); progressDialog.setCancelable(true); progressDialog.show(); } @Override protected Void doInBackground(Void... params) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); Uri uri = Uri.parse("http://www.google.com"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } } } You can delete thread.sleep(2000) if you don't want to wait.
{ "language": "en", "url": "https://stackoverflow.com/questions/44863002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: App / iOS crashes with “Terminating in response to backboardd's termination” I have an app which is crashing with Terminating in response to backboardd's termination Here the app crashes and even the Springboard. You can see the Apple logo for a short time and it seems that the device is rebooting. This is taken from the device log Incident Identifier: AECC8A4C-B6E0-47B5-A2DD-C3A367107087 CrashReporter Key: 26d2ecafff1bd02c1e774f056b3d20c8b03241c3 Hardware Model: iPad4,2 OS Version: iPhone OS 7.1.2 (11D257) Kernel Version: Darwin Kernel Version 14.0.0: Thu May 15 23:17:54 PDT 2014; root:xnu-2423.10.71~1/RELEASE_ARM64_S5L8960X Date: 2015-08-17 16:49:06 +0200 Time since snapshot: 117 ms Free pages: 114466 Active pages: 5397 Inactive pages: 67177 Speculative pages: 258 Throttled pages: 0 Purgeable pages: 0 Wired pages: 52014 File-backed pages: 43687 Anonymous pages: 29145 Compressions: 4016283 Decompressions: 516269 Compressor Size: 10655 Uncompressed Pages in Compressor: 30459 Largest process: backboardd Processes Name <UUID> rpages recent_max fds [reason] (state) CloudKeychainPro <0b4f59ba89df38039892ce8ad342a013> 152 152 100 (daemon) (idle) syslog_relay <1dc57ae8a60c3654bbf327c16a01d551> 88 88 100 (daemon) (idle) storebookkeeperd <83b2723af35f32b3beafb32abd677b7b> 509 509 100 (daemon) (idle) adid <707928b1d97336d5beb5291562421efd> 130 130 200 (daemon) (idle) aosnotifyd <6e3b66f6dad73af08e7f49db92efc045> 559 559 100 (daemon) (idle) installd <4e0b7c36602737a3b0dd0bd733eb4378> 195 195 100 (daemon) (idle) mobileassetd <8574a112afc337638edcd9ac0404f1c6> 1531 1531 200 (daemon) (idle) gamed <943623c4259f306e93b97ce614edf89e> 785 785 100 (daemon) (idle) afcd <208713527dc0315a9198e99db64d3cf1> 119 119 100 (daemon) (idle) timed <294a840542e13dca88162e0fbe687f94> 244 244 100 (daemon) (idle) keybagd <92fe9694044a3f4387459afb0f88a705> 114 114 100 (daemon) (idle) MobileGestaltHel <f20bac36fcac32628ad30c2da33effd8> 161 161 100 (daemon) (idle) geod <fb5d1b37f6703663818bd883ed500ea6> 263 263 100 (daemon) (idle) softwareupdatese <5cfe93434a573beeb6ef41304af4a352> 949 949 200 (daemon) (idle) assetsd <fd2bd931098b341f846302c614cc5ae8> 471 471 200 (daemon) (idle) IMDPersistenceAg <9bd313f498a13e61b54d2ae6ec19ea2c> 220 220 100 (daemon) (idle) accountsd <ee22a71a12f933179729608a16b45094> 622 622 100 (daemon) (idle) itunesstored <3768d425f2103c209fdd1722b8f5acaa> 1171 1171 100 (daemon) (idle) securityd <d79d9800981f3cedad0ca6975c9b9f0c> 602 602 100 (daemon) (idle) mediaremoted <336797e58ac036298bdcdd5d558c227c> 245 245 100 (daemon) (idle) coresymbolicatio <0b798227409d39c3b23e63bf4bcb820d> 89 89 100 (daemon) (idle) DuetLST <06955a348ea2371e8d7ec43936431caa> 452 452 100 (daemon) (idle) sandboxd <e75c30438fb73c20a67dd096f80352e3> 130 130 100 (daemon) (idle) networkd_privile <5bd47a1c3d12302ea6d78a52cf4ab0a4> 90 90 100 (daemon) (idle) routined <6dbb51d76fbb3d79aa6ea9f3c16c608f> 383 383 100 (daemon) (idle) lsd <f2a08944163c31b9a8fd7f3a43ceacb0> 261 261 100 (daemon) (idle) assistantd <5b53d51bff1236baa617758c37d4f862> 418 418 100 (daemon) (idle) xpcd <8b704605eb243a10bfe026138c1908cd> 292 292 100 (daemon) (idle) librariand <c8d851b111f0324e8de6eaf46ac108d0> 380 380 100 (daemon) (idle) MobileMail <f359afe7da513629b0a6b8aa32a0b90b> 1073 1073 100 (resume) (continuous) tccd <e37a9bd3403c34adbbd9d75e9022240a> 179 179 100 (daemon) kbd <2669fa0ab11a356fbd9482881637e730> 595 595 100 (daemon) MyCrashingApp <25870f37b79d36e584a2e7c6db2717f5> 176783 176783 100 [per-process-limit] (frontmost) (resume) ptpd <606d697050af3b23a54e4d75eafef6c0> 605 605 200 (daemon) identityservices <1695cbd72da83c4c87c568bd53a01d24> 442 442 200 (daemon) wifid <c0ed3dbc8d7f329489a04faf460c027c> 411 411 200 (daemon) syslogd <88667a0c3dc6398e9b1c6a0c5a5d8f24> 187 187 200 (daemon) powerd <1a8551a962783aa9899be0e55a9c1e58> 152 152 200 (daemon) locationd <3480b01585f039ca9c45ecc16928d8b0> 1139 1139 200 (daemon) imagent <5a1a726d45e033f2bea34c3ae04e817c> 300 300 200 (daemon) dataaccessd <ae41b26410e3338ba33e337fb5439069> 1131 1131 100 (daemon) apsd <f96e01aab90637b0822aff105bf78d70> 578 578 200 (daemon) mediaserverd <6c2cee9548813cea95bf5548d3411408> 1087 1087 100 (daemon) iaptransportd <009cdd0e53bf34829b6a8b69e0ca49bf> 260 260 200 (daemon) mDNSResponder <090a345fd6e13f52b156a3eb9a0e78ee> 220 220 100 (daemon) sharingd <63eae5785eac326987c89d771258ebf8> 571 571 200 (daemon) SpringBoard <ccb584e84f2f3005a9c20897fdb783dd> 6419 6419 100 backboardd <3085386f5f99357aa9f055e0fb79b827> 181876 181876 100 [per-process-limit] (daemon) fseventsd <8b8df4c7b46b3dcfb4e1b1d8a6cbb686> 1203 1203 50 (daemon) lockdownd <6bdd33b3920236808292915812d386c8> 344 344 50 (daemon) wirelessproxd <41e0cf822ff33124b3c3949cedce7fd2> 196 196 50 (daemon) configd <2123dc8c1e103375aec0905809a8d38e> 646 646 50 (daemon) aggregated <178824f7adc231249e9e341c03c36855> 590 590 100 (daemon) fairplayd.A2 <9948545906083ff9962c310943eb34de> 148 148 100 (daemon) BTServer <5540f7e4ecd535b9a48b50258130dbd1> 404 404 100 (daemon) distnoted <a237d6a85cae3c409b914ccb8e5b63f1> 182 182 100 (daemon) UserEventAgent <f9cb9c166628392a9d190acff16950b9> 995 995 100 (daemon) filecoordination <4d26113e2e3d3b21832eb866679edf38> 251 251 200 (daemon) itunescloudd <266cb30204a039d5b2f5aba30cf05015> 1044 1044 100 (daemon) DTPower <79ced86c61333b6aaa2460276eb0b8eb> 282 282 200 (daemon) ubd <b54681e3319e36b48148ab2026ebf542> 655 655 200 (daemon) eapolclient <a5ac733ff23936b4ab05dde3fd5fb17b> 173 173 50 (daemon) afcd <208713527dc0315a9198e99db64d3cf1> 134 134 200 (daemon) notification_pro <293150329f1d317c99a6c5fa2e25963a> 140 140 200 (daemon) DTMobileIS <100bfdacf0a63ae9ab08b27669042812> 2292 2292 200 (daemon) LeakAgent <30856ea2089a3263aaf27fd9faee406d> 3520 3520 100 (daemon) networkd <7262086478d63812ae40c561e8e1acbf> 509 509 200 (daemon) WirelessCoexMana <1e096a90f671399d975e83beb668eb91> 151 151 100 (daemon) touchsetupd <9d37501e59f13ca1b1577435bdb43a9f> 197 197 200 (daemon) CommCenter <e5c6b5b1f64833de93bd22bbe135c9b6> 1196 1196 100 (daemon) notifyd <1d555aa3d08c336294a38d9c134dca00> 319 319 100 (daemon) **End** I can't see any hint where the problem lies. The app crashes when I push a new view controller on the navigation stack. On this view controller there is a full screen label. The error also happens after opening and closing the view controller 40 times or so. Similar questions have different hints: * *Too much memory from OS requested *Too many animations/didn't queue animations *Use instruments *Memory warning So the memory management problem is the most likely one. I tried to use Instruments, but Leaks didn't give me some useful hints (only some malloc and auto release pool with 48 kB max. - seems a OS bug). Also Zombies and Activity Monitor aren't helpful. Using Instruments makes everything really slow. Only with allocations I saw the UILabel subclass is taking too much space. Every time the new view controller is created, the memory increases by 10 MB (persistent bytes) and that is only the label! Too make things more complex I'm using Xamarin.iOS. The garbage collector isn't deallocating the view controller when it popped off the navigation controller. But it does it at some time. I think when the system needs more space (nothing left) than the GC kicks in. I could reproduce this behavior in a simple project with my big sized label. Why does the garbage collector doesn't kick in? I get memory warnings but I can't release something. Normally the view controller and its subviews should get deallocated when they are unloaded from the navigation controller. When I know why my app is crashing I can do something against this. How can I debug this issue? Edit: Now I tried to crash the app on an iPhone. Here you can find the debugger output and here the device log. Again it seems that I'm running out of memory. But my only hint is still the label, because none of the tools can tell me exactly where the problem lies. A: I made the following steps to reduce the memory pressure: * *used separate class for my custom EventArgs (before: in view controller) *no anonymous function for button in UINavigationBar *no anonymous funciton for UIActionSheet *rewrote EventHandler in that way that I subscribe to them in viewWillAppear and unsubscribe in viewWillDisappear (most of the time) *added Target for UIGestureRecognizer in viewWillAppear and removed it in viewWillDisappear *removed cycle between view controller and datasource through using a WeakReference I made some checks and it now seems to work. For testing if a view controller is deallocated or not use this: protected override void Dispose (bool disposing) { Console.WriteLine (String.Format ("{0} controller disposed - {1}", this.GetType (), this.GetHashCode ())); base.Dispose (disposing); } Through this and commenting the things out I were able to detect the reference cycles. I hope I fixed all problems. The main problems were the EventHandler. For solving my issue the following questions belong to it: * *Clicked handler not executed for UIButton in UIBarButtonItem *How to break reference cycle between view controller and data source *Through presenting new view controller viewWillDisappear on parent is triggered where I unsubscribe from the events *RemoveTarget from UITapGestureRecognizer *Add/remove EventHandler for UIBarButtonItem The following links were helpful in resolving the memory issue: * *Memory and Performance Best Practices *Is this a bug in MonoTouch GC? *Memory Management Pitfalls in Xamarin iOS - Introduction + Part 1 + Part 2 *Weak Event Pattern in MonoTouch *iOS Memory Managment by Rodrigo Kumpera (Xamarin) *My App Crashed, Now What? – Part 1 + Part 2 *signal
{ "language": "en", "url": "https://stackoverflow.com/questions/32053817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Post form to void controller action without getting redirected afterwards This is my view from which I'm posting the form: @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id="frmRegister", @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary("", new { @class = "text-danger" }) <div class="col-md-8"> @Html.TextBoxFor(x => x.Username, new { @class = "form-control form-input", placeholder = "ID" }) @Html.ValidationMessageFor(m => m.Username, "", new { @class = "text-danger" }) </div> <div class="col-md-8"> @Html.TextBoxFor(x => x.Mail, new { @class = "form-control form-input", placeholder = "Mail" }) @Html.ValidationMessageFor(m => m.Mail, "", new { @class = "text-danger" }) </div> <div class="col-md-8"> @Html.PasswordFor(x => x.Password, new { @class = "form-control form-input", placeholder = "Parolă" }) @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" }) </div> <div class="col-md-8"> @Html.PasswordFor(x => x.ConfirmPassword, new { @class = "form-control form-input", placeholder = "Confirmă parola" }) @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "text-danger" }) </div> <input type="submit" id="btnGetConfCodeView" onclick="ShowConfCodeInput()" style="margin-top: 7px; margin-bottom: -5px" value="Fă-l!" class="btn btn-info" /> <input type="button" id="btnCloseRegister" style="margin-top: 7px; margin-bottom: -5px" value="Las'" class="btn btn-default" /> } And I'm using the action to store the inputted data: [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public void Register(RegisterViewModel viewModel) { if (ModelState.IsValid) { var user = new User { Username = viewModel.Username, Mail = viewModel.Mail, Password = viewModel.Password, MemberSince = DateTime.Now }; Session["currentUser"] = user; } } And after this action executes, I get redirected to /Account/Register path. I want this to not happen, is it possible? A: It is going to show you blank screen with the url Account/Register since you are returning void from your HttpPost action method. Ideally, you should be doing the PRG pattern. POST - REDIRECT-GET * *The form is displayed that asks the user for some input. *When the user submits the form, the code does some business logic/transaction (Save some thing to db etc). After successfully doing that, Send a 302 response to browser. *The 302 response tells the browser to issue a totally new GET request to the url provided by the server.In MVC, We can use RedirectToAction method to send the 302 response to the browser. So your code will be [HttpPost] public void Register(RegisterViewModel viewModel) { if (ModelState.IsValid) { // to do :Save return RedirectToAction("SuccesfullyRegistered","Account"); } return View(viewModel); } So when user submits the form, we will save the user and send a 302 response to the browser and browser will issue a request to Account/SuccessfullyRegistered action method. The PRG pattern prevents the duplicate form submission issue when user reloads the new view. A: Based upon your comment, you should use Ajax Helper or jquery to submit your form via ajax. Working with Ajax Helper in ASP.NET MVC is a good tutorial of using Ajax Helper and there are lots of questions in stackoverflow about using jquery to submit a form. It's up to you to employ one of them. It seems that Ajax Helper is more easier to use. A: If you really want to fire and forget the POST request of a form submit, then you can add an invisible iframe and let the target attribute of your form point to that iframe. Then the content of the reply to the POST will land there and the user won't see it since the iframe is hidden. Your iframe definition could look like this: <iframe id="nulframe" name="nulframe" style="width:0;height:0;border:0; border:none;" /> and you would add the target attribute to the first line of your code like this: @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id="frmRegister", @class = "form-horizontal", role = "form", target = "nulframe" })) You could even handle the load event of the iframe to get signalled when the POST is completed.
{ "language": "en", "url": "https://stackoverflow.com/questions/34252185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: strategy pattern implementation with differing return classes I have a MessageProcessor class which processes xml messages of different types. A switch statement (C#) based on the message type calls the appropriate method to parse the xml and extract the data required for the type of message. I would rather have a number of parser classes, one of which will be injected into the MessageProcessor when it is created based on the message type. Switch replaced with polymorphism - so far so good. However, the problem I have is that the current parser methods each return different results, e.g. ParseExecute(xml, out Session), ParseCallback(xml, out id, out name, ...) Is it possible to do what I want to do in this scenario? A: Just a suggestion. Had you think about create a base result class and derive all different result types from it? Doing in that way you can think in use polymorphism to re-interpret the result to the concrete type. But as I don't know your design in depth this can add some extra complexity for you. At least hope it can give some inspiration :) A: Switch also could be replaced with ChainOfResonsibility A: Some kind of factory pattern maybe public class ParserFactory { public static IParser Create(string type) { IParser parser; switch (type) { case "1": parser = new Parser1(); break; case "2": parser = new Parser2(); break; default: throw new ArgumentOutOfRangeException("type"); } return parser; } } And return objects that implements an interface as well public class Parser1 : IParser { public IParseResult Parse(string xml) { //Set values return result; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/1985289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to load MobileNet weights with an input tensor in Keras I'm trying to apply transfer learning to MNIST using MobileNet weights in Keras. Keras documentation to use MobileNet https://keras.io/applications/#mobilenet Mobilenet accepts 224x224x3 as input but MNIST is 28x28x1. I'm creating a Lambda layer which can convert 28x28x1 image into 224x224x3 and send it as input to MobileNet. The following code causes TypeError: Input layers to a Model must be InputLayer objects. Received inputs: Tensor("lambda_2/ResizeNearestNeighbor:0", shape=(?, 224, 224, 3), dtype=float32). Input 0 (0-based) originates from layer type Lambda. height = 28 width = 28 input_image = Input(shape=(height,width,1)) def resize_image_to_inception(x): x = K.repeat_elements(x, 3, axis=3) x = K.resize_images(x, 8, 8, data_format="channels_last") return x input_image_ = Lambda(resize_image_to_inception, output_shape=(224, 224, 3))(input_image) print(type(input_image_)) base_model = MobileNet(input_tensor=input_image_, weights='imagenet', include_top=False)
{ "language": "en", "url": "https://stackoverflow.com/questions/47862788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Segue using didSelectRowAtIndexPath I have a Master-Detail VC setup for a Core Data project. If the searchBar is active, one set of results is displayed, if it's not active, the objects from the fetchedResultsController displays in the MasterVC. I had been trying to segue using prepareForSegue, but I my instructor suggested I use didSelectRowAtIndexPath to do the segue. override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var selectedNote: Note // Check to see which table view cell was selected. if tableView == self.tableView { selectedNote = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Note // <--this is "everything" } else { // need this to unwrap the optional if let filteredObjects = filteredObjects { selectedNote = filteredObjects[indexPath.row] } } // Set up the detail view controller to show. let detailViewController = DetailViewController() detailViewController.detailDescriptionLabel = selectedNote.valueForKey("noteBody") as! UILabel // Note: Should not be necessary but current iOS 8.0 bug requires it. tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: false) // original code navigationController?.pushViewController(detailViewController, animated: true) } I'm getting this compiler error: Variable 'selectedNote' used before being initialized--it's declared at the top of the method! If I add "self" before selectedNote like so: detailViewController.detailDescriptionLabel = self.selectedNote.valueForKey("noteBody") as! UILabel 'MasterViewController' does not have a member named 'selectedNote' despite being there. So I'm obviously mucking up something. I put a breakpoint in before let detailViewController = DetailViewController() and in lldb it's printing out the right object. I've looked around here for a solution, but I'm coming up short. I can't find applicable code that works on GitHub. class Note: NSManagedObject { @NSManaged var dateCreated: NSDate @NSManaged var dateEdited: NSDate @NSManaged var noteTitle: String @NSManaged var noteBody: String } Any ideas how to pass the selectedNote's properties forward to the detailViewController? Update: Based on the responses I've gotten, I've shut up the compiler warnings with this code: override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var selectedNote: Note? // Check to see which table view cell was selected. if tableView == self.tableView { selectedNote = self.fetchedResultsController.objectAtIndexPath(indexPath) as? Note // <--this is "everything" } else { // need this to unwrap the optional if let filteredObjects = filteredObjects { selectedNote = filteredObjects[indexPath.row] } } // Set up the detail view controller to show. let detailViewController = DetailViewController() detailViewController.detailDescriptionLabel.text = (selectedNote!.valueForKey("noteBody") as! String) // Note: Should not be necessary but current iOS 8.0 bug requires it. tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: false) // original code navigationController?.pushViewController(detailViewController, animated: true) } But I'm getting this in the console when it crashes: There are already notes in the app fatal error: unexpectedly found nil while unwrapping an Optional value However, when I type po selectedObject the object I clicked displays in the console. A: You need to declare selectedNote as optional like this: var selectedNote: Note? And later check if value exist before using it. if let note = selectedNote { // Set up the detail view controller to show. let detailViewController = DetailViewController() detailViewController.detailDescriptionLabel = note.valueForKey("noteBody") as! UILabel // Note: Should not be necessary but current iOS 8.0 bug requires it. tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: false) // original code navigationController?.pushViewController(detailViewController, animated: true) } Update: The problem is that you are trying to create DetailViewController let detailViewController = DetailViewController() But what you need instead is to have reference to the DetailViewController in order to pass information to it. So you can create segue from Master to Detail controller in Interface builder. Then remove logic from didSelectRowAtIndexPath override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Note: Should not be necessary but current iOS 8.0 bug requires it. tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: false) } And implement it in prepareForSegue method: override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let cell = sender as? UITableViewCell { let indexPath = tableView.indexPathForCell(cell)! var selectedNote: Note? if filteredObjects?.count > 0 { selectedNote = filteredObjects![indexPath.row] }else { selectedNote = self.fetchedResultsController.objectAtIndexPath(indexPath) as? Note // <--this is "everything" } if let note = selectedNote { let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = note } } } } showDetail - segue identifier which you need to setup in IB. var detailItem: AnyObject? - you need to declare it in DetailViewController.
{ "language": "en", "url": "https://stackoverflow.com/questions/28797044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting InvalidConnectionAttributeException when trying to do a Database Connection I am getting InvalidConnectionAttributeException when trying to obtain a database connection. import java.sql.*; public class JdbcTest { public static void main (String[] args) throws SQLException { Connection con= null; Statement st= null; ResultSet rs= null; try { // get connection to database con= DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "st", "st"); System.out.println("Connection has created successfuly !"); // create a statement st= con.createStatement(); // Execute sql query rs= st.executeQuery("SELECT * FROM demo.employees;"); // process the result set while (rs.next()) { System.out.println(rs.getString("last_name")+", "+rs.getString("first_name")); } con.close(); } catch (Exception exc){ exc.printStackTrace(); } } } That's the output of my program: at java.sql.DriverManager.getConnection(Unknown Source) at JdbcTest.main(JdbcTest.java:15) Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Maroc' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2243) at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2267) at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319) at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ... 6 more Could someone tells me what the problem is, please? Thanks. A: The server time zone 'Maroc' that is being used is invalid. To see what value it is set to use SELECT @@global.time_zone; Try to set the whichever Time Zone by default-time-zone in the file my.cnf For eg: default-time-zone='+00:00' To set it for current session do: SET time_zone = timezonename;
{ "language": "en", "url": "https://stackoverflow.com/questions/55994808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cache OAuth2 tokens in SpringBoot application? I am implementing a Spring Boot application, in which the methods are calling third party REST endpoints. This REST API is accessible after OAuth2 authentication. That is why I retrieve tokens from the third party (various users can use my application and respectfully call the REST endpoints) and use these tokens for authorization in order to call the endpoints. But in the current implementation this happens before every call. That is why I would like to ask for advice how to cache these tokens and whether this is a good practice at all? Also the tokens expire in 1 hour. A: You should not cache access tokens on the backend of a web application ,if you can store them client side and send them with each request. In case you don't have possibility to store it at client side (possible case your API is talking to some message client like USSD,SMS etc),It will be expensive to get an OAuth access token, because it requires an HTTP request to the token endpoint. This case is a good example where you can cache tokens whenever possible. You can make use of REDIS if you have multiple instances. REMEMBER : Tokens are sensitive data, because they grant access to a user's resources. (Moreover, unlike a user's password, you can't just store a hash of the token.) Therefore, it's critical to protect tokens from being compromised. You can make use of encryption.Do check below links for more details : https://auth0.com/docs/best-practices/token-best-practices. https://github.com/auth0/express-openid-connect/blob/master/EXAMPLES.md#5-obtaining-and-storing-access-tokens-to-call-external-apis https://learn.microsoft.com/en-us/azure/architecture/multitenant-identity/token-cache As per Auth0 Token Best Practices Store and reuse. Reduce unnecessary roundtrips that extend your application's attack surface, and optimize plan token limits (where applicable) by storing access tokens obtained from the authorization server. Rather than requesting a new token, use the stored token during future calls until it expires. How you store tokens will depend on the characteristics of your application: typical solutions include databases (for apps that need to perform API calls regardless of the presence of a session) and HTTP sessions (for apps that have an activity window limited to an interactive session). For an example of server-side storage and token reuse, see Obtaining and Storing Access Tokens to Call External APIs in our Github repo
{ "language": "en", "url": "https://stackoverflow.com/questions/58119997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: didSelectRowAtIndexPath when is it being called So I am trying to make an app where you click a cell in a list of cells on the uitableview and it opens a cooresponding PDF file. To do this i want to pass the title of the cell in between to seperate classes. I have one class called "IndianaSpecificLawsView" that manages the UITableCells and this is the code for it - (id)initWithStyle:(UITableViewStyle)style { self = [super initWithStyle:style]; if (self) { // Custom initialization } return self; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; NSString* cellTitle = [[cell textLabel] text]; NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; NSLog(@" (Pt1 Cell Title == %@",cellTitle); // saving an NSString [prefs setObject:@"cellTitle" forKey:@"cellTitle_String"]; [[NSUserDefaults standardUserDefaults] synchronize]; } - (void)viewDidLoad { [super viewDidLoad]; // Uncomment the following line to preserve selection between presentations. // self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } And I am trying to use NSUserDefuaults to pass it but when i put in the NSLog to test it the NSLog is never getting printed. Do i need to call this method? I assumed it was being called when i pressed the button but it is not. Thanks! A: Change your viewDidLoad method and set UITableView's data source and delegate: - (void)viewDidLoad { [super viewDidLoad]; self.tableView.dataSource = self; self.tableView.delegate = self; } And implement UITableViewDataSource and UITableViewDelegate protocols.
{ "language": "en", "url": "https://stackoverflow.com/questions/21960552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Populate each value from a text file into a text box in a html using selenium My Requirement is as below: I have a web application which has Client search page(html). I have a list of Client numbers in a file. I want to pass first Client number from the file into a text box in the web url and click on submit button and wait for 10 sec to open the account details page. Once the account details page opens it should submit the return submit button from the account details page which route to account search page. Once it comes to account search page, the next value should get passed from the file and the process should follow until all the values are populated from the text file. What is the best way of doing and can I get the code for this? A: Use FileReader to access the lines of the file. while (line) { clientSearchPage(); } Use element.sendKeys(line) to input the data to the text-boxes Use explicit waits: WebDriverWait and ExpectedConditions.elementToBeClickable(element) / (ExpectedCondition<Boolean>) driver -> element.isDisplayed() instead of Thread.sleep() Make an attempt yourself before asking on SO, nobody is gonna do your job for you
{ "language": "en", "url": "https://stackoverflow.com/questions/65640165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passport-jwt token verification strategy never called I want to use passport-jwt to create my own strategy. According to several tutorial, i tried the following : // auth.js const passport = require("passport"); const passportJWT = require("passport-jwt"); const _ = require("lodash"); const users = require("./users.js"); const cfg = require("./config.js"); const ExtractJwt = passportJWT.ExtractJwt; const JwtStrategy = passportJWT.Strategy; var params = { secretOrKey: cfg.jwtSecret, //ignoreExpiration: false, jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), //passReqToCallback: false, jsonWebTokenOptions: { maxAge: "3 days" } }; module.exports = function () { var strategy = new JwtStrategy(params, function (payload, done) { console.log('payload received', payload); // Just check in array is user is on it var user = users[_.findIndex(users, { id: payload.id })]; if (user) { return done(null, { id: user.id, name: user.name, scope: user.scope }); } else { console.log("Echec : redirection") return done(new Error("User not found"), null); } }); passport.use(strategy); return { initialize: function () { return passport.initialize(); }, authenticate: function () { return passport.authenticate("jwt", cfg.jwtSession); } }; } // index.js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const auth = require("./auth.js")(); const jwt = require("jsonwebtoken") const users = require("./users.js"); const cfg = require("./config.js"); const moment = require("moment") const _ = require("lodash"); moment.locale("fr-FR"); var port = process.env.PORT || settings.port || 3000; app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(auth.initialize()); app.post('/authenticate', function (req, res) { if (req.body.user && req.body.password) { var user = users[_.findIndex(users, { user: req.body.user })]; if (user) { res.set("Authorization", "Bearer " + jwt.sign({ id: user.id, name: user.name, exp: Math.round(moment.duration(moment().add(3, 'days').diff(moment())).asSeconds()) }, cfg.jwtSecret)) res.json({ id: user.id, name: user.name, type: "Success" }); } else { res.sendStatus(401); } } else { res.sendStatus(401); } }) app.get('/', auth.authenticate(), function (req, res) { res.render('trend', {}); }) app.get('/login', function (req, res) { res.send("Login page") }) app.listen(port, function () { console.log(`Example app listening on port ${port}`); }) I'm able to generate a JWT and to set it in header as a Bearer token, by calling "/authenticate". But now, i'm stuck for the token validation. When i call "/", i'm first not able to debug my function, because nothing appear, even not a console log (so it's like the authentication strategy is never called, none of my multiple console.log is outputted) and it return me "Unauthorized" I found something that would answer me here : passport jwt verify callback not called So i tried by replacing bearer to jwt, and i successfully got the token in params.jwtFromRequest. But still stuck for the strategy. And unfortunatelly, the link in the linked question is dead... Any suggestions ?
{ "language": "en", "url": "https://stackoverflow.com/questions/47080576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vuejs v-for remove element I have code like : <div id="files"> <div v-for="(file, key) in data.files" v-bind:id="key"> @{{ file }} <span v-on:click="removeFile(key)"> <button>X</button> </span> <button v-on:click="addFiles()">Add Files</button> </div> </div> File js methods: { removeFile(key) { var elem = document.getElementById("#" + key); elem.parentNode.removeChild(elem); return false; } When i clicked button, selected file had been deleted as well but it also returned error like: Uncaught TypeError: Cannot read property 'parentNode' of null I tried this way but same problem: file had been removed, with error var parent = document.getElementById("files"); var child = document.getElementById("#" + key); parent.removeChild(child); Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. Any idea? Thanks so much! A: Replace the content of your removeFile() method with this: (given that the files variable is an array) methods: { removeFile(key) { this.files.splice(key, 1); } You can also use the Vue helper for removing items in an array or a property in an object: methods: { removeFile(key) { this.$delete(this.files, key); }
{ "language": "en", "url": "https://stackoverflow.com/questions/50808837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jq validation get all errors For example I have form with 'firstname' field. I added two rules to this field (number, required). But when I submit form I see just one error. How I can see list of errors ('This field is required.' and 'Please enter a valid number.') ? .error { font: normal 10px arial; padding: 3px; margin: 3px; background-color: #ffc; border: 1px solid #c00; } body{font-size:x-large;background:#CCC;} h1{margin-bottom:20px;} form{padding:50px;} $(document).ready(function(){ $("#form").validate({ rules: { 'firstname': { number: true, required: true, }, } });}); <form id='form' name='form' method='post' action=''><p> <input type='text' name='firstname' id='firstname'/></p> <input type='submit' name='Submit' value='Submit'/></p> </form> http://jsfiddle.net/4tcsjwah/398/ A: pretty sure this will work, change it to meet your requirements though. var messages = { email: { required:"Email is required field. Please enter valid email address", email:"Please enter valid email address", } }; $(function(){ $("#test-form").validate({ onfocusout:false, onkeyup:false, messages:messages }); }); Visit this JS Fiddle: http://jsfiddle.net/JcFYr/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/53695354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 502 BAD Gateway | ingress nginx with cert-manager I am using nginx ingress v1.1.3 in azure AKS v1.21. My traffic is getting terminated at nginx ingress for all other domains and it is working as expected. Recently I added cert-manager to manage certificate, but when implemented i am getting 502 for this particular ingress and same is working if i use my custom certificate. Here's my ingress configuration : apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: new-dns namespace: application-production annotations: kubernetes.io/ingress.class: "nginx" nginx.ingress.kubernetes.io/auth-tls-verify-client: "off" nginx.ingress.kubernetes.io/ssl-passthrough: "false" cert-manager.io/cluster-issuer: "letsencrypt" nginx.ingress.kubernetes.io/connection-proxy-header: upgrade nginx.ingress.kubernetes.io/http2-push-preload: "true" nginx.ingress.kubernetes.io/proxy-http-version: "1.1" nginx.ingress.kubernetes.io/ssl-prefer-server-ciphers: "true" spec: tls: - hosts: - xxx-xxxxxx.com secretName: new-dns rules: - host: xxx-xxx.com http: paths: - pathType: Prefix path: / backend: service: name: my-backend port: number: 8080 Logs of nginx when configuration applied I0507 02:25:05.236731 7 admission.go:149] processed ingress via admission controller {testedIngressLength:11 testedIngressTime:0.076s renderingIngressLength:11 renderingIngressTime:0.001s admissionTime:1.2MBs testedConfigurationSize:0.077} I0507 02:25:05.236761 7 main.go:100] "successfully validated configuration, accepting" ingress="application-production/anew-dns" I0507 02:25:05.258742 7 store.go:427] "Found valid IngressClass" ingress="application-production/anew-dns" ingressclass="nginx" I0507 02:25:05.259236 7 event.go:282] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"application-production", Name:"anew-dns", UID:"a95d83e7-51ad-472d-a5a2-5f4cc6352e81", APIVersion:"networking.k8s.io/v1", ResourceVersion:"137003252", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync I0507 02:25:05.260169 7 controller.go:159] "Configuration changes detected, backend reload required" I0507 02:25:05.418604 7 controller.go:176] "Backend successfully reloaded" I0507 02:25:05.418745 7 event.go:282] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-756f546d89-69xnq", UID:"bdc7b594-4070-465c-b7a9-afc846e3e7a9", APIVersion:"v1", ResourceVersion:"136713253", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration I0507 02:25:22.295245 7 event.go:282] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"application-production", Name:"anew-dns", UID:"a95d83e7-51ad-472d-a5a2-5f4cc6352e81", APIVersion:"networking.k8s.io/v1", ResourceVersion:"137003343", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync Error after sometime 2022/05/07 02:03:44 [error] 12307#12307: *4399339 upstream prematurely closed connection while reading response header from upstream, client: xx.xx.xx.xx, server: xxxx.xxxx.xxx, request: "GET / HTTP/2.0", upstream: "http:/xx.xx.xx.xx:8080/", host: "xxxx.xxxx.xxxx" A: I found out that ingress and cert manager is setup correctly there was issue in my backend. Since LetsEncrypt root cert is expired and I am calling axios which is giving invalid cert hence no response was returned to nginx ingress. Solution: Upgrade openssl version to 1.1.0 or later.
{ "language": "en", "url": "https://stackoverflow.com/questions/72149182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ViGEm.NET namespace missing when using Unity? [this question has the unity3d tag and I can't change it to unity2d] I was trying to use ViGEm using this tutorial to help me. But when I was writing the code, a red underline appeared on using Nefarius.ViGEm.Client; It said: The type or namespace 'Nefarius' could not be found. (are you missing a using directive or an assembly reference?) How do I make this work with Unity? I have carefully done every step of the tutorial. A: These steps fixed it: * *Go to the nuget website and download the package. *Extract the file as a .zip file. *Go inside the lib folder and copy the .dll file to [Unity Project]\Assets\Plugins (create the folder if it doesn't exist)
{ "language": "en", "url": "https://stackoverflow.com/questions/64923193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xml get width and set to android:height <LinearLayout android:layout_width="match_parent" android:layout_height=" " android:orientation="vertical" > Here's the thing, lets say i have this LinearLayout that has a width of match_parent, so the width of the LinearLayout depends on the width of the device. What i dont know is how could i set the android:layout_height=" " value to correspond on the value of the android:layout_width="match_parent" so i could have a Square LinearLayout i know i can do this using LayoutParams but is there a way to do it on xml? Thank you guys.. A: First get screen width Display mDisplay = activity.getWindowManager().getDefaultDisplay(); int width = mDisplay.getWidth(); int height = mDisplay.getHeight(); Set Size to Layout LinearLayout layout = (LinearLayout)findViewById(R.id.LayoutID); // Gets the layout params that will allow you to resize the layout LayoutParams params = layout.getLayoutParams(); // Changes the height and width to the specified *pixels* params.height = width; params.width = width; layout.setLayoutParams(params); In XML: <LinearLayout android:layout_width="0dp" android:layout_height="0dp" android:id="@+id/LayoutID" android:orientation="vertical" >
{ "language": "en", "url": "https://stackoverflow.com/questions/20438705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Failed to run test cases : cannot test target on simulator Cannot test target “FrameworkToolKitTests” on “iPhone 13 Pro Max” architectures: x86_64 Domain: XCTHTestRunSpecificationErrorDomain Code: 2 Using Xcode13.2.1 / testing framework code ,but testing not started Note: set (Enable testability : true )
{ "language": "en", "url": "https://stackoverflow.com/questions/74122033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React Native code stopped working all of a sudden I am dealing with a very strange problem. My React Native code was working fine till yesterday. I was trying to import FB data (User ID, Profile Pic etc) and was successfully able to see the FB User ID on my app till yesterday. All of a sudden I can't see it anymore.. I get the following log when I use expo start and just a blank screen on my phone. I have tried clearing cache and updating expo-cli as well.. Any pointers will be highly appreciated. Running application on Redmi 6 Pro. Warning: componentWillMount has been renamed, and is not recommended for use. See fb.me/react-unsafe-component-lifecycles for details. * Move code with side effects to componentDidMount, and set initial state in the constructor. * Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder. Please update the following components: %s, Login - node_modules\react-native\Libraries\LogBox\LogBox.js:117:10 in registerWarning - node_modules\react-native\Libraries\LogBox\LogBox.js:63:8 in warnImpl - node_modules\react-native\Libraries\LogBox\LogBox.js:36:4 in console.warn - node_modules\expo\build\environment\react-native-logs.fx.js:18:4 in warn - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:106:4 in printWarning - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:60:16 in warn - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5846:10 in ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:19093:6 in flushRenderPhaseStrictModeWarningsInDEV - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18335:41 in commitRootImpl * [native code]:null in commitRootImpl - node_modules\scheduler\cjs\scheduler.development.js:653:23 in unstable_runWithPriority - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18317:17 in commitRoot - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17697:12 in performSyncWorkOnRoot * [native code]:null in performSyncWorkOnRoot - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5321:31 in runWithPriority$argument_1 - node_modules\scheduler\cjs\scheduler.development.js:653:23 in unstable_runWithPriority - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5316:21 in flushSyncCallbackQueueImpl - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5304:28 in flushSyncCallbackQueue - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17125:30 in scheduleUpdateOnFiber - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:20527:14 in updateContainer - node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:21068:17 in render - node_modules\react-native\Libraries\ReactNative\renderApplication.js:54:4 in renderApplication - node_modules\react-native\Libraries\ReactNative\AppRegistry.js:117:25 in runnables.appKey.run - node_modules\react-native\Libraries\ReactNative\AppRegistry.js:213:4 in runApplication - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0 - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue * [native code]:null in callFunctionReturnFlushedQueue Best, Nitin
{ "language": "en", "url": "https://stackoverflow.com/questions/65085103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode: Impossible to use c++ with Scenekit? I'm a beginner with Xcode... I'm trying to use openCV c++ with Scenekit=> to make an AR scene. Well, I was too optimistic. 1/I started to use the default XCode template for game.=> works! 2/openCV without scenekit=> works 3/ mixing... I imported some c++ headers in the gameviewController file (basically a UIViewController with scenekit inside). If I let it so, I get compiler error (cstddef not defined). Fair enough, it's C++ so, from what I read, I just have to rename .m to .mm But, in this case, I get a full list of linker errors such as Undefined symbols for architecture arm64: "_OBJC_CLASS_$_SCNAction", referenced from: => I guess it is more tricky to mix objective C and C++ but on a simpler project, without Scenekit but with a very similar code otherwise, it worked nicely. Any clue or guide for mixing them? Should I use swift? Thanks a lot, Michael A: I just need to add "SceneKit.framework" to Link Binary With Libraries: A: Same problem here. I had a pure Objective-C class, simply named "GameViewController.m". To turn it into an Obj-C++ class, change the ".m" to ".mm". However, just by changing the extension, the linker spat back 13 undefined symbols.... "_OBJC_CLASS_$_SCNTransaction", referenced from: ... "_OBJC_CLASS_$_SCNFloor", referenced from: ... "_OBJC_CLASS_$_SCNMaterial", referenced from: ... etc... To get around this, just create a different (new) Obj-C++ class, with a .mm extension, and place your C++ code in that class. Now you can instantiate that new class from the class containing SceneKit calls and call the methods in the new Obj-C++ class. Inside the GameViewcontroller.m class: ... scene = [SCNScene sceneNamed:@"art.scnassets/grid.dae"]; kinematics = [[KinematicScene alloc] init]; [kinematics setupCharacters]; ... And inside the new Obj-C++ class (KinematicsScene.mm) @implementation KinematicScene { AI::Location *location; } -(id) init { self = [super init]; if( self ) { AI::KinematicSeek* seek = new AI::KinematicSeek[2]; location = new AI::Location[2]; } return self; } -(void) setupCharacters { ..... } ... etc .... @end A: This worked for me: * *Disable module support [CLANG_ENABLE_MODULES, -fmodules]. This has user experience downsides. Read the online help for this setting before disabling it, and also be aware that if you disable it you will become responsible for hunting down the libraries and frameworks you need to link against, and this can be tedious if you are not an old hand. *Build and (attempt to) link. Add the frameworks and libraries you need to resolve the link errors. I recommend creating a group in your project and directing it to your SDK, then adding the frameworks and libraries relative to that SDK.
{ "language": "en", "url": "https://stackoverflow.com/questions/29097946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Login to Dropbox with vbscript I found a script on here to login to a forum that someone made and I edited it to login to Dropbox, but it still isn't working for me. I am looking for the script to uncheck the "remember me" checkbox and login to Dropbox from a vbs file that I execute on brand new machines. Here is what I have so far: Call Main Function Main Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_") IE.Visible = True IE.Navigate "dropbox.com/login" Wait IE With IE.Document .getElementByID("login_email").value = "mypassword" .getElementByID("login_password").value = "myemail" .getElementByID("remember_me").checked = "unchecked" .getElementsByName("frmLogin")(0).Submit End With End Function Sub Wait(IE) Do WScript.Sleep 500 Loop While IE.ReadyState < 4 And IE.Busy End Sub I changed the ID's that it "gets" in order to set the username and password, but the "frmLogin" I am unsure of. A: Consider the below example having nodes accessibility extended checks and using .click method instead of .submit, since the last one leads to 403 error page for me: Option Explicit Dim objIE, strMsg DropBoxLogin objIE, strMsg MsgBox strMsg Sub DropBoxLogin(objIE, strMsg) Set objIE = CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate "https://www.dropbox.com/login" Wait objIE If Not IsNull(objIE.Document.getElementById("header-account-menu")) Then strMsg = "Already logged in" Else WaitElementById objIE, "regular-login-forms" With objIE.Document.getElementsByClassName("login-form")(0) .item("login_email").value = "mymail@mydomain.com" .item("login_password").value = "mypassword" .item("remember_me").checked = False .getElementsByTagName("button")(0).click End With WaitElementById objIE, "header-account-menu" Wait objIE strMsg = "Log in completed" End If End Sub Sub Wait(objIE) Do While objIE.ReadyState < 4 Or objIE.Busy WScript.Sleep 10 Loop Do Until objIE.Document.readyState = "complete" WScript.Sleep 10 Loop End Sub Sub WaitElementById(objIE, strId) Do While IsNull(objIE.Document.getElementById(strId)) WScript.Sleep 10 Loop End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/37191755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reverse button click event with jquery I created a button that allows adding a geojson file to my map once we click on it. However, I would like to be able to have a hide/show option when pressing on the button. I mean when I click on it I would like my geojson to appear on my map and once a click a second time I would like it to disappear. However until now each time I press my button a new layer is added to the map... here is the basic code: I tried with toggle() but did not change... const button_canton = $("#Limite_cantonales").click(function() { $.getJSON("canton.geojson", function(data) { var limite_canton = L.geoJSON(data, { onEachFeature: function onEachFeature(feature, layer) { layer.bindPopup('<strong>' + feature.properties.NAME); } }).addTo(myMap); $("#button_canton").toggle(); }); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div id="info" class="info"> <button id="Limite_CH">Frontières nationales</button> </div> A: To HIDE the button, remove the $("#") and just do button_canton.toggle(); To TOGGLE the map try this - it only makes the map once const $myMap = $("#myMap"); $("#Limite_cantonales").click(function() { if ($myMap.children()) $myMap.toggle() else { $.getJSON("canton.geojson", function(data) { $myMap.show() var limite_canton = L.geoJSON(data, { onEachFeature: function onEachFeature(feature, layer) { layer.bindPopup('<strong>' + feature.properties.NAME); } }).addTo($myMap); }); } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div id="info" class="info"> <button id="Limite_CH">Frontières nationales</button> </div> <div id="myMap" hidden></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/70511764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF CallBack implementation Im having hard time to understand the advantages of callback on the basic way of making our client to be a service too and our service to be a client too. A: I can give you one big advantage. We have an application that involves a client (WPF) and a Windows service. Normally the client calls the service (via WCF) to retrieve and/or save data etc. But, there are times we want the service to send the client a message, to notify the client it needs to perform a certain action (like shutdown or display a message to the user - could be anything). A callback is perfect for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/10367648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: How to split the row in apache POI header I am trying to create table ind Microsoft Word using apache poi. But I am not being able to generate the header attached for the table. Any suggestions, i can create the attached header using apache poi? I am able to created the entire table but the last 2 columns which are appearing (merge and split), i need to do in java. For the merging for the columns i have used the below code: //merging horizontally by setting grid span instead of using CTHMerge static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) { XWPFTableCell cell = table.getRow(row).getCell(fromCol); // Try getting the TcPr. Not simply setting an new one every time. CTTcPr tcPr = cell.getCTTc().getTcPr(); if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr(); // The first merged cell has grid span property set if (tcPr.isSetGridSpan()) { tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1)); } else { tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1)); } // Cells which join (merge) the first one, must be removed for (int colIndex = toCol; colIndex > fromCol; colIndex--) { table.getRow(row).getCtRow().removeTc(colIndex); table.getRow(row).removeCell(colIndex); } } A: First creating a table having less rows and/or columns and then splitting single cells definitely is not the way to go. Instead create the table having as much rows and/or columns as maximum needed. Merging is simpler than splitting. According to your screen shots the table needs 4 rows and 9 columns. The following complete example creates exactly the table of your screen shots: import java.io.File; import java.io.FileOutputStream; import java.math.BigInteger; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge; public class CreateWordTableMerge3 { static void mergeCellVertically(XWPFTable table, int col, int fromRow, int toRow) { for(int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) { XWPFTableCell cell = table.getRow(rowIndex).getCell(col); CTVMerge vmerge = CTVMerge.Factory.newInstance(); if(rowIndex == fromRow){ // The first merged cell is set with RESTART merge value vmerge.setVal(STMerge.RESTART); } else { // Cells which join (merge) the first one, are set with CONTINUE vmerge.setVal(STMerge.CONTINUE); // and the content should be removed for (int i = cell.getParagraphs().size(); i > 0; i--) { cell.removeParagraph(0); } cell.addParagraph(); } // Try getting the TcPr. Not simply setting an new one every time. CTTcPr tcPr = cell.getCTTc().getTcPr(); if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr(); tcPr.setVMerge(vmerge); } } //merging horizontally by setting grid span instead of using CTHMerge static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) { XWPFTableCell cell = table.getRow(row).getCell(fromCol); // Try getting the TcPr. Not simply setting an new one every time. CTTcPr tcPr = cell.getCTTc().getTcPr(); if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr(); // The first merged cell has grid span property set if (tcPr.isSetGridSpan()) { tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol-fromCol+1)); } else { tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol-fromCol+1)); } // Cells which join (merge) the first one, must be removed for(int colIndex = toCol; colIndex > fromCol; colIndex--) { table.getRow(row).getCtRow().removeTc(colIndex); table.getRow(row).removeCell(colIndex); } } static void setColumnWidth(XWPFTable table, int row, int col, int width) { CTTblWidth tblWidth = CTTblWidth.Factory.newInstance(); tblWidth.setW(BigInteger.valueOf(width)); tblWidth.setType(STTblWidth.DXA); CTTcPr tcPr = table.getRow(row).getCell(col).getCTTc().getTcPr(); if (tcPr != null) { tcPr.setTcW(tblWidth); } else { tcPr = CTTcPr.Factory.newInstance(); tcPr.setTcW(tblWidth); table.getRow(row).getCell(col).getCTTc().setTcPr(tcPr); } } public static void main(String[] args) throws Exception { XWPFDocument document= new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run=paragraph.createRun(); run.setText("The table:"); //create table //4 rows 9 columns XWPFTable table = document.createTable(4,9); for (int row = 0; row < 4; row++) { for (int col = 0; col < 9; col++) { //table.getRow(row).getCell(col).setText("row " + row + ", col " + col); if (row < 3) table.getRow(row).getCell(col).setColor("D9D9D9"); } } //defining the column widths for the grid //column width values are in unit twentieths of a point (1/1440 of an inch) int defaultColWidth = 1*1440*6/9; // 9 columns fits to 6 inches int[] colunmWidths = new int[] { defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth }; //create CTTblGrid for this table with widths of the 8 columns. //necessary for Libreoffice/Openoffice to accept the column widths. //first column table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[0])); //other columns for (int col = 1; col < colunmWidths.length; col++) { table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[col])); } //using the merge methods and setting the column widths //horizontally merge all columns in first row mergeCellHorizontally(table, 0, 0, 8); setColumnWidth(table, 0, 0, colunmWidths[0]+colunmWidths[1]+colunmWidths[2]+colunmWidths[3] +colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]+colunmWidths[8]); //horizontally merge last two columns in second row mergeCellHorizontally(table, 1, 7, 8); setColumnWidth(table, 1, 7, colunmWidths[7]+colunmWidths[7]); //vertically merge row 2 and 3 in column 1 to 7 for (int c = 0; c < 7; c++) { mergeCellVertically(table, c, 1, 2); } paragraph = document.createParagraph(); FileOutputStream out = new FileOutputStream("create_table.docx"); document.write(out); out.close(); } } Result:
{ "language": "en", "url": "https://stackoverflow.com/questions/58510514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split string to maximum length and append the rest to the last array item Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item? So, for example I have 'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"] I would like to output ["Billy", "Bob Joe"] Is there a way for this to be easily done in JavaScript? A: You can use splice and join like: function customSplit(str, splitter, max) { let res = str.split(splitter); if(max < res.length) res.push(res.splice(max - 1).join(splitter)); return res; } console.log(customSplit('Billy Bob Joe', ' ', 2)); console.log(customSplit('a b c d e f g h', ' ', 4)); A: Try something like this (run code snippet to see result): var base_str = 'Billy Bob Joe whatever'; //try here limit 1 , 2, 3 and see console.log result var base_split = base_str.split(' ',2); var second_str = base_split.join(' '); var second_split = base_str.split(second_str); base_split.push(second_split[1].trim()); console.log(base_split); A: Here is what I came up with, but it's not super optimized function explode(del, str, limit) { let items = str.split(del), r = [] for(let i = 0; i < limit - 1; i++){ r.push(items.shift()) } r.push(items.join(' ')) return r } console.log(explode(' ', 'Billy Bob Joe', 2)); console.log(explode(' ', 'a b c d e f g h', 4)); A: You can create a function that will create a regex string matching the number of words passed as an argument. const buildRegexString = function(numWords) { let regexStr = '^' for (let i = 1; i < numWords; i++) { regexStr += '(\\S+)\\s'; } regexStr += '(.*)'; return regexStr; } const input = 'Billy Bob Joe Ringo George'; const regex = new RegExp(buildRegexString(3)); const match = input.match(regex); const result = match.slice(1); console.log(result); A: I think you can't do that using split function you can use var str = "Billy Bob Joe"; var res = str.split(" ",1); str=str.replace(res,''); Now str have Bob Joe
{ "language": "en", "url": "https://stackoverflow.com/questions/44914080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Modify every two largest elements of matrix rows and columns In python, I have a matrix and I want to find the two largest elements in every row and every column and change their values to 1 (seperately, I mean get two matrices where one of them modified the rows and the other modified the cols). The main goal is to get a corresponding matrix with zeros everywhere except those ones I've put in the 2 largest element of each row and column (using np.where(mat == 1, 1, 0). I'm trying to use the np.argpartition in order to do so but without success. Please help. See image below. A: Here's an approach with np.argpartition - idx_row = np.argpartition(-a,2,axis=1)[:,:2] out_row = np.zeros(a.shape,dtype=int) out_row[np.arange(idx_row.shape[0])[:,None],idx_row] = 1 idx_col = np.argpartition(-a,2,axis=0)[:2] out_col = np.zeros(a.shape,dtype=int) out_col[idx_col,np.arange(idx_col.shape[1])] = 1 Sample input, output - In [40]: a Out[40]: array([[ 3, 7, 1, -5, 14, 2, 8], [ 5, 8, 1, 4, -3, 3, 10], [11, 3, 5, 1, 9, 2, 5], [ 6, 4, 12, 6, 1, 15, 4], [ 8, 2, 0, 1, -2, 3, 5]]) In [41]: out_row Out[41]: array([[0, 0, 0, 0, 1, 0, 1], [0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1]]) In [42]: out_col Out[42]: array([[0, 1, 0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0]]) Alternatively, if you are into compact codes, we can skip the initialization and use broadcasting to get the outputs from idx_row and idx_col directly, like so - out_row = (idx_row[...,None] == np.arange(a.shape[1])).any(1).astype(int) out_col = (idx_col[...,None] == np.arange(a.shape[0])).any(0).astype(int).T
{ "language": "en", "url": "https://stackoverflow.com/questions/41661362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Scroll Carousel, Default Tab Controller & GridView as one in flutter I have a design like this. What I want is that as I scroll up the GridView the Carousel scrolls up and the tab controller stays at the top fixed. All of this should be done in one scroll. I have done this before with custom scroll and sliver GridView but I have no idea as to how I can also add a Default Tab controller in the custom scrollView and make it stay fixed at the top. Thanks for your help :) A: I tried below code hope it solves your problem.... You can also play with this code at DartPad NestedScrollView NestedScrollView( physics: ClampingScrollPhysics(), headerSliverBuilder: (context, value) { return [ SliverToBoxAdapter( /// _buildCarousel() in your case.... child: Container( height: 200, child: Center( child: Text("Your Carousel will be here"), ) ), ), SliverToBoxAdapter( child: TabBar( labelColor: Colors.blue, unselectedLabelColor: Colors.black, controller: tb, tabs: <Widget>[ Tab(child: Text("tab1"),), Tab(child: Text("tab2"),) ], ) ), ]; }, body: TabBarView( controller: tb, children: <Widget>[ GridView.count( physics: NeverScrollableScrollPhysics(), crossAxisCount: 3, children: List.generate(10, (index) => Icon(Icons.grid_off) ).toList() ), GridView.count( physics: NeverScrollableScrollPhysics(), crossAxisCount: 3, children: List.generate(5, (index) => Icon(Icons.grid_on) ).toList() ), ], ), ) A: See this DartPad for running ex. PinnedAppBar_SliverAppBar_NestedScrollView NestedScrollView( controller: ScrollController(), physics: ClampingScrollPhysics(), headerSliverBuilder: (context, value) { return [ SliverAppBar( pinned: true, backgroundColor: Colors.white, flexibleSpace: FlexibleSpaceBar( background: /// _buildCarousel() in your case.... Container( height: 200, child: Center( child: Text("Your Carousel will be here"), ) ), ), expandedHeight: 250.0, /// your Carousel + Tabbar height(50) floating: true, bottom: TabBar( labelColor: Colors.blue, unselectedLabelColor: Colors.black, controller: tb, tabs: <Widget>[ Tab(child: Text("tab1"),), Tab(child: Text("tab2"),) ], ), ), ]; }, body: TabBarView( controller: tb, children: <Widget>[ GridView.count( crossAxisCount: 3, children: List.generate(10, (index) => Icon(Icons.grid_off) ).toList() ), GridView.count( crossAxisCount: 3, children: List.generate(5, (index) => Icon(Icons.grid_on) ).toList() ), ], ), )
{ "language": "en", "url": "https://stackoverflow.com/questions/63096568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need some help writing an EMPTY_OR macro I'm trying to code a macro called EMPTY_OR, which will return the first argument, but if it's empty, it will return the second one. Here's what I have so far: #include <iostream> #define EMPTY_OR(x, y) ( (sizeof(#x) > sizeof("")) ? (x) : (y) ) #define TEST(x, y) EMPTY_OR(y, x) using namespace std; int main() { int four = TEST(4, ); int eight = TEST(4, 8); cout << "four: " << four << endl; cout << "eight: " << eight << endl; return 0; } It's close, but it doesn't work because the first line of the main function expands to the following: ( (sizeof("") > sizeof("")) ? () : (4) ) The condition is never true, so () is never evaluated. I shouldn't care about it, but the compiler does, and it shows an error. How can I solve it with the most straightforward and standard-compliant (or at least MSVC-compliant) way? A: If I'm understanding what you're trying to do correctly, I'd remove the sizeof and just check if the first character in the string is \0; #define EMPTY_OR(x, y) ( #x[0] ? (x+0) : (y) ) A: Here's a solution adapted from this article and without Boost that works on anything that I can think of that you can pass: #define CAT(a, b) CAT_(a, b) #define CAT_(a, b) a##b #define IF(cond, t, f) CAT(IF_, cond)(t, f) #define IF_1(t, f) t #define IF_0(t, f) f #define COMMA(x) , #define ARG3(a, b, c, ...) c #define HAS_COMMA(x) ARG3(x, 1, 0,) #define EMPTY(x) EMPTY_(HAS_COMMA(COMMA x ())) #define EMPTY_(x) HAS_COMMA(CAT(EMPTY_, x)) #define EMPTY_1 , #define EMPTY_OR(x, y) IF(EMPTY(x), y, x) #define TEST(x, y) EMPTY_OR(y, x) #include <iostream> using namespace std; int main() { int t = TEST(1==, ) 1; int f = TEST(1==, 0==) 1; cout << "t: " << t << endl; cout << "f: " << f << endl; return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/23043371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Collapsing columns in a table without jquery by click and by url for our intranet i've to do a large table with lots of columns. As there are many columns, i want to be able to hide some "blocks" of columns for better overview. The columns have two headings, one as kind of grouping for the "Progress step" and one under it with details for each step. I found several solutions but the problem is that it is required to hide each group/step by click, but it should be also possible to have predefined views like a short overview, detailed view, maybe reachable by a url? Currently the table heading looks like: <table> <thead> <colgroup> <col> <col> <col> <col span='11' class='step0'> <col span='2' class='step1'> <col span='3' class='step2'> <col span='3' class='step3'> <col span='3' class='step4'> </colgroup> <tr> <th rowspan='2'>ID</th> <th rowspan='2'>Name</th> <th rowspan='2'>State</th> <th colspan='11'>Step 0</th> <th colspan='2'>Step 1</th> <th colspan='3'>Step 2</th> <th colspan='3'>Step 3</th> <th colspan='3'>Step 4</th> </tr> <tr> <th>Step 0 - Info 1</th> <th>Step 0 - Info 2</th> <th>Step 0 - Info 3</th> <th>Step 0 - Info 4</th> <th>Step 0 - Info 5</th> <th>Step 0 - Info 6</th> <th>Step 0 - Info 7</th> <th>Step 0 - Info 8</th> <th>Step 0 - Info 9</th> <th>Step 0 - User+Date</th> <th>Step 0 - Notes</th> <th>Step 1 - User+Date</th> <th>Step 1 - Notes</th> <th>Step 2 - Info</th> <th>Step 2 - User+Date</th> <th>Step 2 - Notes</th> <th>Step 3 - Info</th> <th>Step 3 - User+Date</a></th> <th>Step 3 - Notes</th> <th>Step 4 - Info</th> <th>Step 4 - User+Date</th> <th>Step 4 - Notes</th> </tr> </thead> </table> As i never used jquery (and can't even code JS besides a bit modification of existing scripts, i'd prefer a solution without jquery. If it is much easier with jquery, i'd have a look. Maybe one column of each group should stay visible, but that could be achieved by modifying the colgroup :) Thanks in advance! A: jQuery is kind of obsolete, if you don’t need to support quite old platforms. So you’re right in searching for a non-jQuery solution. It’s not necessary to code JS yourself, as there are plenty of libraries out there that you can use for such purposes. Usually they come in so called packages, which can be installed by means of the node package manager (npm). Learning how to integrate npm can be quite long, so you can also download libraries (aka scripts) that you might find on the web. It’s important that the download includes all dependencies. You will need to ask yourself some questions, though, to be able to choose the right library/script: * *What is the UI pattern that you want to use? This will determine your search keyword * *Collapse column-groups into one column? This is called a collapse pattern, I would recommend it due to it’s intuitiveness. *Have a checklist on your site to hide the step completely from the table? *Should the solution be accessible to users with situational, temporary or permanent disabilities? Include the keyword accessible or a11y in your search * *The minimum should be keyboard support *What platforms need to be supported (browser version and operating system)? *Is there already another JavaScript framework used in the intranet, like jQuery or other? * *You would either like to look for a library that integrates well, *or one that uses “vanilla” JavaScript, so no framework at all *Are you using a build system, into which the library should integrate? Ask the architects, if you don’t know *How much of your solution would you be willing to replace by a library? * *There are Data Grid libraries out there that offer your functionality, but will build the whole table based on JavaScript, instead of simply adding functionality *or would you like to apply progressive enhancement, meaning you’re simply adding functionality on top of a already fully usable table? (I’d recommend that) *Which licenses do you accept? There are different open source licenses, that allow you manipulating code or not, and might oblige you to publish any changes you make Finally, the library will need a mapping between the toggle and the columns to hide somewhere. It can be done in JavaScript only, but I would recommend to use a library that makes use of HTML attributes instead, so that you don’t need to write JavaScript. If the library is specialised in tables, it might use the already present colspan attributes to do the mapping. Otherwise, you might have to provide the mapping with data- attributes. So, your search might be like “Accessible collapsible column groups javascript”. Example with Bootstrap Here is an example based on Bootstrap’s Collapse Component. Bootstrap is a framework and supports accessibility. Some particularities concerning accessibility in tables might be missing. Note that you cannot hide cells directly, if you keep the grouping header visible, since the table’s structure would fall apart. If you go for the checklist solution instead of a collapse pattern, you could use the same component, and reference all cells (including those with colspan) in the data-bs-target attribute. … <thead> <tr> <th> Step 0 - Info 1 <button class="btn btn-light" data-bs-toggle="collapse" data-bs-target=".cell-col-0" aria-expanded="false">Toggle</button> </th> … <th> Step 1 - User+Date <button class="btn btn-light" data-bs-toggle="collapse" data-bs-target=".cell-col-1" aria-expanded="false">Toggle</button> </th> … </tr> … <tr> <th><div class="cell-col-0">Step 0 - Info 1</div></th> … <th><div class="cell-col-1">Step 1 - User+Date</div></th> … </tr> </thead> <tbody> <tr> <td><div class="cell-col-0">Step 0 - Info 1 - Row 1</div></td> … <td><div class="cell-col-1">Step 1 - User+Date - Row 1</div></td> … A: There is no need to use an unwieldy library. Plain "Vanilla" JavaScript will do. The following lines of code will make a col within a colgroup disappear, when you deselect its corresponding checkbox on top of the table: /* // =========================================================== // un-comment this section when you run this from your PHP server: <?PHP $hidden = array(0,2); // hide steps 0 and 2 ?> const hidden=<?PHP echo json_encode($hidden); ?>; // ============================================================*/ // stackoverflow mockup of PHP input: const hidden=[0,2]; const cols = document.querySelectorAll("table col:nth-child(n+4)"), ttls= [...document.querySelectorAll("table tr.ttl th:nth-child(n+4)")].map(t=>t.textContent), div = document.querySelector("div"); div.innerHTML=ttls.map(t=>`<label><input type="checkbox" checked>${t}</label>`).join(" "); const cbs = div.querySelectorAll("input[type=checkbox]"); hidden.forEach(h=>{cols[h].classList.add("hidden");cbs[h].checked=false}); cbs.forEach((cb,i)=>{ cb.addEventListener("change",ev=>cols[i].classList.toggle("hidden",!cb.checked)) }); // enter a few lines of data into the table ... (to make it look more impressive) document.getElementById("tbd").innerHTML = [...Array(5)].map((_, i) => `<tr>${[...Array(25)].map((_,j)=> `<td>${(i+1)*100+j}</td>`).join("")}</tr>`).join("\n"); td, th { border: 1px solid grey } .hidden { visibility: collapse } <div></div> <table> <thead> <colgroup> <col> <col> <col> <col span='11' class='step0'> <col span='2' class='step1'> <col span='3' class='step2'> <col span='3' class='step3'> <col span='3' class='step4'> </colgroup> <tr class="ttl"> <th rowspan='2'>ID</th> <th rowspan='2'>Name</th> <th rowspan='2'>State</th> <th colspan='11'>Step 0</th> <th colspan='2'>Step 1</th> <th colspan='3'>Step 2</th> <th colspan='3'>Step 3</th> <th colspan='3'>Step 4</th> </tr> <tr> <th>Step 0 - Info 1</th> <th>Step 0 - Info 2</th> <th>Step 0 - Info 3</th> <th>Step 0 - Info 4</th> <th>Step 0 - Info 5</th> <th>Step 0 - Info 6</th> <th>Step 0 - Info 7</th> <th>Step 0 - Info 8</th> <th>Step 0 - Info 9</th> <th>Step 0 - User+Date</th> <th>Step 0 - Notes</th> <th>Step 1 - User+Date</th> <th>Step 1 - Notes</th> <th>Step 2 - Info</th> <th>Step 2 - User+Date</th> <th>Step 2 - Notes</th> <th>Step 3 - Info</th> <th>Step 3 - User+Date</th> <th>Step 3 - Notes</th> <th>Step 4 - Info</th> <th>Step 4 - User+Date</th> <th>Step 4 - Notes</th> </tr> </thead> <tbody id="tbd"></tbody> </table> I am not sure whether this will work on all browsers, but I tested it successfully on Chrome, Edge and Firefox.
{ "language": "en", "url": "https://stackoverflow.com/questions/71926527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Using foldl to calculate the product sum Basically, I wish to calculate a list with the algorithm as below: myList = [a1, a2, a3, ... a8] -- all elements are Int result = a[n] * n (where n is index starting from 0) result = a1*0 + a2*1 + a3*2 .... + a8*7 The below code works. prodSum xs = helper 0 xs where helper a (x:xs) = let a' = (a + 1) in a * x + helper a' xs helper a _ = 0 However, I was asked to implement it using foldl, and I tried but did not make it. Can anyone suggest a solution? A: To do this with just foldl, we need to consider what state we need to keep while traversing the list. In this case, we need the index of the current item (which starts at 0) and the current sum (which also starts at 0). We can store both of them in a tuple. On every step, we add the current index multiplied by current value to the sum, and increment the index by 1. After the foldl is done, we can discard the index and return the sum. Prelude> prodSum = fst . foldl (\(sum, i) x -> (sum + x * i, i + 1)) (0, 0) Prelude> prodSum [1..2] 2 Prelude> prodSum [1..5] 40 Prelude> prodSum [1..8] 168
{ "language": "en", "url": "https://stackoverflow.com/questions/72500121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to replace part of tensorflow codes with a saved model I was wondering if someone can show me how to replace part of a big model with an (already) saved small model in Tensorflow. Precisely, what I want is, in the below, to make the f(x) with y=g(x) in part. The y=g(x) is the already trained, saved model, and I wanted to train f(x) without chaining g(x). def f(x): .... y = g(x) z = tf.matmul(y, w) + b return z And I will declare the f(x) twice like with tf.variable_scope("foo"): z1 = f(x1) with tf.variable_scope("bar", reuse=True): z2 = f(x2) Any comment is appreciated. A: Do something like y = tf.stop_gradient(g(x)) and load the weights of g from a checkpoint by creating your own saver and passing the list of g's variables to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/48087828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting properties transport and path for socket.io I'm trying to create the socket connection with the backend over the socket.io library. Thing is - I need to turn off the long-polling option and set the custom path. But I can't set them both because always work only one option. So, if I try this way, I'm setting the path, but not transports: this.socket = io( 'wss://some-url.com', { path: '/v1/url/to/websockets' }, { transports: [ 'websocket' ] } ); And library is trying to make the long-polling connection that will be rejected by the server (which I don't have access to), but path will be correct. But if I'm trying to change the order and set the transports property first, library will omit the path property and frontend will send the request to the wss://some-url.com/socket.io/?EIO=3&transport=websocket url, which is incorrect. I understand that it is some conflict because of the fact that transport property changes the URL (it sets itself as the query param), but what I don't understand - how can I set the path and transports properties because I need them so bad. Didn't find the solution on the official docs and here. Any ideas? A: Your synatx is wrong, correct syntax this.socket = io( 'wss://some-url.com', { path :'/v1/url/to/websockets', transports: ['websocket'] }); i.e. both should be within same object
{ "language": "en", "url": "https://stackoverflow.com/questions/46796141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Uppercase the names of multiple files in a directory in Python I'm working on a small project that requires that I use Python to uppercase all the names of files in a certain directory "ex: input: Brandy.jpg , output: BRANDY.jpg". The thing is I've never done on multiple files before, what I've done was the following: universe = os.listdir('parallel_universe/') universe = [os.path.splitext(x)[0].upper() for x in universe] But what I've done capitalized the names in the list only but not the files in the directory itself, the output was like the following: ['ADAM SANDLER','ANGELINA JULIE','ARIANA GRANDE','BEN AFFLECK','BEN STILLER','BILL GATES', 'BRAD PITT','BRITNEY SPEARS','BRUCE LEE','CAMERON DIAZ','DWAYNE JOHNSON','ELON MUSK','ELTON JOHN','JACK BLACK','JACKIE CHAN','JAMIE FOXX','JASON SEGEL', 'JASON STATHAM'] What am I missing here? And since I don't have much experience in Python, I'd love if your answers include explanations for each step, and thanks in advance. A: Right now, you are converting the strings to uppercase, but that's it. There is no actual renaming being done. In order to rename, you need to use os.rename If you were to wrap your code with os.rename, it should solve your problem, like so: [os.rename("parallel_universe/" + x, "parallel_universe/" + os.path.splitext(x)[0].upper() + os.path.splitext(x)[1]) for x in universe] I have removed the assignment universe= because this line no longer returns a list and you will instead get a bunch on None objects. Docs for os.rename: https://docs.python.org/3/library/os.html#os.rename
{ "language": "en", "url": "https://stackoverflow.com/questions/72037049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to check if a particular word from a string list contains in a string, but it should not be between any other words? I need to check if any string from a string list matches wholly (whole word search) within the input string i.e. it should not match the word in between characters. e.g. check the code below: String input = "i was hoping the number"; String[] valid = new String[] { "nip", "pin" }; if (Arrays.stream(valid).anyMatch(input::contains)) { System.out.println("valid"); } My output is valid, which is not correct. It is fetching the pin string from the hoping word. I should be able to match only if the pin word is separate. A: Do it as follows: import java.util.Arrays; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "i was hoping the number"; String[] valid = new String[] { "nip", "pin" }; if (Arrays.stream(valid).anyMatch(p -> Pattern.compile("\\b" + p + "\\b").matcher(input).find())) { System.out.println("valid"); } } } Note that \b is used for word boundary which I have added before and after the matching words to create word boundary for them. Some more tests: import java.util.Arrays; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String[] testStrings = { "i was hoping the number", "my pin is 123", "the word, turnip ends with nip", "turnip is a vegetable" }; String[] valid = new String[] { "nip", "pin" }; for (String input : testStrings) { if (Arrays.stream(valid).anyMatch(p -> Pattern.compile("\\b" + p + "\\b").matcher(input).find())) { System.out.println(input + " => " + "valid"); } else { System.out.println(input + " => " + "invalid"); } } } } Output: i was hoping the number => invalid my pin is 123 => valid the word, turnip ends with nip => valid turnip is a vegetable => invalid Solution without using Stream API: import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "i was hoping the number"; String[] valid = new String[] { "nip", "pin" }; for (String toBeMatched : valid) { if (Pattern.compile("\\b" + toBeMatched + "\\b").matcher(input).find()) { System.out.println("valid"); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/64184827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing Long Functions With a "data" Argument I'm aware of how to write short functions using a data argument (How to handle "data" argument in a function?) - you can just copy and paste the body of the function and use an if-else statement to run the function depending on whether or not an argument is provided for the "data" argument. I have a much longer function, and I don't want to copy and paste the entire thing and use an if statement and change the code throughout the entire function. For example: df <- data.frame(x = c(1:5), y = c(4:8), z = c(5:1)) my_fxn <- function(x, y, z, data) { aaa <- x ^ 2 + 5 bbb <- (y * log(y) + 5) ^ 7 ccc <- z + aaa ddd <- mean(c(x, y, z)) eee <- aaa + bbb + ccc + ddd paste(eee, "my_fxn", eee, sep = "_") } my_fxn(df$x, df$y, df$z) > my_fxn(df$x, df$y, df$z) [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" "240475836.750078_my_fxn_240475836.750078" [4] "776392986.326892_my_fxn_776392986.326892" "2219080769.50416_my_fxn_2219080769.50416" How can I concisely write a line (or a few lines) of code at the beginning of my_fxn to allow me to use the following line of code to generate the same answer from my_fxn? my_fxn(x, y, z, data = df) Update: I think my real problem is that the names of the data frame and the columns in the data frame do not match the names of the function's arguments. Why doesn't the following code work? df <- data.frame(x = c(1:5), y = c(6:10), z = LETTERS[1:5]) my_fxn <- function (aaa, bbb, ccc, data) { if (!missing(data)) { aaa = as.numeric(data$aaa) bbb = as.numeric(data$bbb) ccc = as.character(data$ccc) } print(aaa[1]) } my_fxn(x, y, z, df) A: Why would you need to copy and paste the entire function? Wouldn't you just use the same methods as in the SO thread you linked. ie just have a section of the code at the top specifying that x, y and z are equal to data df <- data.frame(x = c(1:5), y = c(4:8), z = c(5:1)) my_fxn <- function(x, y, z, data) { if(missing(data)){ x = x; y = y; z = z # unnecessary but just to be explicit } else { x = data$x y = data$y z = data$z } aaa <- x ^ 2 + 5 bbb <- (y * log(y) + 5) ^ 7 ccc <- z + aaa ddd <- mean(c(x, y, z)) eee <- aaa + bbb + ccc + ddd paste(eee, "my_fxn", eee, sep = "_") } my_fxn(df$x, df$y, df$z) [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" "240475836.750078_my_fxn_240475836.750078" "776392986.326892_my_fxn_776392986.326892" [5] "2219080769.50416_my_fxn_2219080769.50416" > my_fxn(x, y, z, data = df) [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" "240475836.750078_my_fxn_240475836.750078" "776392986.326892_my_fxn_776392986.326892" [5] "2219080769.50416_my_fxn_2219080769.50416" So on your update you are attempting to to assign aaa = as.numeric(data$aaa) bbb = as.numeric(data$bbb) ccc = as.character(data$ccc) Where data$aaa would be data$x and data$bbb would be data$y. The issue here is that there is no reason why the x column would be associated with aaa which is why in my previous answer I used x, y, z. in your case, the function will look for df$aaa which doesn't presently exist. In order to generalize this the way you want so that you do not need to know the column names and hard code them into the function, You might try my_fxn <- function (aaa, bbb, ccc, data) { if (!missing(data)) { aaa = as.numeric(data[,1]) bbb = as.numeric(data[,2]) ccc = as.character(data[,3]) } print(aaa[1]) } my_fxn(x, y, z, df) A: Easiest fix would be passing the column names as character to the function and modify the function so it gets the values from the dataframe columns. df <- data.frame(x = c(1:5), y = c(4:8), z = c(5:1)) my_fxn <- function(xx, yy, zz, data) { if(missing(data)){ x = xx; y = yy; z = zz } else { x <- data[[xx]] y <- data[[yy]] z <- data[[zz]] } aaa <- x ^ 2 + 5 bbb <- (y * log(y) + 5) ^ 7 ccc <- z + aaa ddd <- mean(c(x, y, z)) eee <- aaa + bbb + ccc + ddd paste(eee, "my_fxn", eee, sep = "_") } my_fxn("x", "y", "z", data = df) # [1] "14500329.5724518_my_fxn_14500329.5724518" "64360436.579237_my_fxn_64360436.579237" # [3] "240475836.750078_my_fxn_240475836.750078" "776392986.326892_my_fxn_776392986.326892" # [5] "2219080769.50416_my_fxn_2219080769.50416"
{ "language": "en", "url": "https://stackoverflow.com/questions/55896203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to monitor growth of On Premise Azure Devops Server We have our on-premise Azure DevOps Server that is growing quite fast. The database files (SQL Server 14) were about 130 GB. In less than a month are now 160 GB. There's an agent monitor (maybe an Azure DevOps extension?) to log mostly Azure DevOps operations that may cause this? Not only push etc. standard GIT operation but something more specific? We have several repositories, pipelines, artifacts, etc. Edit: auditing on Azure DevOps Services isn't available for on-premises deployments. And more there are several 3rd part providers offering this service but again seems like they work only in the cloud. What eventually I'm looking for is a way to know the memory occupancy of a single Team Project or its pipeline/release etc. Then it will be easy to check day after day who is growing so rapidly. A: * *You can check the Azure DevOps server growth using continuous monitoring by application insights *You can set the alert rules using the below sample CLI script To modify alert rule settings: In the left pane of the release pipeline page, select Configure Application Insights Alerts. $subscription = az account show --query "id";$subscription.Trim("`"");$resource="/subscriptions/$subscription/resourcegroups/"+"$(Parameters.AppInsightsResourceGroupName)"+"/providers/microsoft.insights/components/" + "$(Parameters.ApplicationInsightsResourceName)"; az monitor metrics alert create -n 'Availability_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'avg availabilityResults/availabilityPercentage < 99' --description "created from Azure DevOps"; az monitor metrics alert create -n 'FailedRequests_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'count requests/failed > 5' --description "created from Azure DevOps"; az monitor metrics alert create -n 'ServerResponseTime_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'avg requests/duration > 5' --description "created from Azure DevOps"; az monitor metrics alert create -n 'ServerExceptions_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'count exceptions/server > 5' --description "created from Azure DevOps"; * *You can modify the script and add additional rules, and you can even modify alert conditions. or you can even remove alert rules which you don't require
{ "language": "en", "url": "https://stackoverflow.com/questions/71438249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Global access vs. local variables I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. Now, my question is that if I should just create them as global variables and access them anywhere in the code (in side of single class) or I should create them as local variables and pass them as parameters to other functions. I just want to see what would be the best programming practice. I am using C#. Thanks. A: In general you should avoid global variables. If it will be practical, I recommend keeping them as locals and passing them as parameters to your functions. As Josh pointed out, if these variables are only used inside a single instance of the class, then you should just make them private (or protected) members of that class and be done with it. Of course, then they could only be passed in as parameters to other methods with the same access level (IE, private). Alternatively, you may consider using the Singleton Design Pattern, which is slightly cleaner (and preferable) to using globals. A: If the scope of the objects is the lifetime of the class they are instantiated in, then they should be private member variables. If they do not maintain state themselves, then you should make them static classes. You should still pass them around as variables, or at least create property accessors to get at the backing field. This way you can change implementation details without blowing up your code. SOLID design principles are a good place to start when thinking about these things. A: I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. This sounds like a perfect time to use a private static readonly variable. These can be initialized in their declaration, or you can make a static constructor to initialize them. The fact that you are only referencing these objects within a single class is key point. There are other better ways to do things if these objects are ever needed outside of the single class. A: If the objects will be the same for every instance of the class then static const double PI = 3.14158; A: You should generally use accessor methods (e.g. getters and setters) and keep your internal variables private. This way the rest of your code, outside of your class, is not dependent on your actual variables. See this tutorial. A: If your class is dependent on these 2 objects then they should probably be members on the class itself. Something like this (where A is the class you are talking about and B is one of the objects you initialize: public class A { private B _b; public A(B b) { _b = b; } public void DoSomething() { //do something with _b; } private void DoSomethingElse() { //do something else with _b; } } In this example A is dependent on B (so you pass your instance of B into A's constructor or through some Dependency Injection framework). It wouldn't make a lot of sense for every method on class A to need a parameter of type B to be passed to it. A: I think in this case you should ask what makes more sense. Is there some kind of relationship between the 2 objects and the new class. Also, how often are they used in the class. Generally, If only a couple of methods use the objects, pass them around otherwise, instantiate them as class level variables (possibly using private static readonly as Jefferey suggests) and use them in the class. Making the code more readable should be your goal here.
{ "language": "en", "url": "https://stackoverflow.com/questions/2508797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to create this custom ANN using tensorflow? I am trying to create this custom ANN using tensorflow. Here is image of the toy network and code. import tensorflow as tf import numpy as np in = np.array([1, 2, 3, 4], , dtype="float32") y_true = np.array([10, 11], , dtype="float32") # w is vector of weights # y_pred = np.array([in[0]*w[0]+in[1]*w[0]], [in[2]*w[1]+in[3]*w[1]] ) # y_pred1 = 1 / (1 + tf.math.exp(-y_pred)) # sigmoid activation function def loss_fun(y_true, y_pred1): loss1 = tf.reduce_sum(tf.pow(y_pred1 - y_true, 2)) # model.compile(loss=loss_fun, optimizer='adam', metrics=['accuracy']) The output of this network goes to another ANN to the right and I know that stuff, but don't know how can I create the connections, update the w, y_pred, and compile the model. Any help? A: Something like this ought to work import tensorflow as tf import numpy as np def y_pred(x, w): return [x[0]*w[0]+x[1]*w[0], x[2]*w[1]+x[3]*w[1]] def loss_fun(y_true, y_pred): return tf.reduce_sum(tf.pow(y_pred - y_true, 2)) x = np.array([1, 2, 3, 4], dtype="float32") y_true = np.array([10, 11], dtype="float32") w = tf.Variable(initial_value=np.random.normal(size=(2)), name='weights', dtype=tf.float32) xt = tf.convert_to_tensor(x) yt = tf.convert_to_tensor(y_true) sgd_opt = tf.optimizers.SGD() training_steps = 100 display_steps = 10 for step in range(training_steps): with tf.GradientTape() as tape: tape.watch(w) yp = y_pred(xt, w) loss = loss_fun(yt, yp) dl_dw = tape.gradient(loss, w) sgd_opt.apply_gradients(zip([dl_dw], [w])) if step % display_steps == 0: print(loss, w)
{ "language": "en", "url": "https://stackoverflow.com/questions/69527333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Member turns to undefined I've developed a jQuery plugin which has default options: $.fn.incromentor.defaults = { max : 65355, min : 0 }; In the initialization of the plugin, I merge the user options with plugin default options using $.extend function init( $elm, options ) { this.$element = $elm; this.options = $.extend( {}, $.fn.incromentor.defaults, options ); } So the problem is, if user sets minor max to 0, that property turns to undefined! Why is this and how can I store a simple 0? Here a jsFiddle: http://jsfiddle.net/KDXa6/2/ Edit After linting the code in JSLint, the error dissapeared so I suspect there was an obscure error in my typing. A: $.fn.incromentor.defaults = {} will overwrite your default options, so something else such as more_text, less_text is turned to undefined. Your Users should pass their options into the constructor such as $('#myel').Incrementor({ max : 65355, min : 0}); -- $this to $(this) http://jsfiddle.net/KDXa6/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/11376784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: @volatile usage unclear - sending an object with a `var` to another thread I am not sure I use @volatile correctly here. I have a buffer, like this: final class BufD(val buf: Array[Double], @volatile var size: Int) Which is sent between processes, whereby it might cross thread boundaries. The sender may update the size field just before sending it out. Therefore I want to make sure that the receiver under no circumstances can see a stale size value here. First question: Does @volatile ensure this or is it redundant? Now I am introducing a trait: trait BufLike { @volatile var size: Int } final class BufD(val buf: Array[Double], @volatile var size: Int) extends BufLike This gives me a compiler warning: Warning:(6, 4) no valid targets for annotation on method size - it is discarded unused. You may specify targets with meta-annotations, e.g. @(volatile @getter) @volatile var size: Int ^ Second question: Should I remove the @volatile here or change it in a different way? A: I assume thread-A creates, updates, then passes the object-X to thread-B. If object-X and whatever it refers to directly or transitively (fields) are no further updated by thread-A, then volatile is redundant. The consistency of the object-X state at the receiving thread is guaranteed by JVM. In other words, if logical ownership for object-X is passed from thread-A to thread-B, then volatile doesn't make sense. Conversely, on modern multicore systems, the performance implications of volatile can be more than that of thread-local garbage left by immutable case classes. If object-X is supposed to be shared for writing, making a field volatile will help to share its value, but you will face another problem: non-atomic updates on the object-X, if fields' values depend on each other. As @alf pointed out, to benefit from happens-before guarantees, the objects must be passed safely! This can be achieved using java.util.concurrent.** classes. High level constructs like Akka define their own mechanisms of "passing" objects safely. References: https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html A: As @tair points out, the real solution to your problem is to use an immutable case class: The sender may update the size field just before sending it out. It seems that receiver does not update the size; neither does sender update the size after if has already sent the BufD out. So for all practical reasons, recipient is much better off receiving an immutable object. As for @volatile, it ensures visibility—the writes are indeed hitting the main memory instead of being cached in the thread local cache, and the reads include a memory barrier to ensure that the value read is not stale. Without @volatile, the recipient thread is free to cache the value (it's not volatile, hence it should not be changed from the other thread, hence it's safe to cache) and re-use it instead of referring to the main memory. (SLS 11.2.1, JLS §8.3.1.4) @volatile Marks a field which can change its value outside the control of the program; this is equivalent to the volatile modifier in Java. and A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field. The problem here is that either you don't need all that as the object is effectively immutable (and you're better off with a properly immutable one), or you want to see coordinated changes in buf and size on the recipient size. In the latter case, @volatile may be useful (while fragile), if writer appends (not overwrites!) to buf, and then updates the size. In this case, write to buf happens-before write to size, which in turn happens-before reader can read the updated value from size (by volatility), therefore if reader checks and re-checks the size, and writer only appends, you're probably fine. Having said that, I would not use this design. As for the warning, it all compiles to Java, i.e. JVM, bytecode, and volatile is a JVM flag for fields. Traits cannot define a field—they only define methods, and it's up to the extending class to decide whether it'll be a proper variable or (a pair of) methods (SLS 4.2). A variable declaration var x: T is equivalent to the declarations of both a getter function x and a setter function x_=: def x: T def x_= (y: T): Unit A function cannot be @volatile, hence the warning.
{ "language": "en", "url": "https://stackoverflow.com/questions/37305415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: why are drawables colored in black on some mobile phones? In my application I have got a few drawables and I give the user the possibilty to change the backgroundcolor with sharedpreferences. The problem is, that on some mobile phones the drawables are colored in black even if no sharedpreferences are set. The problem occures on older mobile phones API Level < 19. I tried it also with drawable.setColorFilter(...): Resources resForColorFilter = getApplicationContext().getResources(); Drawable drawableForColorFilter = resForColorFilter.getDrawable(R.drawable.soundshape); if(backgroundcolorPref.equalsIgnoreCase("backgroundcolorString")){ Log.d("in backgroundcolorString", "in backgroundcolorString"); drawableForColorFilter.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.CLEAR)); } try { if(!(backgroundcolorPref.equalsIgnoreCase(textFarbePref))){ drawableForColorFilter.setColorFilter(new PorterDuffColorFilter(Color.parseColor(backgroundcolorPref), PorterDuff.Mode.CLEAR)); // wenn die Hintergrundfarbe gleich der Textfarbe ist } else if(backgroundcolorPref.equalsIgnoreCase(textFarbePref)) { // wenn der Hintergrund schwarz gefärbt ist if(backgroundcolorPref.equalsIgnoreCase("#000000")){ textFarbePref = "#FFFFFF"; } else if(backgroundcolorPref.equalsIgnoreCase("#ffffff")){ textFarbePref = "#000000"; } else { textFarbePref = "#000000"; } } } catch(IllegalArgumentException illegalArgumentException){ drawableForColorFilter.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.CLEAR)); } Resources res = getApplicationContext().getResources(); Drawable drawable = res.getDrawable(R.drawable.soundshape); // das geladene Design auf der TextView anwenden, damit ein abgerunter Rahmen erscheint soundUmrandung.setBackground(drawable); if(backgroundcolorPref.equalsIgnoreCase("backgroundcolorString")){ Log.d("in backgroundcolorString", "in backgroundcolorString"); drawableForColorFilter.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.CLEAR)); } try { if(!(backgroundcolorPref.equalsIgnoreCase(textFarbePref))){ drawableForColorFilter.setColorFilter(new PorterDuffColorFilter(Color.parseColor(backgroundcolorPref), PorterDuff.Mode.CLEAR)); // wenn die Hintergrundfarbe gleich der Textfarbe ist } else if(backgroundcolorPref.equalsIgnoreCase(textFarbePref)) { // wenn der Hintergrund schwarz gefärbt ist if(backgroundcolorPref.equalsIgnoreCase("#000000")){ textFarbePref = "#FFFFFF"; } else if(backgroundcolorPref.equalsIgnoreCase("#ffffff")){ textFarbePref = "#000000"; } else { textFarbePref = "#000000"; } } } catch(IllegalArgumentException illegalArgumentException){ drawableForColorFilter.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.CLEAR)); } Resources res = getApplicationContext().getResources(); Drawable drawable = res.getDrawable(R.drawable.soundshape); // das geladene Design auf der TextView anwenden, damit ein abgerunter Rahmen erscheint soundUmrandung.setBackground(drawable); Why are drawables on some mobile phones colored in black? Ok, well this seems to be a bug of API Level 16. I solved the problem by using transparency with drawable.setAlpha(0). Just a little problem remains: the corners of the buttons, and which I specified in xml aren't visible anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/25126200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PrototypeJS not removing select element Given the following HTML, I'm trying to remove all form elements. The problem I'm encountering is that the select element is not being removed, but rather the first option in it is being removed each time the remove code is called. See http://jsfiddle.net/b8FfT/ HTML <fieldset> <div id="order_history_block"> <div id="history_form" class="order-history-form"> <div>Add Order Comments</div> <span class="field-row"> <label class="normal" for="history_status">Status</label><br> <select name="history[status]" class="select" id="history_status"> <option value="processing">Ok to Ship</option> <option value="pending" selected="selected">Pending</option> </select> </span> <span class="field-row"> <label class="normal" for="history_comment">Comment</label> <textarea name="history[comment]" rows="3" cols="5" style="height:6em; width:99%;" id="history_comment"></textarea> </span> <div class="f-left"> <input name="history[is_visible_on_front]" type="checkbox" id="history_visible" value="1"><label class="normal" for="history_visible"> Visible on Frontend</label> </div> <div class="f-right"> <button id="id_79ae3bd75916862b0245fbcb3343d24e" title="Submit Comment" type="button" class="scalable save" onclick="doStuff()" style=""><span><span><span>Submit Comment</span></span></span></button> </div> <div class="clear"></div> </div> <div class="divider"></div> <!-- ... --> </div> </fieldset> JS var a = $('order_history_block').parentNode; $(a).select('input', 'select', 'textarea').invoke('remove'); A: So the HTMLSelectElement prototype (not the framework) has its own remove() method and when you call remove() on <select>s it does not traverse up the prototype chain to the remove() method of HTMLElement added by PrototypeJS. 2 options for you $('history_status').parentNode.removeChild($('history_status')); or Element.remove($('history_status')); I've filed a bug report for this as well https://github.com/sstephenson/prototype/issues/122 EDIT Use a CSS selector and the select() method like this $('order_history_block').up().select('select').each(function(item){ Element.remove(item); });
{ "language": "en", "url": "https://stackoverflow.com/questions/19684961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Encrypt string with public RSA-1280 hex key I've been trying to encrypt a password with a public RSA key that is sent to me by the server. var csp = new CspParameters(1, "Microsoft Strong Cryptographic Provider"); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1280, csp); byte[] key = ByteUtils.HexToBytes(client.RSAKey); RSA.ImportCspBlob(key); byte[] encrypted = RSA.Encrypt(Encoding.ASCII.GetBytes(password), true); The hex key is provided in such format: string key = "30819D300D06092A864886F70D010101050003818B0030818702818100C7BD672D8C634D443840AD809790852770D3A2E99F456D6516329E0205D0645C23FD001D4D070CEE368A20526FEB2402358C915D7E86102B1659AA8651C449C344599F72BE904B8E338E7002E9978453C5BBCCA51AC165AA265069E0EAB1411D11A2FFDD35E5A8296A6A2AF238945874E8206979B0A16E2E4260A161CAB5C905020111"; As the string is 320-bytes long in hex format, I assume the key is 160 bytes (RSA 1280) Using this method, the provider keeps saying "Bad Version of provider.\r\n". I've tried several methods, convert it to Base64, simply import it as ASCII / Unicode. Nothing worked so far. EDIT: My HexToBytes function (which works afaik, it returns me correct 160-b array): public static byte[] HexToBytes(string pValue) { // FIRST. Use StringBuilder. StringBuilder builder = new StringBuilder(); // SECOND... USE STRINGBUILDER!... and LINQ. foreach (char c in pValue.Where(IsHexDigit).Select(Char.ToUpper)) { builder.Append(c); } // THIRD. If you have an odd number of characters, something is very wrong. string hexString = builder.ToString(); if (hexString.Length % 2 == 1) { //throw new InvalidOperationException("There is an odd number of hexadecimal digits in this string."); // I will just add a zero to the end, who cares (0 padding) Log.WriteLine(LogLevel.Debug, "Hexstring had an odd number of hexadecimal digits."); hexString += '0'; } byte[] bytes = new byte[hexString.Length / 2]; // FOURTH. Use the for-loop like a pro :D for (int i = 0, j = 0; i < bytes.Length; i++, j += 2) { string byteString = String.Concat(hexString[j], hexString[j + 1]); bytes[i] = HexToByte(byteString); } return bytes; } A: Your public key is not in the correct format. It is not a CSP blob. It is a DER encoded SubjectPublicKeyInfo structure. You can find source code to parse it or you can write your own. Here is one example of such code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7360193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xamarin.Forms Android I'm developing a cross platform mobile application using Xamarin and Visual Studio 2013. I'm using Portable Class Libraries and I'm writing my code in the PCL project. Whenever I try to debug my app on the virtual android emulator I get this exception: Java.Lang.ClassNotFoundException: android.animation.ValueAnimator in loader dalvik.system.PathClassLoader@43d0b930 How comes? What is ValueAnimator? A: I actually ran into a very similar issue last night when I was working with a Xamarin.Forms application in Xamarin Studio. I had recently updated the Xamarin.Forms and Xamarin.Android.Support.v4 packages in my Android project when it started happening. I believe what I did to get it to work again (I tried a number of things so I'm not exactly sure which one actually fixed it) was to go into my Android project and delete the references to both Xamarin.Forms and Xamarin.Android.Supoort.v4. Then I went into "Manage NuGet Packages" and I added the official Xamarin.Forms library. Since the Xamarin.Android.Support.v4 package is a dependency it pulled that down for me as well. I cleaned and rebuilt my project and I got passed the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/25727471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Beginner not sure how to join lists while scraping Hello I am trying to scrape www.allocine.fr for the latest movies I made the following script: # -*- coding: utf-8 -*- import urllib import re page = ["?page=1", "?page=2", "?page=3"] i=0 while i<len(page): url = "http://www.allocine.fr/film/aucinema/" +page[i] htmlfile = urllib.urlopen(url) htmltext = htmlfile.read() regex = '<a class="no_underline" href="/film/fichefilm_gen_cfilm=[^.]*.html">\n(.+?)\n</a>' pattern = re.compile(regex) movie = re.findall(pattern,htmltext) i+=1 movielist = '\n '.join(movie) print movielist The problem is that the first and last items in the list don't have a space in front of them... what I try to say is on the output the last item in the 1st list and the first item in the 2nd list are not delimited by a space. It looks like this: Something in 1st list something2 in 1st list something3 in 1st list Otherthing in 2nd list otherthing2 in 2nd list otherthing3 in 2nd list ==== I want it to be like: something something something otherthing otherthing A: You could: print the space before: movielist = ' ' + '\n '.join(movie) print the space for each item: movielist = '\n'.join([' ' +i for i in movie]) Exemple: >>> print '\n '.join(movie) something something something otherthing otherthing >>> print ' '+'\n '.join(movie) something something something otherthing otherthing >>> print '\n'.join([' ' +i for i in movie]) something something something otherthing otherthing A: if you just want the items to be listed side by side then change your print statement to something like print "foo" % bar, Reference: python print end=' '
{ "language": "en", "url": "https://stackoverflow.com/questions/25626324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with kotlin receiver when converting from java I'm trying to convert a java class into a kotlin class @Override protected Context constructContext(long entityId, String author, String changesSetId) { Context context = constructDefaultContext(author, changesSetId); try (Connection connection = datasourceConfig.getDataSource().getConnection()) { try (Statement stm = connection.createStatement()) { try(ResultSet rs = stm.executeQuery("select * from modules where id = " + entityId)){ if (rs.next()) { ModuleDto moduleDto = constructModuleDto(rs); context.put("module", moduleDto); } else throw new IllegalArgumentException("No module with id: " + entityId); } } } catch (SQLException throwables) { throw new RuntimeException(throwables); } return context; } the intellij conversion produces override fun constructContext(entityId: Long, author: String, changesSetId: String): Context { val context = constructDefaultContext(author, changesSetId) try { datasourceConfig.dataSource!!.connection.use { connection -> connection.createStatement().use { stm -> stm.executeQuery( "select * from modules where id = $entityId" ).use { rs -> if (rs.next()) { val moduleDto = constructModuleDto(rs) context.put("module", moduleDto) } else throw IllegalArgumentException("No module with id: $entityId") } } } } catch (throwables: SQLException) { throw RuntimeException(throwables) } return context } But when I build it, I get the following error: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline fun <T : Closeable?, R> TypeVariable(T).use(block: (TypeVariable(T)) -> TypeVariable(R)): TypeVariable(R) defined in kotlin.io Pointing at this line: datasourceConfig.dataSource!!.connection.use { connection -> I admit I'm stumped and any advice would be greatly appreciated... EDIT: dataSourceConfig is a simple class to get a datasource, that I had converted using the Intellij converter at an earlier date: class DatasourceConfig { var ds: DataSource? = null @get:Throws(SQLException::class) val dataSource: DataSource? get() { if (null == ds) { val state = CodeGenerationConfigState.instance val mySQLDataSource = MysqlDataSource() mySQLDataSource.setUrl(String.format("jdbc:mysql://localhost:3306/%s", state.dbName)) mySQLDataSource.user = state.username mySQLDataSource.password = state.password ds = mySQLDataSource } return ds } } and context is a VelocityContext A: So it seems I needed to include the kotlin jdk 8 libraries in my gradle build file: implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
{ "language": "en", "url": "https://stackoverflow.com/questions/66358023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt Jambi (Qt4Dotnet): distinguishing signal emitters in a slot I'm newb to Qt and got stuck in a signal/slot mechanism. I have a toolbar with a number of tool buttons, each associated with some widget. The task is to show appropriate widget when tool button is clicked. I want to write a single slot that will handle the associations, but I can't figure out how to distinguish what button triggered a signal. It seems that clicked and toggled signals of QToolButton accept only no-argument slots and store no information about their emitter. I can subclass QtoolButton and raise a CLR event with information about the event sender on each clicked or toggled signal emission, but there should be simplier way to do what I want. Can you help me? A: In your slot, you should be able to call the function sender(), which would return a pointer to the object that emitted the signal (if any did... remember, you can call slots just like a function as well). This is the quick, relatively easy, and sloppy way. However, it breaks encapsulation. A slightly better way would be to provide a numbering mechanism for the buttons, and use a QSignalMapper to map the individual buttons into one signal that contains an int for the button that was clicked. This is in C++ (which I'm more familiar with): QSignalMapper *mapper = new QSignalMapper( this ); connect( mapper, SIGNAL( mapped( int ) ), SLOT( MyFancyFunction( int ) ) ); // Do this for each button: mapper->connect( button1, SIGNAL( clicked() ), SLOT( map() ) ); mapper->setMapping( button1, FIRST_TOOL ) Then: void MyFancyFunction( int option ) { switch ( option ) { case FIRST_TOOL: // do whatever... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/1139216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to calculate minimum unixtimestamp value using sparksql? completion time | unixtimestamp | user| 0.07 |1529094938000 |user3| 0.16 |1529094944000 |user2| 0.27 |1529094947000 |user1| 0.08 |1529094950000 |user2| 0.24 |1529094953000 |user1| 0.10 |1529094956000 |user1| 0.64 |1529094959000 |user3| 0.13 |1529094962000 |user3| 0.67 |1529094965000 |user1| I want minimum timestamp for every user. How can we do it using Sparksql? Assume the above table is in a dataframe. A: we will first convert the timestamp field into integer type if it is not already by any chance. val new_dataframe = dataframe.select($"unixtimestamp".cast(IntegerType).as("unixtimestamp")) 1) Create sqlContext in spark if not exists using the SparkContext object val sqlContext = new org.apache.spark.sql.SQLContext(sc) 2) Register this dataframe as a table new_dataframe.registerTempTable("user_timestamp_data") 3) Now with the prior created sqlContext we can query as val result = sqlContext.sql("SELECT q.user,ROUND(UNIX_TIMESTAMP(q.min)*1000) as MinimumUnixTimeStamp FROM ( select user, MIN(FROM_UNIXTIME(unixtimestamp/1000) min FROM user_timestamp_data GROUP BY user ORDER BY user ASC) AS q ") That should give you users and their corresponding minimum timestamp value A: Use groupBy and agg: val df2 = df.groupBy("user").agg(min(col("unixtimestamp")))
{ "language": "en", "url": "https://stackoverflow.com/questions/51722975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Micronaut multiple JDBC templates not working I am trying to write a micronaut function which is deploying as AWS Lambda. With my micronaut function, I need to connect to multiple databases and get the data and put details into AWS SQS. In this regard, I am trying to use JDBC template approach to get data from different data sources. But I am getting error: Multiple possible bean candidates found: [org.springframework.jdbc.core.JdbcTemplate, org.springframework.jdbc.core.JdbcTemplate, org.springframework.jdbc.core.JdbcTemplate] error package io.test.invoice; import io.micronaut.context.annotation.Factory; import org.springframework.jdbc.core.JdbcTemplate; import javax.inject.Named; import javax.inject.Singleton; import javax.sql.DataSource; @Factory public class JdbcTemplateFactory { @Singleton JdbcTemplate jdbcTemplateOne(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Singleton JdbcTemplate jdbcTemplateTwo(@Named(value = "database2") DataSource dataSource) { return new JdbcTemplate(dataSource); } } package io.test.invoice; import io.micronaut.context.annotation.Requires; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import javax.inject.Singleton; import java.util.List; @Singleton @Requires(beans = JdbcTemplate.class) public class CodeSetRepository { private final JdbcTemplate jdbcTemplateOne; private final JdbcTemplate jdbcTemplateTwo; public CodeSetRepository(JdbcTemplate jdbcTemplateOne, JdbcTemplate jdbcTemplateTwo) { this.jdbcTemplateOne = jdbcTemplateOne; this.jdbcTemplateTwo = jdbcTemplateTwo; } public List<CodeSet> getAllCodeSets() { String SELECT_QUERY = "SELECT * FROM public.code_set"; return this.jdbcTemplateTwo.query(SELECT_QUERY, new BeanPropertyRowMapper(CodeSet.class)); } public List<Country> getAllCountries() { String SELECT_QUERY = "SELECT * FROM public.country"; return this.jdbcTemplateOne.query(SELECT_QUERY, new BeanPropertyRowMapper(Country.class)); } } Could anyone help with this please? A: The name of the parameter jdbcTemplateOne has no bearing on the injection. So both parameters are asking for the same thing. There are multiple templates thus Micronaut doesn't know which one to inject. In your factory you can create a template for each datasource with @EachBean(DataSource.class) JdbcTemplate jdbcTemplateOne(DataSource dataSource) { return new JdbcTemplate(dataSource); } Then the named qualifier of the datasource will transfer to the template. That means in your example you could inject @Named("database2") JdbcTemplate jdbcTemplate. Alternatively you can add @Named qualifiers to the factory methods and then inject the jdbc templates with those qualifiers. A: Change your repository constructor like below @Inject public CodeSetRepository(@Named("database2") JdbcTemplate jdbcTemplateOne) { this.jdbcTemplateOne = jdbcTemplateOne; }
{ "language": "en", "url": "https://stackoverflow.com/questions/60256665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using & validating RTF input after using FILTER_SANITIZE_FULL_SPECIAL_CHARS I am trying to validate a rich text input provided by the TinyMCE editor. I am very aware of leaving myself open to XSS etc and want to get this right. I am sanising the POST data prior to doing anything with it with the following code: //sanitise POST array $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS); I then have a custom validation class to check each field input now it's been sanitized, but... I'm not sure how to check the sanitised RTF input. For example I am using ctype-alpha to check for alpha inputs & filter_var($this->currentObject->value, FILTER_VALIDATE_EMAIL to check for valid email addresses but I'm not sure what to use for the sanitised tinyMCE field. I think what I need is a regex perhaps? Does anyone know the correct expression to check the a tinyMCE RTF input? Am I doing this the right way round??? If using a regex I can then use my function below to return whether it is valid: //used to send a custom regex function regex($regex, $errorMsg = null) { if ($this->isValid && (!empty($this->currentObject->value))) { $this->isValid = (filter_var($this->currentObject->value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "$regex")))) ? true : false; if (!$this->isValid) { $this->setErrorMsg($errorMsg, self::$error_regex); } } return $this; } I think this will work, but am I missing any characters? ^[a-zA-Z0-9\s&amp;|&\.\!?\;\\\-\<\>\/]*$ A: You can use the following functions to sanitize user inputs. Custom regex functions might have some corner cases. sanitize --------- htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8'); wordsanitize ------------ $string = preg_replace('~\W+~', '', $string); htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8'); charactersanitize ----------------- $string = preg_replace('~[^A-Za-z_.]~', '', $string); htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8'); numbersanitize -------------- $string = preg_replace('~\D+~', '', $string); htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8');
{ "language": "en", "url": "https://stackoverflow.com/questions/61695468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matlab mcc Warning "Adding path ... to Compiler path instance" I'm compiling my matlab .m functions (and mex files) to run as a standalone program on a Linux server. In the end, I manage to compile all files and even run them, although in the process I do get some warnings: Warning: Adding path "input_folder1" to Compiler path instance. Warning: Adding path "input_folder2" to Compiler path instance. Warning: Adding path "input_folder3" to Compiler path instance. Basically, my question is what is causing these warnings and how can I avoid them? And, can I run into trouble if I move this standalone program to a different server? The mcc line that is causing these warnings is: mcc -m -d output_folder -I input_folder1 -I input_folder2 -I input_folder3 -a mex_file1.mexa64 -a mex_file2.mexa64 MainScriptFile.m SubFunction1.m SubFunction2.m SubFunction3.m A: These warnings are caused by a missing path. If you want to shut them off, you can either disable them using warning off or add the input_folders to the Compiler path before compiling. But since mcc does that anyway (and displays a warning), you can safely ignore them. Basically, they're just mcc telling you "Couldn't you have done that to start with? Now I'll have to do it myself...". I can't answer your second question the way it is worded, so I'll have to go with this: You will not run into trouble caused by these warnings or any implications. If you do run into trouble, it's for a different reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/22475129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Drawables Ldpi Mdpi Hdpi Xhdpi Can Anyone tell the ratios of ldpi, mpdi, hdpi, and xhdpi? and also how can I tell if the phone/ tablet is in ldpi mdpi hdpi and xhdpi? Tnx in advance A: Approximately 3:4:6:8 for the ldpi mdpi hdpi and xhdpi ratios.
{ "language": "en", "url": "https://stackoverflow.com/questions/24587100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: In Rspec Capybara integration test ,Controllers not maintaining session after login/signup, getting current_user nil I have a test case where after registration devise signup(resource_name, resource) method is called and a redirect_url is sent back to front end , which in turns load the requested page by window.location = redirect_url, though when the next page is hit the next page controller is getting current_user as nil. Test Case require 'rails_helper' feature "sign up with investment profile", js: true do context 'all fields are valid' do let(:goal) do create( :goal, risk_level: Tags::BALANCED, age: 30 ) end before 'valid sign up steps' do create(:currency_conversion) f = File.read("#{Dir.pwd}/spec/response/marketplace/performance.json") allow(Marketplace::StrategyService).to receive(:get_performance_trail).and_return(JSON.parse(f)) model_portfolio_version = create(:model_portfolio_version, :with_performance_trails) goal.model_portfolio_version = model_portfolio_version goal.save! goal.reload visit_page_containing_ajax "/suggestions/#{goal.url_hash}" click_link 'Next: Personal Details' within('.signup-page-header') do expect(page).to have_content 'SIGN UP' end fill_registration_fields(signup_email) fill_personal_info_form wait_for_ajax find('.btn-primary').click wait_for_ajax fill_identification_form wait_for_ajax find('.btn-primary').click wait_for_ajax fill_declaration_form wait_for_ajax find('.btn-primary').click wait_for_ajax expect(page).to have_current_path(kyc_dashboard_path(goal.url_hash)) end context 'User should get registered and redirected to kyc dashboard' do let(:signup_email) { 'email@example.com' } context 'user' do it 'creates investor account' do expect(page).to have_content('Your registration is successful') end end end end end PS: This is happening in test environment only After debugging for hours , I found that we are maintaining session in active_record_store when i change it to cookie_store spec works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/47299834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating Random Number AVR without seed I writing an application in AVR Studio 4 which generates random numbers and outputs them on a seven segment display. At the moment i am using a seed, the seed value then gets randomized and the value output. This method obviously produces the same random number sequence (and displays the same sequence) every time the program is run. Is there an alternate method i can use which does not use a seed and as such does not start the program with the same number each time, allowing for different random numbers. Thanks A: Each time the microcontroller starts up it is seeing exactly the same internal state as any other time it starts up. This means its output will always be the same regardless of any algorithm you might use. The only way to get it to produce different behaviour is to somehow modify its state at startup by introducing some external information or by storing state between startups. Some ideas for how to do the first option might be to measure the duration of a user key press (if your system has buttons) or sensing a temperature or other external input and using this to seed the algorithm. However the simplest option is probably to just store a counter in EEPROM that is incremented after each startup and use this to generate the seed.
{ "language": "en", "url": "https://stackoverflow.com/questions/29201603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: All permutations with repetition using scala I am looking for the scala way to give all permutations without repetitions. I know there are some postings on this site already but they seem to have a slightly different problem. I am searching for all permutations with repetitions. For example: combine(List('A','C','G')) Should yield: List(List('A'.'A','A'),List('A'.'A','C'),List('A'.'A','G'),List('A'.'C','A'), List('A'.'C',''C), ... List('G'.'G','G') I am sorry if my problem is already solved but I was not able to find it. Thanks in advance. EDIT: My own approach (doesn't compile): def combine(size: Int = sym.length) : List[List[T]] = { size match { case 0 => List() case 1 => sym.toList.map(List(_)) case _ => for (el <- sym) yield el :: combine(size-1) } } sym is an array member of a class which contains all the symbols to be combined. A: def combinations(size: Int = sym.length) : List[List[T]] = { if (size == 0) List(List()) else { for { x <- sym.toList xs <- combinations(size-1) } yield x :: xs } } A: This should work: val input = List('A','C','G') (input ++ input ++ input) combinations(3) toList A: scala> def comb(s:String)=(s * s.length).combinations(s.length) comb: (s: String)Iterator[String] scala> comb("ACG").toList res16: List[String] = List(AAA, AAC, AAG, ACC, ACG, AGG, CCC, CCG, CGG, GGG) And if you wanted the resulting permutations: scala> comb("ACG").flatMap(_.toSeq.permutations.toList).toList res11: List[Seq[Char]] = List(AAA, AAC, ACA, CAA, AAG, AGA, GAA, ACC, CAC, CCA, ACG, AGC, CAG, CGA, GAC, GCA, AGG, GAG, GGA, CCC, CCG, CGC, GCC, CGG, GCG, GGC, GGG) You can leave out the toList but it's there so you can see the results. A: It seems no one has suggested the easiest---or, at least, easiest to read---solution. It is myList = List("A", "C", "G") for { i <- myList j <- myList k <- myList } yield List(i,j,k) (This is syntactic sugar for the following composition of maps: myList.flatMap(i => myList.flatMap(j => myList.map(k => List(i,j,k)))) to which the Scala compiler translates the above for expression.) A: With Scalaz: scala> import scalaz._ import scalaz._ scala> import Scalaz._ import Scalaz._ scala> def combine[A](xs: List[A]): List[List[A]] = { | xs.replicate[List](xs.size).sequence | } combine: [A](xs: List[A])List[List[A]] scala> combine(List('A', 'C', 'G')) res47: List[List[Char]] = List(List(A, A, A), List(A, A, C), List(A, A, G), List (A, C, A), List(A, C, C), List(A, C, G), List(A, G, A), List(A, G, C), List(A, G , G), List(C, A, A), List(C, A, C), List(C, A, G), List(C, C, A), List(C, C, C), List(C, C, G), List(C, G, A), List(C, G, C), List(C, G, G), List(G, A, A), List (G, A, C), List(G, A, G), List(G, C, A), List(G, C, C), List(G, C, G), List(G, G , A), List(G, G, C), List(G, G, G)) A: In ScalaZ 7 import scalaz._ import Scalaz._ def combinine[T](l: List[T]) = l.replicateM(l.size) A: Just making a more generic answers, from @opyate and @monnef: // considering that we want a permutation_size List.fill(permutation_size)(input).flatten.combinations(permutation_size).toList This will generate the permutation with repetition with size permutation_size: val a = List.fill(2)(List("A","B","C")).flatten.combinations(2).toList a: List[List[String]] = List(List(A, A), List(A, B), List(A, C), List(B, B), List(B, C), List(C, C)) and val a = List.fill(3)(List("A","B","C")).flatten.combinations(3).toList a: List[List[String]] = List(List(A, A, A), List(A, A, B), List(A, A, C), List(A, B, B), List(A, B, C), List(A, C, C), List(B, B, B), List(B, B, C), List(B, C, C), List(C, C, C))
{ "language": "en", "url": "https://stackoverflow.com/questions/7474709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Lua and Visual C++ I have a simple question. When I open VC++, create an "Empty Project," insert the Lua 5.2.0 source code, then compile, I get no errors. However, when I do this except select "Windows Forms Application" at the beginning, I get a whole bunch of errors. What may be causing this? EDIT: The errors are about safe versions of certain functions: 1>..\lua-5.2.0\src\lua.c(102): error C3861: 'signal': identifier not found 1>..\lua-5.2.0\src\lua.c(178): error C3861: 'signal': identifier not found 1>..\lua-5.2.0\src\lua.c(180): error C3861: 'signal': identifier not found 1> luac.c 1>..\lua-5.2.0\src\luac.c(43): warning C4996: 'strerror': This function or variable may be unsafe. Consider using strerror_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 1> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(157) : see declaration of 'strerror' 1>..\lua-5.2.0\src\luac.c(178): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 1> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\stdio.h(234) : see declaration of 'fopen' 1> lundump.c 1> lvm.c 1>..\lua-5.2.0\src\lvm.c(53): warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 1> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\stdio.h(371) : see declaration of 'sprintf' 1> lzio.c 1> Generating Code... A: It may be because when you create a windows form application, it is actually using managed c++ (uses .net), which I don't think lua is compatible with. Take a look at http://luaplus.org/ that might be what you're looking for. It seems like it's lua for ANY .net language (which managed c++ is)
{ "language": "en", "url": "https://stackoverflow.com/questions/9439262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: darcs appending extra directory separator I am having a problem using darcs getover ssh. I think the failure is because of something wrong in the path to the repository, but I cannot figure out how to correct. The error message reads: darcs failed: Not a repository: britt@brittoffice.uwaterloo.ca:/home/britt/manuscripts/morient ((scp) failed to fetch: britt@brittoffice.uwaterloo.ca:/home/britt/manuscripts/morient//_darcs/inventory) Note the two forward slashes after the repository name morient. I don't know where they come from or how to get rid of them. The directory path would be correct with only one. Is this darcs or scp or other? Thank you. A: it looks like this issue was wrongly closed. I reopened it. http://hub.darcs.net/simon/darcsden/issue/48
{ "language": "en", "url": "https://stackoverflow.com/questions/19802455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: #1062 - Duplicate entry 'default-0-payment/paypal_standard/active' for key 'UNQ_CORE_CONFIG_DATA_SCOPE_SCOPE_ID_PATH I have this problem so i followed answer in that link, it didt worked for me. so i followed comment of @Mukesh Chapagain , INSERT INTO core_config_data (config_id ,scope ,scope_id ,path ,value) VALUES (NULL , 'default', '0', 'payment/paypal_standard/active', '1' ); but its giving below error : #1062 - Duplicate entry 'default-0-payment/paypal_standard/active' for key 'UNQ_CORE_CONFIG_DATA_SCOPE_SCOPE_ID_PATH
{ "language": "en", "url": "https://stackoverflow.com/questions/38315067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to persist the time and score using shared preferences I having developing simple application, which has just like game. When I have finished game the gave over page display, which as time and score. Now if i want to play that game again and again. How to store that previous all time and score and current finished. I want to display, all time and score in to the list according to high to low score, after score button was clicked. I have done shared preferences in gaveover page and that value get from score page. but why not display when i play third time. second time it is ok. third time and so on.. just replacing upward . I don't have enough idea, how to store that all information in to array and display on list. But I have try to use map, but getting not more idea. I want to display this type of format in to the score page: Time .............. Score 1:10 .............. 175 2:05 .............. 145 1:15 .............. 110 2:50 ............... 90 Here I have just started little code but not complete and better, GaveOver.Java Where just diplay socre , time and mistakes after finish game. Score.Java public class Scores extends Activity { private static String strTime; private static int intScore; public static SharedPreferences settings; public static final String MY_PREFS_NAME = "PrefName"; @Override protected void onCreate(Bundle savedInstanceState) { ImageView back, reset, score_home; super.onCreate(savedInstanceState); setContentView(R.layout.score); // lv = (ListView) findViewById(R.id.listView); getValuesFromGaveOver(); SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0); String data=pref.getString("DATA", "Nothing"); Log.i("horror", "DATA "+data); } private void getValuesFromGaveOver() { SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0); strTime = pref.getString(TIME, "n/a"); intScore = pref.getInt(SCORE, -1); Log.i("horror", "From Gave Over "+"Time="+strTime+" "+"Score="+intScore); } @Override protected void onStop() { super.onStop(); SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0); strTime = pref.getString(TIME, ""); intScore = pref.getInt(SCORE, -1); savePreferences(intScore, strTime); } private void savePreferences(int s, String t) { SharedPreferences sPref = this.getSharedPreferences(MY_PREFS_NAME, 0); SharedPreferences.Editor edit = sPref.edit(); edit.putString("DATA", strTime+" "+intScore); edit.commit(); } } please give me the good suggestion, how to do it? A: The cleanest way would be to use sqlite databases. Using SharedPreferences is much easier, especially for beginners. You could do it like that: You save a 3rd item, the actual entry count as SharedPreference. Everytime you save a new entry you increment this counter. Then you append the current counter number to the TIME and SCORE keys. // Saves a new entry | Attention: code not tested! save(int score, int time){ SharedPreference pref = ... SharedPreference.Editor editor = ... int newEntryID = pref.getInt("numEntries", 0) + 1; editor.setInt("numEntries", newEntryID); editor.setInt("score" + newEntryID, score); editor.setString("time" + newEntryID, time); editor.commit(); } Assuming "score" is the SharedPreference-Key for SCORE and same for the time. Reading would be of the same scheme. for(int i=0; i<numEntries; ++i){ pref.getInt("score" + i, 0); ... } A: using the shared preference you can store both, 1) first you have to store time, once this is done you have to store score mapped on the given time, you are doing this way, edit.putString("DATA", strTime+" "+intScore); But you can take different approach if you have only one player playing at one time, edit.putString("TIME", strTime); edit.putString(strTime, strScore); 1:10 .............. 175 So here first you mapped your time with TIME and then you mapped score 175 with 1:10 Hope this will help you A: Good idea would be to define Java bean holding score ( say with 2 Fields, time in seconds / points / maybe date / name / whatrever else fields you like to store). You can easily do following with them: * *sort in a list and limit their amount ( you do not like to have 10000 of score entries, 100 will be anough ) *marshall this list to / from JSON ( Shameless self advertising: https://github.com/ko5tik/jsonserializer ) *store JSON in a shared preference or in a private application file (I store up to 100 local highscore entries, and 1000 all time scores and use files)
{ "language": "en", "url": "https://stackoverflow.com/questions/8666116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CFLOOP Duplication I have a drop down list that is generated by two loops. The inner loop generates a series of numbers ie from 0 to 23. The outer loop, is a query loop that selects the correct value from the 23 numbers based on the values stored in my database. My issue here is that those two loops conflict that results in displaying the numbers from 0 to 23 twice. How can keep both loops but avoiding this issue? This problem also cause issues when the form is submitted by trying to submit the form twice and deleting the user's input. This is my code: <select id="openHours#CountVar#" name="openHours#CountVar#"> <cfloop query="doctorHours" > <cfloop from="0" to="23" index="OpenHours"> <option value="#openHours#" <cfif TimeFormat(doctorHours.openTime,'HH') EQ OpenHours AND CountVar EQ doctorHours.day > selected="selected"</cfif>>#OpenHours#</option> </cfloop> </cfloop> </select> This is my CFDUMP for that query query RESULTSET query CLOSETIME DAY DOCTORID OPENTIME 1 1970-01-01 16:00:00.0 4 2011041516290025478779 1970-01-01 10:00:00.0 2 1970-01-01 16:00:00.0 1 2011041516290025478779 1970-01-01 13:00:00.0 3 1970-01-01 16:00:00.0 2 2011041516290025478779 1970-01-01 13:00:00.0 CACHED false EXECUTIONTIME 0 SQL select doctorID, opentime, closetime, day from doctorBusinessHours where doctorID='2011041516290025478779' A: You should return only the hours you need and then loop for the dropdownlist creation: DATEPART(hh,yourdate) will return the hours for your datetime value: <cfquery name="doctorHours" datasource="#ds#"> SELECT doctorID,DATEPART(hh,openTime) As OpenHours, DATEPART(hh,closetime) As CloseHours FROM doctorHours WHERE day = #CountVar# AND doctorID='#docID#' </cfquery> ValueList will transform your query results into a list: <cfset openTimesList = ValueList(doctorHours.OpenHours) /> <cfset closeTimesList = ValueList(doctorHours.CloseHours ) /> ListContains will return the index of the value within your list: <select id="openHours#CountVar#" name="openHours#CountVar#"> <cfloop from="0" to="23" index="OpenHours"> <option value="#openHours#" <cfif ListContains(openTimesList,OpenHours) NEQ 0 > selected="selected" </cfif> >#OpenHours#</option> </cfloop> </select> You can use the same strategy for the closeTimesList. A: Hmmm....the number of values displayed in the code above will be equivelant to the number of records returned by the query X 23. If you're query returns 2 records you will see 46 options and so on. It seems like you believe the query has only 1 record. I would suggest perhaps it has more. Try LIMIT 1 or TOP 1 in your query - or use Maxrows (as suggested in the comments)... but make sure you know what you are including and what you are excluding. You need to know why your query is not what you expect :)
{ "language": "en", "url": "https://stackoverflow.com/questions/10095496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Microsoft Azure Directory oAuth redirect_uri not accepting state query parameter I'm trying to implement the oAuth flow to sign in with Microsoft. I have the following endpoints: https://login.microsoftonline.com/common/oauth2/v2.0/authorize https://login.microsoftonline.com/common/oauth2/v2.0/token My flow is like this: Redirect to Microsoft by clicking on Sign in with Microsoft button: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope=user.read&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F1%2Ffrontend%2Flogin%3Fstate%3Dtest My redirect url is: http://localhost:8000/1/frontend/login?state=test Which is appended with the code I receive back from Microsoft. I then perform a POST request to the /token endpoint. However, I receive an error (AADSTS50011) saying: AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: The data I send is correct, except for the redirect_uri. I have the following value: http%3A%2F%2Flocalhost%3A8000%2F1%2Ffrontend%2Flogin%3Fstate%3Dtest Which is just an url encoded version of my redirect url including the ?state=test I know that everything works fine, except the redirect_uri, because when I remove the state query param, everything works fine. However, to route the redirect_uri correctly in my application, I need the state param. I cannot add it in my App settings, and I have to include it in the first request (/authorize endpoint) That all works fine, but the second (/token) POST request fails, I cannot enter my redirect_uri with the ?state= parameter. I've tried several options such as encoding the redirect_uri, but it doesn't help. All other oAuth flows (Like Github) are working fine. Except Microsoft. A: Attach your state param to the auth request itself, don’t put it in the redirect_uri param. Then the state param is automatically sent back to the redirect uri. https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope=user.read&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F1%2Ffrontend%2Flogin&state=xyz
{ "language": "en", "url": "https://stackoverflow.com/questions/63316748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: create a set of cumulative intersection counts I want to count the intersection of var1[i] and union(var2[1],...,var2[i]). Using this data var1 <- list('2003' = 1:3, '2004' = c(4:3), '2005' = c(6,4,1), '2006' = 1:4 ) var2 <- list('2003' = 1:3, '2004' = c(4:5), '2005' = c(2,3,6), '2006' = 2:3 ) I would like to populate a results list with: 1. intersect(var1$2003,var2$2003) 2. intersect(var1$2004,union(var2$2003,var2$2004)) 3. intersect(var1$2005,union(var2$2005(union(var2$2003,var2$2004)))) and so on, until 2012 (not shown in the example) * *Disclaimer: due to editing, the comments below might not make sense. A: Is something like this what you want? # create the data var1 <- list('2003' = 1:3, '2004' = c(4:3), '2005' = c(6,4,1), '2006' = 1:4 ) var2 <- list('2003' = 1:3, '2004' = c(4:5), '2005' = c(2,3,6), '2006' = 2:3 ) # A couple of nested lapply statements lapply(setNames(seq_along(var1), names(var1)), function(i,l1,l2) length(intersect(l1[[i]], Reduce(union,l2[1:i]))), l1 = var1,l2=var2) $`2003` [1] 3 $`2004` [1] 2 $`2005` [1] 3 $`2006` [1] 4 note that Reduce(union,var2)reduces the list var2 by successively combining the elements using union (see ?Reduce) Reduce(union,var2) [1] 1 2 3 4 5 6 EDIT elegant alternative use the accumulate = T argument in Reduce lapply(mapply(intersect,var1, Reduce(union, var2, accumulate=T)),length) Because -- Reduce(union, var2, accumulate = T) ## [[1]] ## [1] 1 2 3 ## ## [[2]] ## [1] 1 2 3 4 5 ## ## [[3]] ## [1] 1 2 3 4 5 6 ## ## [[4]] ## [1] 1 2 3 4 5 6
{ "language": "en", "url": "https://stackoverflow.com/questions/12209276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: remove Cookie using jquery not working I have two cookies in my JS file and I want to remove them. I have tried the code below but it is not working $.removeCookie('filter', { path: '/Home/' }); $.removeCookie('Pfilter', { path: '/Home/' }); I have also tried the below for null cookies, but this is also not working. Thanks for the help $.cookie('filter',null, { path: '/Home/' }); A: Did you try $.cookie("name", null); $.removeCookie('filter', { path: '/' }); A: It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path. You might be using the generic / for your path instead of /Home/. Give the code below a try. To delete a cookie with jQuery set the value to null: $.removeCookie('filter', { path: '/' }); A: What works for me is setting the cookie to null before removing it: $.cookie("filter", null); $.removeCookie("filter); A: I was having the same issue with jquery version 1.7.1 and jquery cookie version 1.4.1 This was driving me crazy so I decided to dive into the source code and I figured out what is wrong. Here is the definition of $.removeCookie $.removeCookie = function (key, options) { if ($.cookie(key) === undefined) { // this line is the problem return false; } // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; As you can see when the function checks if the cookie exists it doesn't take the options object into account. So if you are on a different path than the cookie you're trying to remove the function will fail. A Few Solutions: Upgrade Jquery Cookies. The most recent version doesn't even do that sanity check. or add this to you document ready $.removeCookie = function (key, options) { if ($.cookie(key, options) === undefined) { // this line is the fix return false; } // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; or when removing cookies do something like this: $.cookie('cookie-name', '', { path: '/my/path', expires:-1 }); A: If you use a domain parameter when creating a cookie, this will work $.removeCookie('cookie', { path: '/' , domain : 'yourdomain.com'}); A: This simple way it works fine: $.cookie("cookieName", "", { expires: -1 });
{ "language": "en", "url": "https://stackoverflow.com/questions/18486165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Could not convert parameter `tx` between node and runtime: Could not decode `Call::Assets.0`:Could not decode Execution failed: ApiError("Could not convert parameter `tx` between node and runtime: Could not decode `Call::Assets.0`:\n\tCould not decode `Call::create.3`:\n\t\tNot enough data to fill buffer\n") Runtime Implementation In Substrate node template vpallet-assets = { default-features = false, version = '3.0.0' } parameter_types! { pub const AssetDepositBase: u64 = 1; pub const AssetDepositPerZombie: u64 = 1; pub const StringLimit: u32 = 50; pub const MetadataDepositBase: u64 = 1; pub const MetadataDepositPerByte: u64 = 1; pub const AssetDepositPerZombie: Balance = 2 * 7; pub const AssetDeposit: Balance = 2 * 7 ; pub const ApprovalDeposit: Balance = 2 * 7 ; } impl pallet_assets::pallet::Config for Runtime { type Event= Event; type Balance= Balance; type AssetId= u32; type Currency = Balances; type ForceOrigin = frame_system::EnsureRoot<AccountId>; type StringLimit = StringLimit; type AssetDepositBase=AssetDepositBase; type AssetDepositPerZombie= AssetDepositPerZombie; type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>; } I am calling the extrinsic from polkadot.js.org (localnode) In Types using { "Address": "MultiAddress", "LookupSource": "MultiAddress" } Error Is Not Releated to types MultiAddress, the error is about Call::Assets.0 , I am calling the assets::create extrinsics and all other are working perfectly A: Close to a duplicate of may other questions here, like this one. You need to set the types used in your chain in you polkadot.js API consuming apps: https://polkadot.js.org/docs/api/start/types.extend
{ "language": "en", "url": "https://stackoverflow.com/questions/69682136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: folium:: make GeoJson search marker transparent I have a basic folium heatmap that shows locations as CircleMarker and a HeatMap layer on top as displayed below. I wanted to add search functionality in my map so I converted my pandas dataframe into a GeoJson format so that I can pass that. class folium.plugins.Search(layer, search_label=None, search_zoom=None, geom_type='Point', position='topleft', placeholder='Search', collapsed=False, **kwargs) Bases: branca.element.MacroElement Adds a search tool to your map. Parameters: layer (GeoJson, TopoJson, FeatureGroup, MarkerCluster class object.) – The map layer to index in the I was able to convert my Pandas DataFrame into GeoJson using below code. df_json = pd.read_csv("C:\\py\\folium\\NE Task 1\\json.csv").dropna(how="any") # convert lat-long to floats and change address from ALL CAPS to Regular Capitalization df_json['latitude'] = df_json['latitude'].astype(float) df_json['longitude'] = df_json['longitude'].astype(float) df_json['Site Name'] = df_json['Site Name'].str.title() # we don't need all those columns - only keep useful ones useful_cols = ['Site ID', 'Site Name', 'latitude', 'longitude'] df_subset = df_json[useful_cols] # drop any rows that lack lat/long data df_geo = df_subset.dropna(subset=['latitude', 'longitude'], axis=0, inplace=False) def df_to_geojson(df_json, properties, lat='latitude', lon='longitude'): geojson = {'type': 'FeatureCollection', 'features': []} # loop through each row in the dataframe and convert each row to geojson format for _, row in df_json.iterrows(): # create a feature template to fill in feature = {'type': 'Feature', 'properties': {}, 'geometry': {'type': 'Point', 'coordinates': []}} # fill in the coordinates feature['geometry']['coordinates'] = [row[lon], row[lat]] # for each column, get the value and add it as a new feature property for prop in properties: feature['properties'][prop] = row[prop] # add this feature (aka, converted dataframe row) to the list of features inside our dict geojson['features'].append(feature) return geojson geojson_dict = df_to_geojson(df_geo, properties=useful_cols) geojson_str = json.dumps(geojson_dict, indent=2) folium.plugins.Search(data=geojson_dict, geom_type='Point', search_zoom=14, search_label='Site ID').add_to(map) After doing that search function is working properly as i wanted but a Marker is being displayed on TOP which i cannot hide like below. Please help me guide how can I hide this marker and keep GeoJson intact so that I can use it for search function. I tried to make it transparent, change the opacity of GeoJson through the solutions I found over stackOverflow but nothing works. Thanks in advance for your time and sorry for the long post. Best Regards A: In general, if you add folium.LayerControl().add_to(map) to the map then it provides functionality to display or hide your Geojson markers. Then you can hide or display markers using show=False or from 'Layers' icon on the top right of the map (see the image below) For example: # creating folium GeoJson objects from out GeoDataFrames pointgeo = folium.GeoJson(gdf,name='group on map', show=False, tooltip=folium.GeoJsonTooltip(fields=['Name', 'Relation', 'City'], aliases=['Name','Relation', 'City'], localize=True)).add_to(map) # To Add a LayerControl add below line folium.LayerControl().add_to(map) map Like in these images Marker are shown or hidden by controlling layer from top righ 'Layers' - 1) with markers 2) markers hidden you can refer to this link for more example: Folium_search Hope this helps!! A: I've found only this solution to make that. search = folium.FeatureGroup(name="Search", show=False).add_to(map) geojson_obj = folium.GeoJson(geo_json, zoom_on_click=True).add_to(search) Search( layer=geojson_obj, search_label="search_name", geom_type="Point", ).add_to(map) folium.LayerControl().add_to(map)
{ "language": "en", "url": "https://stackoverflow.com/questions/55312766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Forcing error in TypeScript compile with void return With the following code: function foo() : void { // do something } var f = foo(); // why no error here? This does not produce a compiler warning/error even though the foo function has been declared to not return anything. Another case that I'd like to prevent is: if (foo()) { } I'm building an API to be used by other developers, and TypeScript works well encouraging type safety and often helps to catch common JavaScript errors that otherwise would only be caught in testing rather than at compile time. This case though isn't apparently handled though as it would be in other languages like C#. The developers often will be customers, and may not have as much experience, so I want to make the platform as robust as possible, and catch as many issues before the code is deployed. Is there some reasonable way to structure the code to prevent other code from attempting to use the undefined result of a function that has no return value? If foo doesn't return anything, I'd rather code only can call it as foo(); and not inadvertently expect a valid return value when doing an assignment (or similar execution). Other programming languages would often catch this type of code structure at compile time (and display a warning/error). A: It is because void is a valid TypeScript type declaration. E.g the following is valid var f:void; However it is not useful as a variable type. From the language spec (http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf): NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters. Update: As pointed out by Ryan : https://twitter.com/SeaRyanC/status/479664200323579904 You don't get much additional typesafety if f:void was disallowed. You can't use f in a meaningful way e.g. the following are all compile errors. var f:void; f.bar; // error function bar(f:{}){} bar(f); // error var baz:{a?:number} = f; // error // Only allowed cases f = undefined; f = null; Curious about your real world case though. Update based on question update: Unfortunately I don't see a way to get the compiler to prevent this, since anything is allowed in a JS/TS if statement. Perhaps you want a boolean only truthy/falsy restriction. if (f()) { } A: I believe if you try: var f:number=foo(); It will return the error you're looking for. I think an untyped variable defaults to "any" which makes it not check typing. Link here:
{ "language": "en", "url": "https://stackoverflow.com/questions/24308842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamic build a table from json data in angular2 I can't wrap my head around a looping system I need to make to build up a table from json data. This is what I've got so far (tried some other stuff but I think this illustrates it the best way). Looping through the headers works fine, it's just the cells I can't get to work. This is my dummy data: tableMockData = [ { "header": "TH 1", "rows": [ "TH1 - row1", "TH1 -row2", "TH1 - row3", "TH1 - row4" ] }, { "header": "TH 2", "rows": [ "TH2 -row1", "TH2 - row2", "TH2 - row3", "TH2 - row4", ] }, { "header": "TH 3", "rows": [ "TH3 -row1", "TH3 - row2", "TH3 - row3", "TH3 - row4", ] }, { "header": "TH 4", "rows": [ "TH4 - row1", "TH4 - row2", "TH4 - row3", "TH4 - row4", ] } ] This is my basic loop as starting point: <tr *ngFor="let row of tableMockData; let i = index"> <td>{{row.rows[i]}}</td> </tr> This is my outcome: This is my desired outcome: Can someone point me out in the right direction, I know which cell needs to go where but I simply can't wrap my head around how to loop through it. Thanks Update: here is a stackblitz example: https://stackblitz.com/edit/angular-cdoqwb A: Update your Html with below code <table> <tr> <th *ngFor="let row of tableMockData; let i = index">{{row.header}} </th> </tr> <tr *ngFor="let row of tableMockData; let i = index"> <td *ngFor="let row1 of row.rows"> {{row1}} </td> </tr> </table> You do not properly bind your JSON.
{ "language": "en", "url": "https://stackoverflow.com/questions/54762274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically add new field with same key name in MongoDB Im trying to create a list on one of my collections in a dynamic way, here is an example. var user = mongoose.Schema({ "NAME": String, "LAST": String, "EMAIL": String, "TasksUploaded": {} }) And what I want to do in mongoose is update the user with the tasks he has already uploaded, what is the best way to do this? what i want at the end is this: { "Name" : "John", "Last" : "Doh", "Email" : "john@doh.com", "TasksUploaded" : { "Task" : "Task A" "Task" : "Task B" "Task" : "Task H" "Task" : "Task F" "Task" : "Task C" } } As you can see the task are not always consecutive and the user can upload them as he wants. Im new to all this new NoSQL and MongoDB stuff, so if you could tell what is the best practice i would appreciate it. This is how I currently update it but what happens is that the "Level" gets replaced and y need to add a new line to the docuemnt. User.findOneAndUpdate({ _id: id}, { $set: { 'TasksUploaded.Task': req.body.task} }, { returnNewDocument: true, new: true }, function (err, result) { if (err) { console.log("Error saving task: " + err); return; } console.log(result); }) } A: Nope, that's not possible. You can't have several keys with the same name in an object. Just imagine, how would you address them? It seems that you need to restructure your data and use arrays. A: thanks to @Sam, I modified my structure to add the upload tasks in a form of an array TasksUploaded ["TaskA","TaskB","TaskC"] Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/41387686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding a forms OnPaint method in component class Im looking to override the OnPaint method of the parent form of my component.. However i face 2 errors while doing this, the first is assigning the parent forms event handler * *No overload for "OnPaint" matches delegate "PaintEventHandler" *Member from "Region.FromHrgn(IntPtr)" cannot be accessed with an instance reference; Qualify it with a type name instead. heres my code private Control hostControl; public override ISite Site { get { return base.Site; } set { base.Site = value; if (value == null) { return; } IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost; if (host != null) { IComponent componentHost = host.RootComponent; if (componentHost is ContainerControl) { hostControl = componentHost as ContainerControl; hostControl.FindForm().Paint += new PaintEventHandler(this.OnPaint); } } } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); hostControl.Region = hostControl.Region.FromHrgn(CreateTriangle(0, 0, this.Width, this.Height, this.Width, this.Height)); } Where am i going wrong? A: Overriding the OnPaint() method of a control is normally recommended for custom drawing of THAT control, not of drawing another control. What you are trying to do in your code is to attach the Paint event of the hosting form to the OnPaint() method of your control. That's probably not working. As you can read in the MSDN documentation, the Paint event of a control is raised by the OnPaint() method. You can attach a custom event handler: hostControl.FindForm().Paint += new PaintEventHandler(Form_Paint); private void Paint(object sender, System.Windows.Forms.PaintEventArgs e) { ... } In the PaintEventArgs argument you will get the required parameters for drawing.
{ "language": "en", "url": "https://stackoverflow.com/questions/45839096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Values of array after cudaMemcpy I'd like to know if, when i'm calling cudaMemcpy(...) to get memory on the GPU, also the values inside the array are copied or not. I will explain better: I'm copying the values from one array to another and then i call cudaMalloc and cudaMemcpy. // Copying values of the arrays for(int i = 0; i<16; i++){ array_device_1[i] = array_host_1[i]; array_device_2[i] = array_host_2[i]; } // Memory allocation of array_device_1 and array_device_2 cudaMalloc((void**) &array_device_1, SIZE_INT*size); cudaMalloc((void**) &array_device_2, SIZE_INT*size); // Transfer array_device_1 and array_device_2 cudaMemcpy(array_device_1, array_host_1, SIZE_INT*size, cudaMemcpyHostToDevice); cudaMemcpy(array_device_2, array_host_2, SIZE_INT*size, cudaMemcpyHostToDevice); kernel<<<N, N>>>(array_device_1, array_device_2); cudaMemcpy(array_host_1, array_device_1, SIZE_INT*size, cudaMemcpyDeviceToHost); cudaMemcpy(array_host_2, array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost); cudaFree(array_device_1); cudaFree(array_device_2); So, when i'm executing all those instructions and I'm using all the arrays inside the kernel, are the values inside the array_device_1 and array_device_2 or not ? I tried to print out after the kernel and i noticed that all the arrays are empty! Really i can't understand how i can keep the values inside them and then changing their values with kernel function. A: Yes they have their values inside. But you can't print them out on the host. For this you will need to copy your data back using cudaMemcpy((void *) array_host_2, (void *) array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost); And then you can print the values of array_host_2. A bit more explanation: Your array_device_* lives on the GPU and from your CPU (that is printing your output) you do not have direct access to this data. So you need to copy it back to your CPUs memory first before printing it out. A: Example of copying array with data to device, altering values in kernel, copy back to host and printing the new values: // Function to run on device by many threads __global__ void myKernel(int *d_arr) { int idx = blockIdx.x * blockDim.x + threadIdx.x; d_arr[idx] = d_arr[idx]*2; } int main(void) { int *h_arr, *d_arr; h_arr = (int *)malloc(10*sizeof(int)); for (int i=0; i<10; ++i) h_arr[i] = i; // Or other values // Sends data to device cudaMalloc((void**) &d_arr, 10*sizeof(int)); cudaMemcpy(d_arr, h_arr, 10*sizeof(int), cudaMemcpyHostToDevice); // Runs kernel on device myKernel<<< 2, 5 >>>(d_arr); // Retrieves data from device cudaMemcpy(h_arr, d_arr, 10*sizeof(int), cudaMemcpyDeviceToHost); for (int i = 0; i<10; ++i) printf("Post kernel value in h_arr[%d] is: %d\n", i,h_arr[i]); cudaFree(d_arr); free(h_arr); return 0; } A: The code snippet you provided seems correct, other than the first few lines as leftaroundabout pointed out. Are you sure the kernel is correct? Perhaps you are not writing the modified values back to global memory. If you make another set of host arrays and copy the GPU arrays back before running the kernel, are they correct? From what you have, the values inside array_host_* should have been copied to array_device_* properly. A: You can use a kernel function to directly print values on GPU memory. Use can use something like: __global__ void printFunc(int *devArray){ printf("%d", devArray[0]); } Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/9928812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I locate data in a database with vague column names? In our database we have a number of tables that have non-descriptive columns names e.g. (Attribute1, Attribute2....Attribute60 etc). What I am wanting to know is if given a particular piece of information e.g. I know that a Job Code could be "123456", but I do not know what column in our database relates to Job Code, is it possible using a query to find out which column in which table contains data that is similar to that of 123456? I am fairly confident my colleague used to have a query to achieve this but he has since left our organisation and I cannot seem to find his query. Appreciate any help I can get! A: sp_search_code is what I use to find any code items which are in the DB; however, what you need is a redgate tool which will index the db and help you search its contents. I will suggest as Just Aguy did, that you spend some time cleaning up those generic column names and any gen table names for that matter, good luck. http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/15285713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to upload to files to amazon EC2 I am trying to upload files to an amazon EC2 from android. however whenever i go to upload the files I get a Unexpected response code 500 error. From what I uderstand this is because the user doesnt have the correct permissions to upload files to the database? I know that the problem is with the amazon EC2 instance rather than the code. but below is my php code for uploading to the server. first of all is that the correct way to enter the upload folder (/var/www/html/uploads) ? Any help on how i can get this working would be great. <?php if(isset($_POST['image'])){ echo "in"; $image = $_POST['image']; upload($_POST['image']); exit; } else{ echo "image_not_in"; exit; } function upload($image){ $now = DateTime::createFromFormat('U.u', microtime(true)); $id = "pleeease"; $upload_folder = "/var/www/html/upload"; $path = "$upload_folder/$id.jpg"; if(file_put_contents($path, base64_decode($image)) != false){ echo "uploaded_success" } else{ echo "uploaded_failed"; } } ?> A: Just a few notes: First, you should make sure to send your data from the app with the enctype of multipart/form-data before submitting to the server. Second, try variants of this simplified code: if(isset($_FILES['image'])) { $fileTmp = $_FILES['image']['tmp_name']; $fileName = $_FILES['image']['name']; move_uploaded_file($fileTmp, "/var/www/html/uploads/" . $fileName); echo "Success"; } else { echo "Error"; } And finally, assuming you're using Apache and the user name is www-data, you'll need to make sure it can write to the upload folder: sudo chown www-data:www-data /var/www/html/uploads sudo chmod 755 /var/www/html/uploads
{ "language": "en", "url": "https://stackoverflow.com/questions/42382461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merge fields laravel collections I have two Laravel collections. Mi first collection called $custom_product: Collection {#313 ▼ #items: array:1 [▼ 0 => array:1 [▼ "custom_description" => "insert description here" ] ] } And I have my other collection called $api_product: Collection {#311 ▼ #items: array:29 [▼ "article_id" => 5570 "active" => null "name" => "CORBATA POLIESTER" "detail" => "- Pesa: 43 gr." "constructor_name" => "gift" "stock_available" => true "stock" => null "prices" => array:6 [▶] "price_pvp" => 29.0 "size" => "1410X100" ] } I want this result. The same collection but with the field custom_description added: Collection {#311 ▼ #items: array:29 [▼ "article_id" => 5570 "active" => null "custom_description" => "insert description here"//add this field "name" => "CORBATA POLIESTER" "detail" => "- Pesa: 43 gr." "constructor_name" => "gift" "stock_available" => true "stock" => null "prices" => array:6 [▶] "price_pvp" => 29.0 "size" => "1410X100" ] } A: You may use put method of laravel collection. $collection = collect(['product_id' => 1, 'name' => 'Desk']); $collection->put('price', 100); $collection->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100] A: You can itarete over collections and add fields manually as with simple array: for ($i = 0; $i < count($secondCollection); $i++) { // Add field to an item. $secondCollection[$i]['custom_description'] = $firstCollection[$i]['custom_description']; } This code will give an idea. Actual code is really depends on collections structure. A: In the case that you were doing this per individual record using the examples given, I think it would be: $api_product->put($custom_product->toArray()[0]); If you wanted to combine multiple records you could use the map() method $api_products_collection->map(function($key,$item) { //combine the record return $item; });
{ "language": "en", "url": "https://stackoverflow.com/questions/41415324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access parent object of Button in click event in UWP application with C# This is for a UWP application for raspberry pi (c#). I have a button as a public member of a class written by me. Since this is a member of class. Whenever an object of this class is created, it needs to have a Click event. I need to have the click event inside the MainPage.xaml.cs file in order for it to have access to other functions, instead of the actual class. I am able to use the following code: ExecutionSequence newSeq = new ExecutionSequence(); newSeq.SelectionButton.Click += SelectionButton_Click; private void SelectionButton_Click(object sender, RoutedEventArgs e) { Button tempbutton = sender as Button; } The above code gives full access of the properties of the Button. However, I am looking for help in the above scenario to access the actual object of class to which this button belongs to as the event requires to access other members of class. Please note that I considered making the click event as another member of the class itself. But it makes things complex in my case.
{ "language": "en", "url": "https://stackoverflow.com/questions/65035416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JQuery Mobile clone page I having trouble cloning a page of jqm. Here is an example: http://jsfiddle.net/QZKBw/ as you can see, the cloning and modifing the page is not the problem: var newPage = $('#page-1').clone(); newPage.prop('id', 'page-2'); newPage.find('#header-1') .prop('id', 'header-2') .find('h1') .html('Page 2'); The switch back to page 1 will end up with two active pages. Is it a problem with jqm? A: This should do it: http://jsfiddle.net/Gajotres/Nc98p/ $(function () { $('#clone-page').click(function () { if($('#page-2').length == 0){ var newPage = $('#page-1').clone(); newPage.prop('id', 'page-2'); newPage.find('#header-1') .prop('id', 'header-2') .find('h1') .html('Page 2'); newPage.find('#content-1') .prop('id', '#content-2') .html('<a href="#page-1" data-role="button"> to Page 1</a>'); newPage.appendTo($.mobile.pageContainer); } $.mobile.changePage('#page-2'); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/14923313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot acces a disposed object I'm trying to change some of my linq codes to sp but in one my functions which is private async Task getNodes() { List<TreeViewNode> nodes = new List<TreeViewNode>(); var activities = await _spConnections.GetActiveListBySpAsync(User.Identity.GetCookieUserCompId<int>()); //Loop and add the Parent Nodes. foreach (var activity in activities) { var model1 = await _activitiesService.GetByIdWithFormsAsync(activity.ID); var model = model1.Forms.OrderBy(f => f.Order).ToList(); var preformid = model1.PreFormId; nodes.Add(new TreeViewNode { id = activity.ID.ToString(), parent = "#", text = activity.Name }); var Forms = await _spConnections.GetSpMainActiveFormListAsync(activity.ID); // Loop and add the Child Nodes. foreach (var form in Forms) { DigitalContentEnum enumType = EnumHelper<DigitalContentEnum>.Parse(form.Type); string typeName = EnumHelper<DigitalContentEnum>.GetDisplayValue(enumType); nodes.Add(new TreeViewNode { id = form.ActivitiesID.ToString() + "-" + form.ID.ToString(), parent = form.ActivitiesID.ToString(), text = form.Title + " <span class='text-danger'>(" + typeName + ") </span> "}); } if (preformid != null) { var preformtags = await _activitiesService.GetByIdWithPreFormsAsync(preformid); var preformModel = preformtags.Forms.OrderBy(x => x.Order).ToList(); foreach (var foorm in preformModel) { DigitalContentEnum enumType = EnumHelper<DigitalContentEnum>.Parse(foorm.Type); string typeName = EnumHelper<DigitalContentEnum>.GetDisplayValue(enumType); nodes.Add(new TreeViewNode { id = foorm.ActivitiesID.ToString() + "-" + foorm.ID.ToString(), parent = model1.ID.ToString(), text = foorm.Title + " <span class='text-danger'>(" + typeName + ") </span> " }); } } } //Serialize to JSON string. var result = JsonConvert.SerializeObject(nodes); ViewBag.Json = result; } So as you see var activities is being filled by running a sp and it does work but when it reaches var model1 = await _activitiesService.GetByIdWithFormsAsync(activity.ID); The Error: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'Context'. appears activitesservice is my repository which the runs the following : public async Task<Activity> GetByIdWithFormsAsync(long id) { return await _activities.Include(x => x.Forms).FirstOrDefaultAsync(x => x.ID == id); } and my sp is: public async Task<List<Form>> GetSpMainActiveFormListAsync(long actId) { var Check = new List<Form>(); using (_unitOfWork) { using (var cmd = _unitOfWork.ExecuteCreateConnection()) { cmd.CommandText = "SpGetMainActiveForm"; cmd.CommandType = System.Data.CommandType.StoredProcedure; var param1 = cmd.CreateParameter(); param1.ParameterName = "actId"; param1.Value = actId; cmd.Parameters.Add(param1); _unitOfWork.ExecuteOpenConnection(); using (var result = cmd.ExecuteReader()) { if (result.HasRows) { Check = (List<Form>)CommonFunctions.Conversions.MapToList<Form>(result); } } _unitOfWork.ExecuteCloseConnection(); } } return Check; } UnitOfWork is my repository of my Context which is public interface IUnitOfWork:IDisposable { EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class; DbSet<TEntity> Set<TEntity>() where TEntity : class; int SaveChanges(bool acceptAllChangesOnSuccess); int SaveChanges(); void ExecuteSqlCommand(string query); DbCommand ExecuteCreateConnection(); void ExecuteOpenConnection(); void ExecuteCloseConnection(); void ExecuteSqlCommand(string query, params object[] parameters); Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()); Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()); } and my context is: public class Context : DbContext, IUnitOfWork { public Context(DbContextOptions<Context> options) : base(options) { } public virtual DbSet<Admin> Admin { set; get; } public virtual DbSet<Activity> Activities { set; get; } public virtual DbSet<ActivityCategory> ActivityCategories { set; get; } public virtual DbSet<ActivitiesPic> ActivitiesPics { set; get; } public virtual DbSet<ActivityRecord> ActivityRecords { set; get; } public virtual DbSet<Answer> Answers { set; get; } public virtual DbSet<Company> Companies { set; get; } public virtual DbSet<Form> Form { set; get; } public virtual DbSet<NazerOrTarah> NazerOrTarah { set; get; } //Added in 1398/12/13 public virtual DbSet<ReportDynamicTemplate> ReportDynamicTemplate { set; get; } public virtual DbSet<ReportTemplateForms> ReportTemplateForms { set; get; } public virtual DbSet<User> Users { set; get; } protected override void OnModelCreating(ModelBuilder builder) { builder.HasDefaultSchema("dbo"); builder.Entity<Activity>() .HasIndex(a => a.CompID); builder.Entity<ActivityRecord>() .HasIndex(a => new { a.ActivitiesID, a.NazerID }); builder.Entity<Answer>() .HasIndex(a => new { a.ActRecordsID, a.FormID }); builder.Entity<Form>() .HasIndex(a => new { a.ActivitiesID, a.ParentId }); // it should be placed here, otherwise it will rewrite the following settings! foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys())) { relationship.DeleteBehavior = DeleteBehavior.Restrict; } base.OnModelCreating(builder); } public void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class { Update(entity); } public void ExecuteSqlCommand(string query) { Database.ExecuteSqlCommand(query); } public DbCommand ExecuteCreateConnection() { return Database.GetDbConnection().CreateCommand(); } public void ExecuteOpenConnection() { Database.OpenConnection(); } public void ExecuteCloseConnection() { Database.CloseConnection(); } public void ExecuteSqlCommand(string query, params object[] parameters) { Database.ExecuteSqlCommand(query, parameters); } } What am I doing wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/63243207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Collecting custom Simple Analytics metadata in a Next.js app I am struggling to collect custom Simple Analytics metadata in my Next.js app. Looking at their docs, I can either set metadata on the window object (link) or add it via a callback function (link). My Next.js app looks as follows: _document.js import Document, { Html, Head, Main, NextScript } from 'next/document' export default class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> [...snip...] <script dangerouslySetInnerHTML={{ __html: `window.sa_event=window.sa_event||function(){a=[].slice.call(arguments);sa_event.q?sa_event.q.push(a):sa_event.q=[a]};` }}/> </Head> <body> <Main /> <NextScript /> // NOTE 3: Where can I define `func` so I have access to the router/query string params? <script async defer data-metadata-collector="func" src="https://scripts.simpleanalyticscdn.com/latest.js"></script> <noscript><img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt=""/></noscript> </body> </Html> ) } } page.js import Head from 'next/head' import { useRouter } from 'next/router' import Layout from '../components/layout' export default function Page() { const router = useRouter() const i = router.query.i return ( <> <Head> [...snip...] </Head> // NOTE 1: This does not work <script> sa_metadata = { i: i } </script> // NOTE 2: I cannot access `i` here <script dangerouslySetInnerHTML={{ __html: `window.sa_metadata={ i: i };` }}/> [...snip...] </> ) } As you can see, I tried two ways of setting metadata on window (NOTES 1 and 2) and I got stuck on the callback function (NOTE 3). Would appreciate any help in moving this forward.
{ "language": "en", "url": "https://stackoverflow.com/questions/75448951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to manipulate rendered data table that uses a reactive expression? I'm quite new with using Shiny. The code below is actually part of an Rmarkdown file with Shiny coding in it. I have an issue in handling reactive expressions within Shiny. Basically after calling a reactive expression, I can render or plot the expressions. What I cannot easily do is to manipulate that data after calling it. I've managed to render and output load_table(). This just tells it to load the csv file on a button click. See code below: ```{r UI inputs} wellPanel( fileInput("dataset", label = "Select a .csv File to upload", accept=c("text/csv", "text/comma-separated-values,text/plain", ".csv")), actionButton(inputId = "loadbutton", label = "Load Data") ) dataTableOutput("df") ``` ```{r Server Functions} load_table <- eventReactive(input$loadbutton, { # input$file1 will be NULL initially. After the user selects # and uploads a file, it will be a data frame with 'name', # 'size', 'type', and 'datapath' columns. The 'datapath' # column will contain the local filenames where the data can # be found. inFile <- input$dataset if (is.null(inFile)){ return(NULL)} else { read.csv(inFile$datapath)} }) output$df <- renderDataTable({ load_table() }) ``` My output An example of a file I loaded However, once the user selects and loads the data - I can't seem to manipulate it because the reactive expression load_table() doesn't work like a dataframe I'm used to. What I want to do next is to manipulate load_table() in any way possible. For example, filtering the data by date range or just simply adding additional columns. But I can't seem to manipulate load_table(). And I can't get the table without using a reactive function. I know there are similar questions already being asked on StackExchange, but it never seems to be what I need. What am I missing here? Regards Z
{ "language": "en", "url": "https://stackoverflow.com/questions/44287545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding another column to a numpy array I have two arrays of the following dimensions: a = (6,1) b = (6,4) I wish to add array (a) as additional column to array (c). Tried: c= np.column_stack([b,a]) and get an error due to mismatch of dimensions. A: Try: c = np.concatenate((b,a), axis=1) This assumes that a.shape = (6,1). If a.shape = (6,) then you can do: c = np.concatenate((b,a.reshape((6,1))), axis=1)
{ "language": "en", "url": "https://stackoverflow.com/questions/40360469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parse html page source with libcurl and C How can I print the source of a webpage, specified in curl_easy_setopt, without html tags? So, printing only the text in the source? A: Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools. The most general solution is to use a HTML parser. A good one in C is HTMLparser from libxml.
{ "language": "en", "url": "https://stackoverflow.com/questions/2162201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }