text
stringlengths
15
59.8k
meta
dict
Q: Binding Array of Structs with Strings in an Array of Structs I'm new to Swift so I hope this isn't something really silly. I'm trying to build an array of Structs, and one of the parameters is another Array with another Struct in it. I'm not sure if there is a better way, but I thought I was making really good progress right up till I tried to edit the embedded Struct. In it's simplified form it looks like this ... struct Group: Identifiable, Codable { var id = UUID() var name: String var number: Int var spaces: Bool var businesses: [Business] } struct Business: Identifiable, Codable { var id = UUID() var name: String var address: String var space: Int var enabled: Bool } These are used in a class with an Observable var that stored in User Defaults class GroupSettings: ObservableObject { @Published var groups = [Group]() { didSet { UserDefaults.standard.set(try? PropertyListEncoder().encode(groups), forKey: "groups") } } init() { if let configData = UserDefaults.standard.value(forKey: "groups") as? Data { if let userDefaultConfig = try? PropertyListDecoder().decode(Array<Group>.self, from: configData){ groups = userDefaultConfig } } } } Its passed in to my initial view and then I'm wanting to make an "Edit Detail" screen. When it gets to the edit detail screen, I can display the Business information in a Text display but I can't get it to working a TextField, it complains about can't convert a to a Binding, but the name from the initial Struct works fine, similar issues with the Int ... I pass a Group from the first view which has the array of Groups in to the detail screen with the @Binding property ... @Binding var group: Group var body: some View { TextField("", text: $group.name) <---- WORKS List { ForEach(self.group.businesses){ business in if business.enabled { Text(business.name) <---- WORKS TextField("", business.address) <---- FAILS TextField("", value: business.space, formatter: NumberFormatter()) <---- FAILS } else { Text("\(business.name) is disabled" } } } } Hopefully I've explained my self well enough, and someone can point out the error of my ways. I did try embedding the 2nd Struct inside the first but that didn't help. Thanks in advance! A: You could use indices inside the ForEach and then still use $group and accessing the index of the businesses via the index like that... List { ForEach(group.businesses.indices) { index in TextField("", text: $group.businesses[index].address) } } A: An alternative solution may be to use zip (or enumerated) to have both businesses and its indices: struct TestView: View { @Binding var group: Group var body: some View { TextField("", text: $group.name) List { let items = Array(zip(group.businesses.indices, group.businesses)) ForEach(items, id: \.1.id) { index, business in if business.enabled { Text(business.name) TextField("", text: $group.businesses[index].address) } else { Text("\(business.name) is disabled") } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65864121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: javascript function scope accessing "this" I have the following sample code. I'm trying to get the this.key inside the namespace function but it's always returning undefined despite me changing the function call, or using arrow approach etc. class Sample { key = ''; constructor(key) { this.key = key; } myNamespace = { saySomething: function(message) { console.log('message:', message); console.log('key:', this.key); } } getTheKey() { console.log('key', this.key); } } let sample = new Sample('thekey'); sample.myNamespace.saySomething('message'); // shows-> key: undefined sample.getTheKey(); // shows-> key: thekey A: The whole point of your myNamespace property seems more than just questionable, but if you insist and still need a function that is bound to your class instance, just bind the function in the constructor, or use an arrow function which does not have its own this, but keeps this whatever it pointed to at the time of definition: (code example demonstrates both): class Sample { key = ''; constructor(key) { this.key = key; this.myNamespace.saySomething = this.myNamespace.saySomething.bind(this); } myNamespace = { saySomething: function(message) { console.log('message:', message); console.log('key:', this.key); } } myOtherNamespace = { saySomething: (message) => { console.log('message:', message); console.log('key:', this.key); } } getTheKey() { console.log('key', this.key); } } let sample = new Sample('thekey'); sample.myNamespace.saySomething('message'); // shows-> key: thekey sample.myOtherNamespace.saySomething('other message'); // shows-> key: thekey sample.getTheKey(); // shows-> key: thekey A: "This" is pointing to two different things. "This" in your namespace function doesn't have a key value, but your constructed "sample" does - your getTheKey function accurately points to the correct "this". To be more specific, getTheKey points to the constructed sample as "this" and the function within saySomething is pointing to saySomething as "this". The constructed sample has a value for key and saySomething does not. You can use an arrow function instead, like so: myNamespace = { saySomething: (message) => { console.log('message:', message); console.log('key:', this.key); } to target your constructed sample instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/72133796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: OS X compile error : Undefined symbols for architecture x86_64: I download the dense trajectory project of Inria and I try to compile it on my mac. https://lear.inrialpes.fr/people/wang/download/dense_trajectory_release_v1.2.tar.gz I got a problem when using make the error I have is : === linking: release/DenseTrack === c++ -L/opt/lib -pipe -Wall -O3 -ggdb -o release/DenseTrack -lopencv_core -lopencv_highgui -lopencv_video -lopencv_imgproc -lavformat -lavdevice -lavutil -lavcodec -lswscale ld: warning: directory not found for option '-L/opt/lib' Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [release/DenseTrack] Error 1 I followed the README and installed opencv and ffmpeg. Does someone know how to handle this kind of error ? ** Edit ** the first warning was due to the compiler searching for my opencv lib directory, but the error of undefined symbol is still present: === linking: release/DenseTrack === c++ -L/usr/local/Cellar/opencv/3.4.1_5/lib -pipe -Wall -O3 -ggdb -o release/DenseTrack -lopencv_core -lopencv_highgui -lopencv_video -lopencv_imgproc -lavformat -lavdevice -lavutil -lavcodec -lswscale Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [release/DenseTrack] Error 1 the makefile of Inria : # set the binaries that have to be built TARGETS := DenseTrack Video # set the build configuration set BUILD := release #BUILD := debug # set bin and build dirs BUILDDIR := .build_$(BUILD) BINDIR := $(BUILD) # libraries LDLIBS = $(addprefix -l, $(LIBS) $(LIBS_$(notdir $*))) LIBS := \ opencv_core opencv_highgui opencv_video opencv_imgproc \ avformat avdevice avutil avcodec swscale # set some flags and compiler/linker specific commands CXXFLAGS = -pipe -D __STDC_CONSTANT_MACROS -D STD=std -Wall $(CXXFLAGS_$(BUILD)) -I. -I/opt/include CXXFLAGS_debug := -ggdb CXXFLAGS_release := -O3 -DNDEBUG -ggdb LDFLAGS = -L/usr/local/Cellar/opencv/3.4.1_5/lib -pipe -Wall $(LDFLAGS_$(BUILD)) LDFLAGS_debug := -ggdb LDFLAGS_release := -O3 -ggdb include make/generic.mk the generic.mk is : # # Copyright (C) 2009 Alexander Kl"aser # # This piece is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # This software has been downloaded from: # http://lear.inrialpes.fr/people/klaeser/software # # # Variables that need to be set in the Makefile that includes this file: # TARGETS all files that are exectuables without there .cpp extension # BUILDDIR temporary dir where things are compiled to (optional, by default ".build") # BINDIR dir where executables are linked to (optional, by default "bin") # SRCDIRS list of directories in which source files are located # this variable needs to be set if you do not have your source and # include files located in the same directory! # # Variables used for compiling/linking: # CXXFLAGS flags for compiling # LDFLAGS flags used for linking # LDLIBS list of libraries to be linked # CXX compiler linker (should be g++ by default) # # set paths for the dependency tool and gcc DEP = make/dep.py # set some standard directories in case they have not been set BUILDDIR ?= .build BINDIR ?= bin # all include files INCLUDES := $(addprefix $(BUILDDIR)/,$(TARGETS:=.l)) # # some general rules # .PHONY: all clean .PRECIOUS: $(BUILDDIR)/%.d all: $(BINDIR) $(addprefix $(BINDIR)/,$(notdir $(TARGETS))) @echo "=== done ===" $(INCLUDES): $(BUILDDIR) clean: @echo "=== cleaning up ===" @rm -rf $(BUILDDIR) $(BUILDDIR) $(BINDIR): @echo "=== creating directory: $@ ===" @mkdir -p $@ # # rules for creating dependency files # # dependencies of .cpp files on other files $(BUILDDIR)/%.d: %.cpp @echo "=== creating dependency file: $@ ===" @test -e $(dir $@) || mkdir -p $(dir $@) g++ $(CXXFLAGS) -MM -MT $(BUILDDIR)/$*.o -MT $(BUILDDIR)/$*.d -MF $@ $< # dependencies for the linking %.so.l %.l: %.d @echo "=== creating dependency file: $@ ===" @test -e $(dir $@) || mkdir -p $(dir $@) $(DEP) "$(BINDIR)/$(@F:.l=)" $*.l $(BUILDDIR) $< $(SRCDIRS) > $@ # # rules for compiling and linking # (link dependencies are defined in .l files) # # compiling $(BUILDDIR)/%.o: %.cpp @echo "=== compiling: $@ ===" @test -e $(dir $@) || mkdir -p $(dir $@) $(CXX) -fPIC $(CXXFLAGS) -c -o $@ $< # linking for shared libraries $(BINDIR)/%.so: @echo "=== linking: $@ ===" @rm -f $@ $(CXX) -shared $(LDFLAGS) -o $@ $(filter %.o, $^) $(LDLIBS) # linking $(BINDIR)/%: @echo "=== linking: $@ ===" @rm -f $@ $(CXX) $(LDFLAGS) -o $@ $(filter %.o, $^) $(LDLIBS) %: %.o %.h: ; %.hpp: ; %.c: ; %.cpp: ; # # include dependency files # ifneq ($(MAKECMDGOALS),clean) -include $(INCLUDES) endif When I do make there is the error because no main is found and so the binary files isn't created in the released directory, when I do make DenseTrack.cpp there is no error but nothing is done. Thanks. A: First, find where you actually installed the OpenCV libraries. So, let's take libopencv_core.dylib and look for it in a bunch of likely places, i.e. $HOME, /usr and /opt: find $HOME /usr /opt -name libopencv_core.dylib Sample Output /Users/mark/OpenCV/lib/libopencv_core.dylib Now we know where it is (on my system), so we can tell the linker: c++ -L/Users/mark/OpenCV/lib ...
{ "language": "en", "url": "https://stackoverflow.com/questions/50873217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Type 'string' is not assignable to type '""' when using BehaviorSubject I want to use BehaviorSubject and send Data from a service to a component but get the error in the component : Type 'string' is not assignable to type '""'. Service assembleDataSubject = new BehaviorSubject<string>(''); assembleData$ = this.assembleDataSubject.asObservable(); composeData(data: string) { this.assembleDataSubject.next(data); } Component data = ''; receiveData(serviceData) { this.service.assembleData$.subscribe( serviceData => (this.data = serviceData), // the error occurs at this.data error => console.log(error) ); return this.data; } I've read a lot of other posts to that kind of failure but I am not able to map the answers to my problem. For me it seems to be different than the other questions because string should be the same as ' ' and because I use kind of standard code. It is just the way BehaviorSubjects are used. If I change anything there I get other failure messages.
{ "language": "en", "url": "https://stackoverflow.com/questions/63519485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change text of delete button on UItable cell I want to change the text of the delete button in red that comes up when we swipe on a table cell. Is that possible?? if possible can you please tell how to do that. Thank you :) \m/ \m/ A: Yes, You can try like this, - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ return @"Name"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25175825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Evaluate arrays and assign values in Python I have two multi-dimensional arrays and I would like to evaluate and assign values for those matching and non-matching values. array_1 = array([[1,2,2], [1,2,3],[1,2,1]]) array_2 = array([[1,1,2], [2,2,3],[3,1,1]]) The idea is that for each member of array 1, if the value is the same, I want to assign 0 and it doesn't, I want to assign a different value. The logic is something like this. (array_1 ==1 and array_2 ==1) = 0 (array_1 ==1 and array_2 ==2) = 10 (array_1 ==1 and array_2 ==3) = 15 (array_1 ==2 and array_2 ==1) = 5 (array_1 ==2 and array_2 ==2) = 0 (array_1 ==2 and array_2 ==3) = 15 (array_1 ==3 and array_2 ==1) = 5 (array_1 ==3 and array_2 ==2) = 10 (array_1 ==3 and array_3 ==3) = 0 The over all goal is to detect a change. A brief description of this methodology is available on https://www.e-education.psu.edu/geog883/node/496 A: First: I am not familiar with the array format that you showed in your post. I have never seen an array instantiated in Python using just square brackets. That's not a function call. Second: Your problem may not be fully specified. However: if you have shown us all the possible values that you can have in your input arrays, then only 1, 2, and 3 are possible. In that case, there are only 9 possible pairings of elements from array_1 and array_2, and the values you want as outputs can easily be stored in a 3 x 3 lookup table. Finally: I use Numpy. You seem to want arrays, and Numpy is very common and handles arrays well. import numpy as np from itertools import product arr1 = np.array([[1,2,2],[1,2,3],[1,2,1]], dtype=int) arr2 = np.array([[1,1,2],[2,2,3],[3,1,1]], dtype=int) lookup = np.array(((0,10,15),(5,0,15),(5,10,0)), dtype=int) result = np.zeros_like(arr1) for r, c in product(*[range(x) for x in arr1.shape]): a, b = arr1[r,c], arr2[r,c] result[r,c] = lookup[a-1,b-1] print(arr1, "\n") print(arr2, "\n") print(result) Here's the output: [[1 2 2] [1 2 3] [1 2 1]] [[1 1 2] [2 2 3] [3 1 1]] [[ 0 5 0] [10 0 0] [15 5 0]] A: You can do this in a list comprehension: Use a conditional expression to produce your values. You put the if, else statement first and then iterate through to replace the values. I have created a list and pulled a number at random from that list. import random array_1 = [[1, 2, 2], [1, 2, 3], [1, 2, 1]] array_2 = [[1, 1, 2], [2, 2, 3], [3, 1, 1]] lst = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] res = [[random.choice(lst) if i != j else 0 for i, j in zip(a, b)] for a, b in zip(array_1, array_2)] for i in res: print(i) Returns: [0, 25, 0] [50, 0, 0] [35, 45, 0]
{ "language": "en", "url": "https://stackoverflow.com/questions/49969215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Recursion to make sequences of a word I was given a homework assignment to find all possible sequences of a given word. eg. if word = 'abc', the below code would return ['a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac', 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']. However, this feels inefficient. I'm just starting to learn recursion, so I'm not sure if there is a better or more efficient way to produce these sequences? edit: I think it's necessary to add a couple things as I kept working and reading the material * *Duplicates are fine, those are sorted out in a separate function *Each value is unique, so sequence 'aab' should produce two 'aa' sequences def gen_all_strings(word): if len(word) == 1: return list(word) else: main_list = list() for idx in range(len(word)): cur_val = word[idx] rest = gen_all_strings(word[:idx] + word[idx+1:]) main_list.append(cur_val) for seq in rest: main_list.append(cur_val + seq) return main_list A: Itertools and list comprehensions are good for breaking stuff down like this. import itertools ["".join(x) for y in range(1, len(word) + 1) for x in itertools.permutations(word, y)]
{ "language": "en", "url": "https://stackoverflow.com/questions/52859965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mass inserting into model in rails, how to auto increment id field? I have a model for stocks and a model for stock_price_history. I want to mass insert with this sqlstatement = "INSERT INTO stock_histories SELECT datapoint1 AS id, datapoint2 AS `date` ...UNION SELECT datapoint9,10,11,12,13,14,15,16, UNION SELECT datapoint 17... etc" ActiveRecord::Base.connection.execute sqlstatement However, I don't actually want to use datapoint1 AS id. If I leave it blank I get an error that my model has 10 fields and I'm inserting only 9 and that it is missing the primary key. Is there a way to force an auto increment on the id when inserting by SQL? Edit: Bonus question cause I'm a noob. I am developing in SQLite3 and deploying to a Posgres (i.e. Heroku), Will I need to modify the above mass insert statement so it's for a posgres database? 2nd edit: my initial question had Assets and AssetHistory instead of Stocks and Stock_Histories. I changed it to Stocks / Stock price histories because I thought it was more intuitive to understand. Therefore some answers refer to Asset Histories for this reason. A: You can change your SQL and be more explicit about which fields you're inserting, and leave id out of the list: insert into asset_histories (date) select datapoint2 as `date` ...etc Here's a long real example: jim=# create table test1 (id serial not null, date date not null, name text not null); NOTICE: CREATE TABLE will create implicit sequence "test1_id_seq" for serial column "test1.id" CREATE TABLE jim=# create table test2 (id serial not null, date date not null, name text not null); NOTICE: CREATE TABLE will create implicit sequence "test2_id_seq" for serial column "test2.id" CREATE TABLE jim=# insert into test1 (date, name) values (now(), 'jim'); INSERT 0 1 jim=# insert into test1 (date, name) values (now(), 'joe'); INSERT 0 1 jim=# insert into test1 (date, name) values (now(), 'bob'); INSERT 0 1 jim=# select * from test1; id | date | name ----+------------+------ 1 | 2013-03-14 | jim 2 | 2013-03-14 | joe 3 | 2013-03-14 | bob (3 rows) jim=# insert into test2 (date, name) select date, name from test1 where name <> 'jim'; INSERT 0 2 jim=# select * from test2; id | date | name ----+------------+------ 1 | 2013-03-14 | joe 2 | 2013-03-14 | bob (2 rows) As you can see, only the selected rows were inserted, and they were assigned new id values in table test2. You'll have to be explicit about all the fields you want to insert, and ensure that the ordering of the insert and the select match. Having said all that, you might want to look into the activerecord-import gem, which makes this sort of thing a lot more Railsy. Assuming you have a bunch of new AssetHistory objects (not persisted yet), you could insert them all with: asset_histories = [] asset_histories << AssetHistory.new date: some_date asset_histories << AssetHistory.new date: some_other_date AssetHistory.import asset_histories That will generate a single efficient insert into the table, and handle the id for you. You'll still need to query some data and construct the objects, which may not be faster than doing it all with raw SQL, but may be a better alternative if you've already got the data in Ruby objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/15420599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vertically centering two divs within body This is a simplified version of a more complex problem. Suppose there are two divs within the body, which have to be vertically centered. Because of some other requirements DOM can't change. So only by changing css I need to vertically align them center. I have tried many other stackoverflow posts but so far couldn't make it work. Here is my code: <!DOCTYPE html> <html> <head> <style> body{ } .div1{ display: block; background: red; width: 300px; } .div2{ display: block; background: green; width: 300px; } </style> </head> <body> <div class="div1"> <p>This is div1</p> </div> <div class="div2"> <p>This is div2</p> </div> </body> </html> A: This is possible using flexbox. html, body { height: 100%; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; } See this CodePen
{ "language": "en", "url": "https://stackoverflow.com/questions/31976781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add default option to plucked array in laravel I want to add default option at the start of a plucked array in Laravel 8. How can I achieve this? $departments = Department::pluck('name', 'id')->all(); A: prepend() $departments = Department::pluck('name', 'id')->prepend('Select Department', '');
{ "language": "en", "url": "https://stackoverflow.com/questions/68195448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tell me a fix for ER_BAD_NULL_ERROR in Node.js, mysql crud operation I am an absolute novice at Node.js. So, as I'm learning, I ran into this problem. I am adding codes from backend for CRUD (This index.js may seem incomplete, because I faced the problem halfway and then started seeking the solution.) package.json { "name": "backend", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon index.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2", "mysql": "^2.18.1", "nodemon": "^2.0.20" } } index.js import express from 'express'; import mysql from "mysql"; const app = express(); const db = mysql.createConnection({ host: "localhost", user: "root", password: "akdkfjdkfj;a", database: "online_sustainability_db" }); app.use(express.json()); app.get("/", (req, res) =>{ res.json("Hello. You are connected to backend."); }); app.get("/data", (req, res) =>{ const query = "SELECT * FROM online_sustainability_db.idea_proposers"; db.query(query, (err, data)=>{ if(err) return res.json(err); else return res.json(data); }) }); app.post("/data", (req, res)=>{ const q = "INSERT INTO idea_proposers (`last_name`, `first_name`, `account_no`, `github_repository_link`, `submission_id`) VALUES (?, ?, ?, ?, ?)"; const last_name = req.body.last_name; const first_name = req.body.first_name; const account_no = req.body.account_no; const github_link = req.body.github_repository_link; const submission_id = req.body.submission_id; db.query(q, [last_name, first_name, account_no, github_link, submission_id], (err, data)=>{ if(err) return res.json(err); else return res.json("Provided data were recorded successfully."); }); }); app.listen(8800, ()=>{ console.log("Connected to backend!"); }); The following image is from postman application. This is the error I am getting. Please, help me fixing it. This is the description of the table I am trying to post the data in. I tried doing some syntactical change and running the code several times. Well, it didn't work. I even looked for resources online, but I couldn't find any similar. A: Kindly select the JSON from Postman whenever you want to send the JSON data. currently, you're sending data as a text.
{ "language": "en", "url": "https://stackoverflow.com/questions/75028021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSURLConnection's connectionDidFinishLoading before redirects In my iOS 5 app, I am trying to resolve redirects of a URL to its the final URL, and only then actually try to open the link in Safari. I'm using code along these lines: http://developer.apple.com/library/ios/#qa/qa1629/_index.html If I use a bitly link to do the redirect to the iTunes store, 'connectionDidFinishLoading' does end up getting called with my iTunes store link. Perfect. If I instead use a redirect on my website 'connectionDidFinishLoading' is always called too early - before the redirects have resolved. That means that safari flashes up redirects a second or so later, and then the app store opens. I don't know if i'm having a problem because my web server is just too slow? (maybe takes 1-2 seconds) Has anybody else bumped into this problem or have advice for how to proceed? Many thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/8529987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: list being printed out weirdly python I have a list like this [796, 829, 1159, 1162] I also have a list like this: ['144 154', '145 151', '145 152', '145 153', '145 154', '146 152', '146 153', '146 154', '147 153', '147 154'] These are not to scale What I want to do is use the first lists elements as index for the last array I have tried this piece of code: contacts = [] for i in findres: contacts += rulelines[i] print contacts where findres is the first list and rulelines is the last list However this prints the contacts list out weirdly: ['5', ' ', '7', '2', '5', ' ', '1', '0', '5', '7', ' ', '1', '5', '0', '7', ' ', '1', '5', '3'] I'm sure its easy but where am I going wrong?? The desirable output I believe is ['5 72','5 105', '7 150',7 153'] I have not put down all of the list elements as there are over 100 elements in each A: Looks like when you assign contacts = rulelines[i] you're actually assigning the rulelines[i] string. You should do contacts.append(rulelines[i]) to add the the contact to the list, otherwise you're constantly overwriting over the last assignment. A: Use this as a template: findres = [5, 7, 15, 22] contacts = list('abcdefghijklmnopqrstuvwxyz') # dummy list result = [ contacts[index] for index in findres ] print result # ['f', 'h', 'p', 'w'] A: If I understand correctly, you need to extract the first number in every elements of findres first. Then, use those extracted numbers as an index for another array >>> findres = ['144 154', '145 151', '145 152', '145 153', '145 154', '146 152', '146 153', '146 154', '147 153', '147 154'] >>> first_elements = [c.split()[0] for c in findres] >>> print first_elements ['144', '145', '145', '145', '145', '146', '146', '146', '147', '147'] >>> contact = [] >>> for i in first_elements: contacts.append(rulelines[i])
{ "language": "en", "url": "https://stackoverflow.com/questions/16199100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lua get Instance in an instance where the name matches a string I am a javascript developer and am starting to use lua. When i write code such as: var obj = { prop: "Hello World" } , propName = "prop"; //and to fetch the value: console.log(obj[propName]); /as apposed to: console.log(obj.propName) //undefined in lua is there any way to get a property of an Instance that has the same name as a string. --i.e: game.Workspace.<INSERT VARIABLE VALUE HERE>.Humanoid.WalkSpeed = 100 P.S i am using lua for roblox if that makes any changes A: I don't known roblox but try this: game.Workspace[myvar].Humanoid.WalkSpeed = 100 In this sense, Lua is like JavaScript.
{ "language": "en", "url": "https://stackoverflow.com/questions/58702596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What characters can be used for up/down triangle (arrow without stem) for display in HTML? I'm looking for a HTML or ASCII character which is a triangle pointing up or down so that I can use it as a toggle switch. I found โ†‘ (&uarr;), and โ†“ (&darr;) - but those have a narrow stem. I'm looking just for the HTML arrow "head". A: There are literal arrowheads in the Spacing Modifier Letters block: U+02C2 ห‚ &#706; Modifier Letter Left Arrowhead U+02C3 หƒ &#707; Modifier Letter Right Arrowhead U+02C4 ห„ &#708; Modifier Letter Up Arrowhead U+02C5 ห… &#709; Modifier Letter Down Arrowhead A: Since you're using these arrows for a toggle switch you may want to consider creating these arrows with an html element using the following styles instead of unicode characters. .upparrow { height: 0; width: 0; border: 4px solid transparent; border-bottom-color: #000; } .downarrow { height: 0; width: 0; border: 4px solid transparent; border-top-color: #000; } http://jsfiddle.net/FrsGR/ A: For HTML Entities โ—„ = &#9668; โ–บ = &#9658; โ–ผ = &#9660; โ–ฒ = &#9650; A: OPTION 1: UNICODE COLUMN SORT ARROWS I found this one very handy for a single character column sorter. (Looks good upscaled) &#x21D5; = โ‡• IMPORTANT NOTE (When using Unicode symbols) Unicode support varies dependant on the symbol of choice, browser and the font family. If you find your chosen symbol does not work in some browsers then try using a different font-family. Microsoft recommends "Segoe UI Symbol" however it would be wise to include the font with your website as not many people have it on their computers. Open this page in other browsers to see which symbols render with the default font. Some more unicode arrows. To use them: * *Copy them right off the page. *Use the code above each row inserting the corresponding hexadeximal number before the closing semi-colon relating to it's poition in the row. Last Digit 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F &#x219; โ† โ†‘ โ†’ โ†“ โ†” โ†• โ†– โ†— โ†˜ โ†™ โ†š โ†› โ†œ โ† โ†ž โ†Ÿ ___ &#x21A; โ†  โ†ก โ†ข โ†ฃ โ†ค โ†ฅ โ†ฆ โ†ง โ†จ โ†ฉ โ†ช โ†ซ โ†ฌ โ†ญ โ†ฎ โ†ฏ ___ &#x21B; โ†ฐ โ†ฑ โ†ฒ โ†ณ โ†ด โ†ต โ†ถ โ†ท โ†ธ โ†น โ†บ โ†ป โ†ผ โ†ฝ โ†พ โ†ฟ ___ &#x21C; โ‡€ โ‡ โ‡‚ โ‡ƒ โ‡„ โ‡… โ‡† โ‡‡ โ‡ˆ โ‡‰ โ‡Š โ‡‹ โ‡Œ โ‡ โ‡Ž โ‡ ___ &#x21D; โ‡ โ‡‘ โ‡’ โ‡“ โ‡” โ‡• โ‡– โ‡— โ‡˜ โ‡™ โ‡š โ‡› โ‡œ โ‡ โ‡ž โ‡Ÿ ___ &#x21E; โ‡  โ‡ก โ‡ข โ‡ฃ โ‡ค โ‡ฅ โ‡ฆ โ‡ง โ‡จ โ‡ฉ โ‡ช โ‡ซ โ‡ฌ โ‡ญ โ‡ฎ โ‡ฏ ___ &#x21F; โ‡ฐ โ‡ฑ โ‡ฒ โ‡ณ โ‡ด โ‡ต โ‡ถ โ‡ท โ‡ธ โ‡น โ‡บ โ‡ป โ‡ผ โ‡ฝ โ‡พ โ‡ฟ ___ Additional HTML unicode symbols A selected list of other helpful Unicode icons/symbols. U+2302 โŒ‚ HOUSE U+2303 โŒƒ UP ARROWHEAD U+2304 โŒ„ DOWN ARROWHEAD U+2305 โŒ… PROJECTIVE U+2306 โŒ† PERSPECTIVE U+2307 โŒ‡ WAVY LINE U+2315 โŒ• TELEPHONE RECORDER U+2316 โŒ– POSITION INDICATOR U+2317 โŒ— VIEWDATA SQUARE U+2318 โŒ˜ PLACE OF INTEREST SIGN U+231A โŒš WATCH U+231B โŒ› HOURGLASS U+2326 โŒฆ ERASE TO THE RIGHT U+2327 โŒง X IN A RECTANGLE BOX U+2328 โŒจ KEYBOARD U+2329 โŒฉ LEFT-POINTING ANGLE BRACKET U+232A โŒช RIGHT-POINTING ANGLE BRACKET U+232B โŒซ ERASE TO THE LEFT U+23E9 โฉ BLACK RIGHT-POINTING DOUBLE TRIANGLE U+23EA โช BLACK LEFT-POINTING DOUBLE TRIANGLE U+23EB โซ BLACK UP-POINTING DOUBLE TRIANGLE U+23EC โฌ BLACK DOWN-POINTING DOUBLE TRIANGLE U+23ED โญ BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR U+23EE โฎ BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR U+23EF โฏ BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR U+23F0 โฐ ALARM CLOCK U+23F1 โฑ STOPWATCH U+23F2 โฒ TIMER CLOCK U+23F3 โณ HOURGLASS WITH FLOWING SAND U+2600 โ˜€ BLACK SUN WITH RAYS U+2601 โ˜ CLOUD U+2602 โ˜‚ UMBRELLA U+2603 โ˜ƒ SNOWMAN U+2604 โ˜„ COMET U+2605 โ˜… BLACK STAR U+2606 โ˜† WHITE STAR U+2607 โ˜‡ LIGHTNING U+2608 โ˜ˆ THUNDERSTORM U+2609 โ˜‰ SUN U+260A โ˜Š ASCENDING NODE U+260B โ˜‹ DESCENDING NODE U+260C โ˜Œ CONJUNCTION U+260D โ˜ OPPOSITION U+260E โ˜Ž BLACK TELEPHONE U+260F โ˜ WHITE TELEPHONE U+2610 โ˜ BALLOT BOX U+2611 โ˜‘ BALLOT BOX WITH CHECK U+2612 โ˜’ BALLOT BOX WITH X U+2613 โ˜“ SALTIRE U+2614 โ˜” UMBRELLA WITH RAINDROPS U+2615 โ˜• HOT BEVERAGE U+2616 โ˜– WHITE SHOGI PIECE U+2617 โ˜— BLACK SHOGI PIECE U+2618 โ˜˜ SHAMROCK U+2619 โ˜™ REVERSED ROTATED FLORAL HEART BULLET U+261A โ˜š BLACK LEFT-POINTING INDEX U+261B โ˜› BLACK RIGHT-POINTING INDEX U+261C โ˜œ WHITE LEFT POINTING INDEX U+261D โ˜ WHITE UP POINTING INDEX U+261E โ˜ž WHITE RIGHT POINTING INDEX U+261F โ˜Ÿ WHITE DOWN POINTING INDEX U+2620 โ˜  SKULL AND CROSSBONES U+2621 โ˜ก CAUTION SIGN U+2622 โ˜ข RADIOACTIVE SIGN U+2623 โ˜ฃ BIOHAZARD SIGN U+262A โ˜ช STAR AND CRESCENT U+262B โ˜ซ FARSI SYMBOL U+262C โ˜ฌ ADI SHAKTI U+262D โ˜ญ HAMMER AND SICKLE U+262E โ˜ฎ PEACE SYMBOL U+262F โ˜ฏ YIN YANG U+2638 โ˜ธ WHEEL OF DHARMA U+2639 โ˜น WHITE FROWNING FACE U+263A โ˜บ WHITE SMILING FACE U+263B โ˜ป BLACK SMILING FACE U+263C โ˜ผ WHITE SUN WITH RAYS U+263D โ˜ฝ FIRST QUARTER MOON U+263E โ˜พ LAST QUARTER MOON U+263F โ˜ฟ MERCURY U+2640 โ™€ FEMALE SIGN U+2641 โ™ EARTH U+2642 โ™‚ MALE SIGN U+2643 โ™ƒ JUPITER U+2644 โ™„ SATURN U+2645 โ™… URANUS U+2646 โ™† NEPTUNE U+2647 โ™‡ PLUTO U+2648 โ™ˆ ARIES U+2649 โ™‰ TAURUS U+264A โ™Š GEMINI U+264B โ™‹ CANCER U+264C โ™Œ LEO U+264D โ™ VIRGO U+264E โ™Ž LIBRA U+264F โ™ SCORPIUS U+2650 โ™ SAGITTARIUS U+2651 โ™‘ CAPRICORN U+2652 โ™’ AQUARIUS U+2653 โ™“ PISCES U+2654 โ™” WHITE CHESS KING U+2655 โ™• WHITE CHESS QUEEN U+2656 โ™– WHITE CHESS ROOK U+2657 โ™— WHITE CHESS BISHOP U+2658 โ™˜ WHITE CHESS KNIGHT U+2659 โ™™ WHITE CHESS PAWN U+265A โ™š BLACK CHESS KING U+265B โ™› BLACK CHESS QUEEN U+265C โ™œ BLACK CHESS ROOK U+265D โ™ BLACK CHESS BISHOP U+265E โ™ž BLACK CHESS KNIGHT U+265F โ™Ÿ BLACK CHESS PAWN U+2660 โ™  BLACK SPADE SUIT U+2661 โ™ก WHITE HEART SUIT U+2662 โ™ข WHITE DIAMOND SUIT U+2663 โ™ฃ BLACK CLUB SUITE U+2664 โ™ค WHITE SPADE SUIT U+2665 โ™ฅ BLACK HEART SUIT U+2666 โ™ฆ BLACK DIAMOND SUIT U+2667 โ™ง WHITE CLUB SUITE U+2668 โ™จ HOT SPRINGS U+2669 โ™ฉ QUARTER NOTE U+266A โ™ช EIGHTH NOTE U+266B โ™ซ BEAMED EIGHTH NOTES U+266C โ™ฌ BEAMED SIXTEENTH NOTES U+266D โ™ญ MUSIC FLAT SIGN U+266E โ™ฎ MUSIC NATURAL SIGN U+266F โ™ฏ MUSIC SHARP SIGN U+267A โ™บ RECYCLING SYMBOL FOR GENERIC MATERIALS U+267B โ™ป BLACK UNIVERSAL RECYCLING SYMBOL U+267C โ™ผ RECYCLED PAPER SYMBOL U+267D โ™ฝ PARTIALLY-RECYCLED PAPER SYMBOL U+267E โ™พ PERMANENT PAPER SIGN U+267F โ™ฟ WHEELCHAIR SYMBOL U+2680 โš€ DIE FACE-1 U+2681 โš DIE FACE-2 U+2682 โš‚ DIE FACE-3 U+2683 โšƒ DIE FACE-4 U+2684 โš„ DIE FACE-5 U+2685 โš… DIE FACE-6 U+2686 โš† WHITE CIRCLE WITH DOT RIGHT U+2687 โš‡ WHITE CIRCLE WITH TWO DOTS U+2688 โšˆ BLACK CIRCLE WITH WHITE DOT RIGHT U+2689 โš‰ BLACK CIRCLE WITH TWO WHITE DOTS U+268A โšŠ MONOGRAM FOR YANG U+268B โš‹ MONOGRAM FOR YIN U+268C โšŒ DIGRAM FOR GREATER YANG U+268D โš DIGRAM FOR LESSER YIN U+268E โšŽ DIGRAM FOR LESSER YANG U+268F โš DIGRAM FOR GREATER YIN U+2690 โš WHITE FLAG U+2691 โš‘ BLACK FLAG U+2692 โš’ HAMMER AND PICK U+2693 โš“ ANCHOR U+2694 โš” CROSSED SWORDS U+2695 โš• STAFF OF AESCULAPIUS U+2696 โš– SCALES U+2697 โš— ALEMBIC U+2698 โš˜ FLOWER U+2699 โš™ GEAR U+269A โšš STAFF OF HERMES U+269B โš› ATOM SYMBOL U+269C โšœ FLEUR-DE-LIS U+269D โš OUTLINED WHITE STAR U+269E โšž THREE LINES CONVERGING RIGHT U+269F โšŸ THREE LINES CONVERGING LEFT U+26A0 โš  WARNING SIGN U+26A1 โšก HIGH VOLTAGE SIGN U+26A2 โšข DOUBLED FEMALE SIGN U+26A3 โšฃ DOUBLED MALE SIGN U+26A4 โšค INTERLOCKED FEMALE AND MALE SIGN U+26A5 โšฅ MALE AND FEMALE SIGN U+26A6 โšฆ MALE WITH STROKE SIGN U+26A7 โšง MALE WITH STROKE AND MALE AND FEMALE SIGN U+26A8 โšจ VERTICAL MALE WITH STROKE SIGN U+26A9 โšฉ HORIZONTAL MALE WITH STROKE SIGN U+26AA โšช MEDIUM WHITE CIRCLE U+26AB โšซ MEDIUM BLACK CIRCLE U+26BD โšฝ SOCCER BALL U+26BE โšพ BASEBALL U+26BF โšฟ SQUARED KEY U+26C0 โ›€ WHITE DRAUGHTSMAN U+26C1 โ› WHITE DRAUGHTS KING U+26C2 โ›‚ BLACK DRAUGHTSMAN U+26C3 โ›ƒ BLACK DRAUGHTS KING U+26C4 โ›„ SNOWMAN WITHOUT SNOW U+26C5 โ›… SUN BEHIND CLOUD U+26C6 โ›† RAIN U+26C7 โ›‡ BLACK SNOWMAN U+26C8 โ›ˆ THUNDER CLOUD AND RAIN U+26C9 โ›‰ TURNED WHITE SHOGI PIECE U+26CA โ›Š TURNED BLACK SHOGI PIECE U+26CB โ›‹ WHITE DIAMOND IN SQUARE U+26CC โ›Œ CROSSING LANES U+26CD โ› DISABLED CAR U+26CE โ›Ž OPHIUCHUS U+26CF โ› PICK U+26D0 โ› CAR SLIDING U+26D1 โ›‘ HELMET WITH WHITE CROSS U+26D2 โ›’ CIRCLED CROSSING LANES U+26D3 โ›“ CHAINS U+26D4 โ›” NO ENTRY U+26D5 โ›• ALTERNATE ONE-WAY LEFT WAY TRAFFIC U+26D6 โ›– BLACK TWO-WAY LEFT WAY TRAFFIC U+26D7 โ›— WHITE TWO-WAY LEFT WAY TRAFFIC U+26D8 โ›˜ BLACK LEFT LANE MERGE U+26D9 โ›™ WHITE LEFT LANE MERGE U+26DA โ›š DRIVE SLOW SIGN U+26DB โ›› HEAVY WHITE DOWN-POINTING TRIANGLE U+26DC โ›œ LEFT CLOSED ENTRY U+26DD โ› SQUARED SALTIRE U+26DE โ›ž FALLING DIAGONAL IN WHITE CIRCLE IN BLACK SQUARE U+26DF โ›Ÿ BLACK TRUCK U+26E0 โ›  RESTRICTED LEFT ENTRY-1 U+26E1 โ›ก RESTRICTED LEFT ENTRY-2 U+26E2 โ›ข ASTRONOMICAL SYMBOL FOR URANUS U+26E3 โ›ฃ HEAVY CIRCLE WITH STROKE AND TWO DOTS ABOVE U+26E4 โ›ค PENTAGRAM U+26E5 โ›ฅ RIGHT-HANDED INTERLACED PENTAGRAM U+26E6 โ›ฆ LEFT-HANDED INTERLACED PENTAGRAM U+26E7 โ›ง INVERTED PENTAGRAM U+26E8 โ›จ BLACK CROSS ON SHIELD U+26E9 โ›ฉ SHINTO SHRINE U+26EA โ›ช CHURCH U+26EB โ›ซ CASTLE U+26EC โ›ฌ HISTORIC SITE U+26ED โ›ญ GEAR WITHOUT HUB U+26EE โ›ฎ GEAR WITH HANDLES U+26EF โ›ฏ MAP SYMBOL FOR LIGHTHOUSE U+26F0 โ›ฐ MOUNTAIN U+26F1 โ›ฑ UMBRELLA ON GROUND U+26F2 โ›ฒ FOUNTAIN U+26F3 โ›ณ FLAG IN HOLE U+26F4 โ›ด FERRY U+26F5 โ›ต SAILBOAT U+26F6 โ›ถ SQUARE FOUR CORNERS U+26F7 โ›ท SKIER U+26F8 โ›ธ ICE SKATE U+26F9 โ›น PERSON WITH BALL U+26FA โ›บ TENT U+26FD โ›ฝ FUEL PUMP U+26FE โ›พ CUP ON BLACK SQUARE U+26FF โ›ฟ WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE U+2701 โœ UPPER BLADE SCISSORS U+2702 โœ‚ BLACK SCISSORS U+2703 โœƒ LOWER BLADE SCISSORS U+2704 โœ„ WHITE SCISSORS U+2705 โœ… WHITE HEAVY CHECK MARK U+2706 โœ† TELEPHONE LOCATION SIGN U+2707 โœ‡ TAPE DRIVE U+2708 โœˆ AIRPLANE U+2709 โœ‰ ENVELOPE U+270A โœŠ RAISED FIST U+270B โœ‹ RAISED HAND U+270C โœŒ VICTORY HAND U+270D โœ WRITING HAND U+270E โœŽ LOWER RIGHT PENCIL U+270F โœ PENCIL U+2710 โœ UPPER RIGHT PENCIL U+2711 โœ‘ WHITE NIB U+2712 โœ’ BLACK NIB U+2713 โœ“ CHECK MARK U+2714 โœ” HEAVY CHECK MARK U+2715 โœ• MULTIPLICATION X U+2716 โœ– HEAVY MULTIPLICATION X U+2717 โœ— BALLOT X U+2718 โœ˜ HEAVY BALLOT X U+2719 โœ™ OUTLINED GREEK CROSS U+271A โœš HEAVY GREEK CROSS U+271B โœ› OPEN CENTRE CROSS U+271C โœœ HEAVY OPEN CENTRE CROSS U+271D โœ LATIN CROSS U+271E โœž SHADOWED WHITE LATIN CROSS U+271F โœŸ OUTLINED LATIN CROSS U+2720 โœ  MALTESE CROSS U+2721 โœก STAR OF DAVID U+2722 โœข FOUR TEARDROP-SPOKED ASTERISK U+2723 โœฃ FOUR BALLOON-SPOKED ASTERISK U+2724 โœค HEAVY FOUR BALLOON-SPOKED ASTERISK U+2725 โœฅ FOUR CLUB-SPOKED ASTERISK U+2726 โœฆ BLACK FOUR POINTED STAR U+2727 โœง WHITE FOUR POINTED STAR U+2728 โœจ SPARKLES U+2729 โœฉ STRESS OUTLINED WHITE STAR U+272A โœช CIRCLED WHITE STAR U+272B โœซ OPEN CENTRE BLACK STAR U+272C โœฌ BLACK CENTRE WHITE STAR U+272D โœญ OUTLINED BLACK STAR U+272E โœฎ HEAVY OUTLINED BLACK STAR U+272F โœฏ PINWHEEL STAR U+2730 โœฐ SHADOWED WHITE STAR U+2731 โœฑ HEAVY ASTERISK U+2732 โœฒ OPEN CENTRE ASTERISK U+2733 โœณ EIGHT SPOKED ASTERISK U+2734 โœด EIGHT POINTED BLACK STAR U+2735 โœต EIGHT POINTED PINWHEEL STAR U+2736 โœถ SIX POINTED BLACK STAR U+2737 โœท EIGHT POINTED RECTILINEAR BLACK STAR U+2738 โœธ HEAVY EIGHT POINTED RECTILINEAR BLACK STAR U+2739 โœน TWELVE POINTED BLACK STAR U+273A โœบ SIXTEEN POINTED ASTERISK U+273B โœป TEARDROP-SPOKED ASTERISK U+273C โœผ OPEN CENTRE TEARDROP-SPOKED ASTERISK U+273D โœฝ HEAVY TEARDROP-SPOKED ASTERISK U+273E โœพ SIX PETALLED BLACK AND WHITE FLORETTE U+273F โœฟ BLACK FLORETTE U+2740 โ€ WHITE FLORETTE U+2741 โ EIGHT PETALLED OUTLINED BLACK FLORETTE U+2742 โ‚ CIRCLED OPEN CENTRE EIGHT POINTED STAR U+2743 โƒ HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK U+2744 โ„ SNOWFLAKE U+2745 โ… TIGHT TRIFOLIATE SNOWFLAKE U+2746 โ† HEAVY CHEVRON SNOWFLAKE U+2747 โ‡ SPARKLE U+2748 โˆ HEAVY SPARKLE U+2749 โ‰ BALLOON-SPOKED ASTERISK U+274A โŠ EIGHT TEARDROP-SPOKED PROPELLER ASTERISK U+274B โ‹ HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK U+274C โŒ CROSS MARK U+274D โ SHADOWED WHITE CIRCLE U+274E โŽ NEGATIVE SQUARED CROSS MARK U+2753 โ“ BLACK QUESTION MARK ORNAMENT U+2754 โ” WHITE QUESTION MARK ORNAMENT U+2755 โ• WHITE EXCLAMATION MARK ORNAMENT U+2756 โ– BLACK DIAMOND MINUS WHITE X U+2757 โ— HEAVY EXCLAMATION MARK SYMBOL U+275B โ› HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT U+275C โœ HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT U+275D โ HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT U+275E โž HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT U+275F โŸ HEAVY LOW SINGLE COMMA QUOTATION MARK ORNAMENT U+2760 โ  HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT U+2761 โก CURVED STEM PARAGRAPH SIGN ORNAMENT U+2762 โข HEAVY EXCLAMATION MARK ORNAMENT U+2763 โฃ HEAVY HEART EXCLAMATION MARK ORNAMENT U+2764 โค HEAVY BLACK HEART U+2765 โฅ ROTATED HEAVY BLACK HEART BULLET U+2766 โฆ FLORAL HEART U+2767 โง ROTATED FLORAL HEART BULLET U+276C โฌ MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT U+276D โญ MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT U+276E โฎ HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT U+276F โฏ HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT U+2770 โฐ HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT U+2771 โฑ HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT U+2794 โž” HEAVY WIDE-HEADED RIGHTWARDS ARROW U+2795 โž• HEAVY PLUS SIGN U+2796 โž– HEAVY MINUS SIGN U+2797 โž— HEAVY DIVISION SIGN U+2798 โž˜ HEAVY SOUTH EAST ARROW U+2799 โž™ HEAVY RIGHTWARDS ARROW U+279A โžš HEAVY NORTH EAST ARROW U+279B โž› DRAFTING POINT RIGHTWARDS ARROW U+279C โžœ HEAVY ROUND-TIPPED RIGHTWARDS ARROW U+279D โž TRIANGLE-HEADED RIGHTWARDS ARROW U+279E โžž HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW U+279F โžŸ DASHED TRIANGLE-HEADED RIGHTWARDS ARROW U+27A0 โž  HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW U+27A1 โžก BLACK RIGHTWARDS ARROW U+27A2 โžข THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD U+27A3 โžฃ THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD U+27A4 โžค BLACK RIGHTWARDS ARROWHEAD U+27A5 โžฅ HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW U+27A6 โžฆ HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW U+27A7 โžง SQUAT BLACK RIGHTWARDS ARROW U+27A8 โžจ HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW U+27A9 โžฉ RIGHT-SHADED WHITE RIGHTWARDS ARROW U+27AA โžช LEFT-SHADED WHITE RIGHTWARDS ARROW U+27AB โžซ BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW U+27AC โžฌ FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW U+27AD โžญ HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW U+27AE โžฎ HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW U+27AF โžฏ NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW U+27B0 โžฐ CURLY LOOP U+27B1 โžฑ NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW U+27B2 โžฒ CIRCLED HEAVY WHITE RIGHTWARDS ARROW U+27B3 โžณ WHITE-FEATHERED RIGHTWARDS ARROW U+27B4 โžด BLACK-FEATHERED SOUTH EAST ARROW U+27B5 โžต BLACK-FEATHERED RIGHTWARDS ARROW U+27B6 โžถ BLACK-FEATHERED NORTH EAST ARROW U+27B7 โžท HEAVY BLACK-FEATHERED SOUTH EAST ARROW U+27B8 โžธ HEAVY BLACK-FEATHERED RIGHTWARDS ARROW U+27B9 โžน HEAVY BLACK-FEATHERED NORTH EAST ARROW U+27BA โžบ TEARDROP-BARBED RIGHTWARDS ARROW U+27BB โžป HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW U+27BC โžผ WEDGE-TAILED RIGHTWARDS ARROW U+27BD โžฝ HEAVY WEDGE-TAILED RIGHTWARDS ARROW U+27BE โžพ OPEN-OUTLINED RIGHTWARDS ARROW U+27C0 โŸ€ THREE DIMENSIONAL ANGLE U+27E8 โŸจ MATHEMATICAL LEFT ANGLE BRACKET U+27E9 โŸฉ MATHEMATICAL RIGHT ANGLE BRACKET U+27EA โŸช MATHEMATICAL LEFT DOUBLE ANGLE BRACKET U+27EB โŸซ MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET U+27F0 โŸฐ UPWARDS QUADRUPLE ARROW U+27F1 โŸฑ DOWNWARDS QUADRUPLE ARROW U+27F2 โŸฒ ANTICLOCKWISE GAPPED CIRCLE ARROW U+27F3 โŸณ CLOCKWISE GAPPED CIRCLE ARROW U+27F4 โŸด RIGHT ARROW WITH CIRCLED PLUS U+27F5 โŸต LONG LEFTWARDS ARROW U+27F6 โŸถ LONG RIGHTWARDS ARROW U+27F7 โŸท LONG LEFT RIGHT ARROW U+27F8 โŸธ LONG LEFTWARDS DOUBLE ARROW U+27F9 โŸน LONG RIGHTWARDS DOUBLE ARROW U+27FA โŸบ LONG LEFT RIGHT DOUBLE ARROW U+27FB โŸป LONG LEFTWARDS ARROW FROM BAR U+27FC โŸผ LONG RIGHTWARDS ARROW FROM BAR U+27FD โŸฝ LONG LEFTWARDS DOUBLE ARROW FROM BAR U+27FE โŸพ LONG RIGHTWARDS DOUBLE ARROW FROM BAR U+27FF โŸฟ LONG RIGHTWARDS SQUIGGLE ARROW U+2900 โค€ RIGHTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE U+2901 โค RIGHTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE U+2902 โค‚ LEFTWARDS DOUBLE ARROW WITH VERTICAL STROKE U+2903 โคƒ RIGHTWARDS DOUBLE ARROW WITH VERTICAL STROKE U+2904 โค„ LEFT RIGHT DOUBLE ARROW WITH VERTICAL STROKE U+2905 โค… RIGHTWARDS TWO-HEADED ARROW FROM BAR U+2906 โค† LEFTWARDS DOUBLE ARROW FROM BAR U+2907 โค‡ RIGHTWARDS DOUBLE ARROW FROM BAR U+2908 โคˆ DOWNWARDS ARROW WITH HORIZONTAL STROKE U+2909 โค‰ UPWARDS ARROW WITH HORIZONTAL STROKE U+290A โคŠ UPWARDS TRIPLE ARROW U+290B โค‹ DOWNWARDS TRIPLE ARROW U+290C โคŒ LEFTWARDS DOUBLE DASH ARROW U+290D โค RIGHTWARDS DOUBLE DASH ARROW U+290E โคŽ LEFTWARDS TRIPLE DASH ARROW U+290F โค RIGHTWARDS TRIPLE DASH ARROW U+2910 โค RIGHTWARDS TWO-HEADED TRIPLE DASH ARROW U+2911 โค‘ RIGHTWARDS ARROW WITH DOTTED STEM U+2912 โค’ UPWARDS ARROW TO BAR U+2913 โค“ DOWNWARDS ARROW TO BAR U+2914 โค” RIGHTWARDS ARROW WITH TAIL WITH VERTICAL STROKE U+2915 โค• RIGHTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE U+2916 โค– RIGHTWARDS TWO-HEADED ARROW WITH TAIL U+2917 โค— RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE U+2918 โค˜ RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE U+2919 โค™ LEFTWARDS ARROW-TAIL U+291A โคš RIGHTWARDS ARROW-TAIL U+291B โค› LEFTWARDS DOUBLE ARROW-TAIL U+291C โคœ RIGHTWARDS DOUBLE ARROW-TAIL U+291D โค LEFTWARDS ARROW TO BLACK DIAMOND U+291E โคž RIGHTWARDS ARROW TO BLACK DIAMOND U+291F โคŸ LEFTWARDS ARROW FROM BAR TO BLACK DIAMOND U+2920 โค  RIGHTWARDS ARROW FROM BAR TO BLACK DIAMOND U+2921 โคก NORTHWEST AND SOUTH EAST ARROW U+2922 โคข NORTHEAST AND SOUTH WEST ARROW U+2923 โคฃ NORTH WEST ARROW WITH HOOK U+2924 โคค NORTH EAST ARROW WITH HOOK U+2925 โคฅ SOUTH EAST ARROW WITH HOOK U+2926 โคฆ SOUTH WEST ARROW WITH HOOK U+2927 โคง NORTH WEST ARROW AND NORTH EAST ARROW U+2928 โคจ NORTH EAST ARROW AND SOUTH EAST ARROW U+2929 โคฉ SOUTH EAST ARROW AND SOUTH WEST ARROW U+292A โคช SOUTH WEST ARROW AND NORTH WEST ARROW U+292B โคซ RISING DIAGONAL CROSSING FALLING DIAGONAL U+292C โคฌ FALLING DIAGONAL CROSSING RISING DIAGONAL U+292D โคญ SOUTH EAST ARROW CROSSING NORTH EAST ARROW U+292E โคฎ NORTH EAST ARROW CROSSING SOUTH EAST ARROW U+292F โคฏ FALLING DIAGONAL CROSSING NORTH EAST ARROW U+2930 โคฐ RISING DIAGONAL CROSSING SOUTH EAST ARROW U+2931 โคฑ NORTH EAST ARROW CROSSING NORTH WEST ARROW U+2932 โคฒ NORTH WEST ARROW CROSSING NORTH EAST ARROW U+2933 โคณ WAVE ARROW POINTING DIRECTLY RIGHT U+2934 โคด ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS U+2935 โคต ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS U+2936 โคถ ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS U+2937 โคท ARROW POINTING DOWNWARDS THEN CURVING RIGHTWARDS U+2938 โคธ RIGHT-SIDE ARC CLOCKWISE ARROW U+2939 โคน LEFT-SIDE ARC ANTICLOCKWISE ARROW U+293A โคบ TOP ARC ANTICLOCKWISE ARROW U+293B โคป BOTTOM ARC ANTICLOCKWISE ARROW U+293C โคผ TOP ARC CLOCKWISE ARROW WITH MINUS U+293D โคฝ TOP ARC ANTICLOCKWISE ARROW WITH PLUS U+293E โคพ LOWER RIGHT SEMICIRCULAR CLOCKWISE ARROW U+293F โคฟ LOWER LEFT SEMICIRCULAR ANTICLOCKWISE ARROW U+2940 โฅ€ ANTICLOCKWISE CLOSED CIRCLE ARROW U+2941 โฅ CLOCKWISE CLOSED CIRCLE ARROW U+2942 โฅ‚ RIGHTWARDS ARROW ABOVE SHORT LEFTWARDS ARROW U+2943 โฅƒ LEFTWARDS ARROW ABOVE SHORT RIGHTWARDS ARROW U+2944 โฅ„ SHORT RIGHTWARDS ARROW ABOVE LEFTWARDS ARROW U+2945 โฅ… RIGHTWARDS ARROW WITH PLUS BELOW U+2946 โฅ† LEFTWARDS ARROW WITH PLUS BELOW U+2962 โฅข LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN U+2963 โฅฃ UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT U+2964 โฅค RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN U+2965 โฅฅ DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT U+2966 โฅฆ LEFTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB UP U+2967 โฅง LEFTWARDS HARPOON WITH BARB DOWN ABOVE RIGHTWARDS HARPOON WITH BARB DOWN U+2968 โฅจ RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP U+2969 โฅฉ RIGHTWARDS HARPOON WITH BARB DOWN ABOVE LEFTWARDS HARPOON WITH BARB DOWN U+296A โฅช LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH U+296B โฅซ LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH U+296C โฅฌ RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH U+296D โฅญ RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH U+296E โฅฎ UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT U+296F โฅฏ DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT U+2989 โฆ‰ Z NOTATION LEFT BINDING BRACKET U+298A โฆŠ Z NOTATION RIGHT BINDING BRACKET U+2991 โฆ‘ LEFT ANGLE BRACKET WITH DOT U+2992 โฆ’ RIGHT ANGLE BRACKET WITH DOT U+2993 โฆ“ LEFT ARC LESS-THAN BRACKET U+2994 โฆ” RIGHT ARC GREATER-THAN BRACKET U+2995 โฆ• DOUBLE LEFT ARC GREATER-THAN BRACKET U+2996 โฆ– DOUBLE RIGHT ARC LESS-THAN BRACKET U+29A8 โฆจ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND RIGHT U+29A9 โฆฉ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND LEFT U+29AA โฆช MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND RIGHT U+29AB โฆซ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND LEFT U+29AC โฆฌ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND UP U+29AD โฆญ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND UP U+29AE โฆฎ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND DOWN U+29AF โฆฏ MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND DOWN U+29BE โฆพ CIRCLED WHITE BULLET U+29BF โฆฟ CIRCLED BULLET U+29C9 โง‰ TWO JOINED SQUARES U+29CE โงŽ RIGHT TRIANGLE ABOVE LEFT TRIANGLE U+29CF โง LEFT TRIANGLE BESIDE VERTICAL BAR U+29D0 โง VERTICAL BAR BESIDE RIGHT TRIANGLE U+29D1 โง‘ BOWTIE WITH LEFT HALF BLACK U+29D2 โง’ BOWTIE WITH RIGHT HALF BLACK U+29D3 โง“ BLACK BOWTIE U+29D4 โง” TIMES WITH LEFT HALF BLACK U+29D5 โง• TIMES WITH RIGHT HALF BLACK U+29D6 โง– WHITE HOURGLASS U+29D7 โง— BLACK HOURGLASS U+29E8 โงจ DOWN-POINTING TRIANGLE WITH LEFT HALF BLACK U+29E9 โงฉ DOWN-POINTING TRIANGLE WITH RIGHT HALF BLACK U+29EA โงช BLACK DIAMOND WITH DOWN ARROW U+29EB โงซ BLACK LOZENGE U+29EC โงฌ WHITE CIRCLE WITH DOWN ARROW U+29ED โงญ BLACK CIRCLE WITH DOWN ARROW U+29F4 โงด RULE-DELAYED U+29FC โงผ LEFT-POINTING CURVED ANGLE BRACKET U+29FD โงฝ RIGHT-POINTING CURVED ANGLE BRACKET U+29FE โงพ TINY U+29FF โงฟ MINY U+2B00 โฌ€ NORTH EAST WHITE ARROW U+2B01 โฌ NORTH WEST WHITE ARROW U+2B02 โฌ‚ SOUTH EAST WHITE ARROW U+2B03 โฌƒ SOUTH WEST WHITE ARROW U+2B04 โฌ„ LEFT RIGHT WHITE ARROW U+2B05 โฌ… LEFTWARDS BLACK ARROW U+2B06 โฌ† UPWARDS BLACK ARROW U+2B07 โฌ‡ DOWNWARDS BLACK ARROW U+2B08 โฌˆ NORTH EAST BLACK ARROW U+2B09 โฌ‰ NORTH WEST BLACK ARROW U+2B0A โฌŠ SOUTH EAST BLACK ARROW U+2B0B โฌ‹ SOUTHWEST BLACK ARROW U+2B0C โฌŒ LEFT RIGHT BLACK ARROW U+2B0D โฌ UP DOWN BLACK ARROW U+2B0E โฌŽ RIGHTWARDS ARROW WITH TIP DOWNWARDS U+2B0F โฌ RIGHTWARDS ARROW WITH TIP UPWARDS U+2B10 โฌ LEFTWARDS ARROW WITH TIP DOWNWARDS U+2B11 โฌ‘ LEFTWARDS ARROW WITH TIP UPWARDS U+2B12 โฌ’ SQUARE WITH TOP HALF BLACK U+2B13 โฌ“ SQUARE WITH BOTTOM HALF BLACK U+2B14 โฌ” SQUARE WITH UPPER RIGHT DIAGONAL HALF BLACK U+2B15 โฌ• SQUARE WITH LOWER LEFT DIAGONAL HALF BLACK U+2B16 โฌ– DIAMOND WITH LEFT HALF BLACK U+2B17 โฌ— DIAMOND WITH RIGHT HALF BLACK U+2B18 โฌ˜ DIAMOND WITH TOP HALF BLACK U+2B19 โฌ™ DIAMOND WITH BOTTOM HALF BLACK U+2B1A โฌš DOTTED SQUARE U+2B1B โฌ› BLACK LARGE SQUARE U+2B1C โฌœ WHITE LARGE SQUARE U+2B1D โฌ BLACK VERY SMALL SQUARE U+2B1E โฌž WHITE VERY SMALL SQUARE U+2B1F โฌŸ BLACK PENTAGON U+2B20 โฌ  WHITE PENTAGON U+2B21 โฌก WHITE HEXAGON U+2B22 โฌข BLACK HEXAGON U+2B23 โฌฃ HORIZONTAL BLACK HEXAGON U+2B24 โฌค BLACK LARGE CIRCLE U+2B25 โฌฅ BLACK MEDIUM DIAMOND U+2B26 โฌฆ WHITE MEDIUM DIAMOND U+2B27 โฌง BLACK MEDIUM LOZENGE U+2B28 โฌจ WHITE MEDIUM LOZENGE U+2B29 โฌฉ BLACK SMALL DIAMOND U+2B2A โฌช BLACK SMALL LOZENGE U+2B2B โฌซ WHITE SMALL LOZENGE U+2B30 โฌฐ LEFT ARROW WITH SMALL CIRCLE U+2B31 โฌฑ THREE LEFTWARDS ARROWS U+2B32 โฌฒ LEFT ARROW WITH CIRCLED PLUS U+2B33 โฌณ LONG LEFTWARDS SQUIGGLE ARROW U+2B34 โฌด LEFTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE U+2B35 โฌต LEFTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE U+2B36 โฌถ LEFTWARDS TWO-HEADED ARROW FROM BAR U+2B37 โฌท LEFTWARDS TWO-HEADED TRIPLE DASH ARROW U+2B38 โฌธ LEFTWARDS ARROW WITH DOTTED STEM U+2B39 โฌน LEFTWARDS ARROW WITH TAIL WITH VERTICAL STROKE U+2B3A โฌบ LEFTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE U+2B3B โฌป LEFTWARDS TWO-HEADED ARROW WITH TAIL U+2B3C โฌผ LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE U+2B3D โฌฝ LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE U+2B3E โฌพ LEFTWARDS ARROW THROUGH X U+2B3F โฌฟ WAVE ARROW POINTING DIRECTLY LEFT U+2B40 โญ€ EQUALS SIGN ABOVE LEFTWARDS ARROW U+2B41 โญ REVERSE TILDE OPERATOR ABOVE LEFTWARDS ARROW U+2B42 โญ‚ LEFTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO U+2B43 โญƒ RIGHTWARDS ARROW THROUGH GREATER-THAN U+2B44 โญ„ RIGHTWARDS ARROW THROUGH SUPERSET U+2B45 โญ… LEFTWARDS QUADRUPLE ARROW U+2B46 โญ† RIGHTWARDS QUADRUPLE ARROW U+2B47 โญ‡ REVERSE TILDE OPERATOR ABOVE RIGHTWARDS ARROW U+2B48 โญˆ RIGHTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO U+2B49 โญ‰ TILDE OPERATOR ABOVE LEFTWARDS ARROW U+2B4A โญŠ LEFTWARDS ARROW ABOVE ALMOST EQUAL TO U+2B4B โญ‹ LEFTWARDS ARROW ABOVE REVERSE TILDE OPERATOR U+2B4C โญŒ RIGHTWARDS ARROW ABOVE REVERSE TILDE OPERATOR U+2B50 โญ WHITE MEDIUM STAR U+2B51 โญ‘ BLACK SMALL STAR U+2B52 โญ’ WHITE SMALL STAR U+2B53 โญ“ BLACK RIGHT-POINTING PENTAGON U+2B54 โญ” WHITE RIGHT-POINTING PENTAGON U+2B55 โญ• HEAVY LARGE CIRCLE U+2B56 โญ– HEAVY OVAL WITH OVAL INSIDE U+2B57 โญ— HEAVY CIRCLE WITH CIRCLE INSIDE U+2B58 โญ˜ HEAVY CIRCLE U+2B59 โญ™ HEAVY CIRCLED SALTIRE OPTION 2: PURE CSS CHEVRONS You can create the chevrons efficiently using only CSS (No images required). It's easy to manipulate: * *ROTATION *THICKNESS *COLOR *SIZE CLICK FOR DEMO ON JSFIDDLE CSS (Efficient with cross browser support) .chevron { position: relative; display: block; height: 50px; /*height should be double border*/ } .chevron::before, .chevron::after { position: absolute; display: block; content: ""; border: 25px solid transparent; /*adjust size*/ } /* Replace all text `top` below with left/right/bottom to rotate the chevron */ .chevron::before { top: 0; border-top-color: #b00; /*Chevron Color*/ } .chevron::after { top: -10px; /*adjust thickness*/ border-top-color: #fff; /*Match background colour*/ } <i class="chevron"></i> OPTION 3: CSS BASE64 IMAGE ICONS UP/DOWN DOWN UP Using only a few lines of CSS we can encode our images into base64. CLICK FOR DEMO ON JSFIDDLE PROS * *No need to include additional resources in the form of images or fonts. *Supports full alpha transparency. *Full cross-browser support. *Small images/icons can be stored in a database. CONS * *Updating/editing can become a hassle. *Not suitable for large images due to excessive code markup that's generated. CSS .sorting, .sorting_asc, .sorting_desc{ padding:4px 21px 4px 4px; cursor:pointer; } .sorting{ background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIUnC2nKLnT4or00PvyrQwrPzUZshQAOw==) no-repeat center right; } .sorting_asc{ background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIRnC2nKLnT4or00Puy3rx7VQAAOw==) no-repeat center right; } .sorting_desc{ background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIPnI+py+0/hJzz0IruwjsVADs=) no-repeat center right; } A: This one seems to imply that 030 and 031 are up and down triangles. (As bobince pointed out, this doesn't seem to be an ASCII standard) A: I use โ–ผ and โ–ฒ, but they might not work for you. I use alt 11551 for the first one and 11550 for the second one. You can always copy paste them if the ascii isnt the same for your system. A: Sorry but they are only in Unicode. :( Big ones: * *U+25B2 (Black up-pointing triangle โ–ฒ) *U+25BC (Black down-pointing triangle โ–ผ) *U+25C0 (Black left-pointing triangle โ—€) *U+25B6 (Black right-pointing triangle โ–ถ) Big white ones: * *U+25B3 (White up-pointing triangle โ–ณ) *U+25BD (White down-pointing triangle โ–ฝ) *U+25C1 (White left-pointing triangle โ—) *U+25B7 (White right-pointing triangle โ–ท) There is also some smalller triangles: * *U+25B4 (Black up-pointing small triangle โ–ด) *U+25C2 (Black left-pointing small triangle โ—‚) *U+25BE (Black down-pointing small triangle โ–พ) *U+25B8 (Black right-pointing small triangle โ–ธ) Also some white ones: * *U+25C3 (White left-pointing small triangle โ—ƒ) *U+25BF (White down-pointing small triangle โ–ฟ) *U+25B9 (White right-pointing small triangle โ–น) *U+25B5 (White up-pointing small triangle โ–ต) There are also some "pointy" triangles. You can read more here in Wikipedia:http://en.wikipedia.org/wiki/Geometric_Shapes But unfortunately, they are all Unicode instead of ASCII. If you still want to use ASCII, then you can use an image file for it of just use ^ and v. (Just like the Google Maps in the mobile version this was referring to the ancient mobile Google Maps) As others also suggested, you can also create triangles with HTML, either with CSS borders or SVG shapes or even JavaScript canvases. CSS div{ width: 0px; height: 0px; border-top: 10px solid black; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: none; } SVG <svg width="16" height="10"> <polygon points="0,0 16,0 8,10"/> </svg> JavaScript var ctx = document.querySelector("canvas").getContext("2d"); // do not use with() outside of this demo! with(ctx){ beginPath(); moveTo(0,0); lineTo(16,0); lineTo(8,10); fill(); endPath(); } Demo A: There are several correct ways to display a down-pointing triangle. Method 1 : use decimal HTML entity HTML : &#9660; Method 2 : use hexidecimal HTML entity HTML : &#x25BC; Method 3 : use character directly HTML : โ–ผ Method 4 : use CSS HTML : <span class='icon-down'></span> CSS : .icon-down:before { content: "\25BC"; } Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. &hearts; to display โ™ฅ). You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/. Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like โ˜ƒ,โ„,โ˜…,โ˜‚,โ˜ญ,โŽ— or โŽ˜, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated. If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this. Background images A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols. This following code is the base64 for and SVG version of the icon : /* size: 0.9kb */ url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4= When to use background-images or fonts For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences: SVG images * *They can have multiple colors *They can embed their own CSS and/or be styled by the HTML document *They can be loaded as a seperate file, embedded in CSS AND embedded in HTML *Each symbol is represented by XML code or base64 code. You cannot use the character directly within your code editor or use an HTML entity *Multiple uses of the same symbol implies duplication of the symbol when XML code is embedded in the HTML. Duplication is not required when embedding the file in the CSS or loading it as a seperate file *You can not use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually. *You need some knowledge of SVG and/or base64 encoding *Limited or no support in old versions of IE Icon fonts * *An icon can have but one fill color, one background color, etc. *An icon can be embedded in CSS or HTML. In HTML, you can use the character directly or use an HTML entity to represent it. *Some symbols can be displayed without the use of a webfont. Most symbols cannot. *Multiple uses of the same symbol implies duplication of the symbol when your character embedded in the HTML. Duplication is not required when embedding the file in the CSS. *You can use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon *You need no special technical knowledge *Support in all major browsers, including old versions of IE Personally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color, background-color and other color-related CSS rules for fonts. The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG. A: Unicode arrows heads: * *โ–ฒ - U+25B2 BLACK UP-POINTING TRIANGLE *โ–ผ - U+25BC BLACK DOWN-POINTING TRIANGLE *โ–ด - U+25B4 SMALL BLACK UP-POINTING TRIANGLE *โ–พ - U+25BE SMALL BLACK DOWN-POINTING TRIANGLE For โ–ฒ and โ–ผ use &#x25B2; and &#x25BC; respectively if you cannot include Unicode characters directly (use UTF-8!). Note that the font support for the smaller versions is not as good. Better to use the large versions in smaller font. More Unicode arrows are at: * *http://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode *http://en.wikipedia.org/wiki/Geometric_Shapes Lastly, these arrows are not ASCII, including โ†‘ and โ†“: they are Unicode. A: Usually, best is to see a character in his context. Here is the full list of Unicode chars, and how your browser currently displays them. I am seeing this list evolving, browser versions after others. This list is obtained by iteration in decimal of the html entities unicode table, it may take some seconds, but is very useful to me in many cases. By hovering quickly a given char you will get the dec and hex and the shortcuts to generate it with a keyboard. var i = 0 do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++ while (i<136690) window.stop() // From https://codepen.io/Nico_KraZhtest/pen/mWzXqy The same snippet as a bookmarklet: javascript:void%20!function(){var%20t=0;do{document.write(%22%3Ca%20title='(Linux|Hex):%20[CTRL+SHIFT]+u%22+t.toString(16)+%22\nHtml%20entity:%20%26%23%20%22+t+%22;\n%26%23x%22+t.toString(16)+%22;\n(Win|Dec):%20[ALT]+%22+t+%22'%20onmouseover='this.focus()'%20onclick='this.href=\%22https://google.com/%3Fq=\%22+this.innerHTML'%20style='cursor:pointer'%20target='new'%3E%26%23%22+t+%22;%3C/a%3E%22),t++}while(t%3C136690);window.stop()}(); To generate that list from php: for ($x = 0; $x < 136690; $x++) { echo html_entity_decode('&#'.$x.';',ENT_NOQUOTES,'UTF-8'); } To generate that list into the console, using php: php -r 'for ($x = 0; $x < 136690; $x++) { echo html_entity_decode("&#".$x.";",ENT_NOQUOTES,"UTF-8");}' Here is a plain text extract, of arrows, some are coming with unicode 10.0. http://unicode.org/versions/Unicode10.0.0/ Unicode 10.0 adds 8,518 characters, for a total of 136,690 characters. โญโญžโญŸโญ โญกโญขโญฃโญคโญฅโญฆโญงโญจโญฉโญชโญซโญฌโญญโญฎโญฏโญฐโญฑโญฒโญณโญถโญทโญธโญนโญบโญปโญผโญฝโญพโญฟโฎ€โฎโฎ‚โฎƒโฎ„โฎ…โฎ†โฎ‡โฎˆโฎ‰โฎŠโฎ‹โฎŒโฎโฎŽโฎโฎโฎ‘โฎ’โฎ“โฎ”โฎ•โฎ˜โฎ™โฎšโฎ›โฎœโฎโฎžโฎŸโฎ โฎกโฎขโฎฃโฎคโฎฅโฎฆโฎงโฎจโฎฉโฎชโฎซโฎฌโฎญโฎฎโฎฏโฎฐโฎฑโฎฒโฎณโฎดโฎตโฎถโฎทโฎธโฎนโฎฝโฎพโฎฟโฏ€โฏโฏ‚โฏ…โฏ†โฏ‡โฏˆโฌถโฌทโฌธโฌนโฌบโฌปโฌผโฌฝโฌพโฌ€โฌโฌ‚โฌƒโฌ„โฌ…โฌ†โฌ‡โฌˆโฌ‰โฌŠโฌ‹โฌŒโฌโฌŽโฌโฌโฌ‘โค€โคโค‚โคƒโค„โค…โค†โค‡โคˆโค‰โคŠโค‹โคŒโคโคŽโคโคโค‘โค’โค“โค”โค•โค–โค—โค˜โค™โคšโค›โคœโคโคžโคŸโค โคกโคขโคฃโคคโคฅโคฆโคงโคจโคฉโคชโคซโคฌโคญโคฎโคฏโคฐโคฑโคฒโคณโคดโคตโคถโคทโคธโคนโคบโคปโคผโคฝโคพโคฟโฅ€โฅโฅ‚โฅƒโฅ„โฅ…โฅ†โฅ‡โฅˆโฅ‰โฅŠโฅ‹โฅŒโฅโฅŽโฅโฅโฅ‘โฅ’โฅ“โฅ”โฅ•โฅ–โฅ—โฅ˜โฅ™โฅšโฅ›โฅœโฅโฅžโฅŸโฅ โฅกโฅขโฅฃโฅคโฅฅโฅฆโฅงโฅจโฅฉโฅชโฅซโฅฌโฅญโฅฎโฅฏโฅฐโฅฑโฅฒโฅณโฅดโฅตโŸจโŸฉโŸชโŸซโŸฌโŸญโŸฎโŸฏโŸฐโŸฑโŸฒโŸณโŸดโŸตโŸถโŸทโŸธโŸนโŸบโŸปโŸผโŸฝโŸพโŸฟโž˜โž™โžšโž›โžœโžโžžโžŸโž โžกโžขโžฃโžคโžฅโžฆโžงโžจโžฉโžชโžซโžฌโžญโžฎโžฏโžฐโžฑโžฒโžณโžดโžตโžถโžทโžธโžนโžบโžปโžผโžฝโžพโŠฒโŠณโŠดโŠตโ†โ†‘โ†’โ†“โ†”โ†•โ†–โ†—โ†˜โ†™โ†šโ†›โ†œโ†โ†žโ†Ÿโ† โ†กโ†ขโ†ฃโ†คโ†ฅโ†ฆโ†งโ†จโ†ฉโ†ชโ†ซโ†ฌโ†ญโ†ฎโ†ฏโ†ฐโ†ฑโ†ฒโ†ณโ†ดโ†ตโ†ถโ†ทโ†ธโ†นโ†บโ†ปโ†ผโ†ฝโ†พโ†ฟโ‡€โ‡โ‡‚โ‡ƒโ‡„โ‡…โ‡†โ‡‡โ‡ˆโ‡‰โ‡Šโ‡‹โ‡Œโ‡โ‡Žโ‡โ‡โ‡‘โ‡’โ‡“โ‡”โ‡•โ‡–โ‡—โ‡˜โ‡™โ‡šโ‡›โ‡œโ‡โ‡žโ‡Ÿโ‡ โ‡กโ‡ขโ‡ฃโ‡คโ‡ฅโ‡ฆโ‡งโ‡จโ‡ฉโ‡ชโ‡ซโ‡ฌโ‡ญโ‡ฎโ‡ฏโ‡ฐโ‡ฑโ‡ฒโ‡ณโ‡ดโ‡ตโ‡ถโ‡ทโ‡ธโ‡นโ‡บโ‡ปโ‡ผโ‡ฝโ‡พโ‡ฟแ‚แƒแ„แ…แ†แ‡แˆแ‰แŠแ‹แŒแแŽแแแ‘แ’แ“แ”แ•แ–แ—แ˜แ™แšแ›แซแฌแญแฎแฏแฐแฑแฒแณแดแตแถแทแธแนแบแปแผแฝแพแฟแ‘€แ‘แ‘‚แ‘ƒแ‘„แ‘…แ‘†แ‘‡แ‘ˆ Hey, did you notice the plain html <details> element has a drop down arrow? This is sometimes all what we need. <details> <summary>Morning</summary> <p>Hello world!</p> </details> <details> <summary>Evening</summary> <p>How sweat?</p> </details> A: "Not ASCII (neither's โ†‘/โ†“)" needs qualification. While these characters are not defined in the American Standard Code for Information Interchange as glyphs, their codes WERE commonly used to give a graphical presentation for ASCII codes 24 and 25 (hex 18 and 19, CANcel and EM:End of Medium). Code page 437 (called Extended ASCII by IBM, includes the numeric codes 128 to 255) defined the use of these glyphs as ASCII codes and the ubiquity of these conventions permeated the industry as seen by their deployment as standards by leading companies such as HP, particularly for printers, and IBM, particularly for microcomputers starting with the original PC. Just as the use of the ASCII codes for CAN and EM was relatively obsolete at the time, justifying their use as glyphs, so has the passage of time made the use of the codes as glyphs obsolete by the current use of UNICODE conventions. It should be emphasized that the extensions to ASCII made by IBM in Extended ASCII, included not only a larger numeric set for numeric codes 128 to 255, but also extended the use of some numeric control codes, in the ASCII range 0 to 32, from just media transmission control protocols to include glyphs. It is often assumed, incorrectly, that the first 0 to 128 were not "extended" and that IBM was using the glyphs of conventional ASCII for this range. This error is also perpetrated in one of the previous references. This error became so pervasive that it colloquially redefined ASCII subliminally. A: I know I'm late to the party but you can accomplish this with plain CSS as well: HTML: (It can be any HTML element, if you're using an inline element like a <span> for example, make sure you make it a block/inline-block element with display:block; or display:inline-block): <div class="up"></div> and <div class="down"></div> CSS: .up { height:0; width:0; border-top:100px solid black; border-left:100px solid transparent; transform:rotate(-45deg); } .down { height:0; width:0; border-bottom:100px solid black; border-right:100px solid transparent; transform:rotate(-45deg); } You can also accomplish it using :before and :after pseudo-elements, which is actually a better way since you avoid creating extra markup. But that's up to you on how you'd like to accomplish it. -- Here's a Demo in CodePen with many arrow possibilities. A: A lot of people here are suggesting to use the triangles, but sometimes you need a chevron. We had a case where our button shows a chevron, and wanted the user's manual to refer to the button in a way which will be recognized by a non-technical user too. So we needed a chevron sign. We used ๏น€ in the end. It is known as PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET and its code is U+FE40. A: I think the asker may be referring to one of these (see attached image) - I found this StackOverflow question while searching for the same thing myself. Unfortunately, this glyph doesn't seem to exist as a distinct character entity anywhere. Wikipedia accomplishes it below by using inline javascript and img content="data:image/gif..." to achieve the symbol. Incidentally, here's the base64 for it: data:image/gif;base64,R0lGODlhFQAJAIABAAAAAAAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS4wLWMwNjAgNjEuMTM0Nzc3LCAyMDEwLzAyLzEyLTE3OjMyOjAwICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjAxODAxMTc0MDcyMDY4MTE4OEM2REYyN0ExMDhBNDJFIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjdCNTAyODcwMEY4NjExRTBBMzkyQzAyM0E1RDk3RDc3IiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjdCNTAyODZGMEY4NjExRTBBMzkyQzAyM0E1RDk3RDc3IiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzUgTWFjaW50b3NoIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MDE4MDExNzQwNzIwNjgxMTg4QzZERjI3QTEwOEE0MkUiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6MDE4MDExNzQwNzIwNjgxMTg4QzZERjI3QTEwOEE0MkUiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4B//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7urm4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXlpWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRzcnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVBPTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLSwrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKCQgHBgUEAwIBAAAh+QQBAAABACwAAAAAFQAJAAACF4yPgMsJ2mJ4VDKKrd4GVz5lYPeMiVUAADs= Hope this helps someone! A: โ–ฒโ–ผ These are U+25B2 (&#x25B2) and U+25BC (&#x25BC) respectively A: HTML Entities for empty triangles โ— = &#9665; โ–ท = &#9655; โ–ฝ = &#9661; โ–ณ = &#9651; A: I decided that most popular symbols recommended here (โ–ผ and โ–ฒ) are looking too bold, so on the site codepoints.net, recommended by user ADJenks, I found these symbols which are looking better for my taste: (U+1F780) (U+1F781) (U+1F782) (U+1F783) A: The site I like to use for this is codepoints.net Here is a search for the words "arrowhead" and "triangle": https://codepoints.net/search?q=arrowhead+triangle It has some matches for "triangle-headed arrow" that have stems, but it's only 4 small pages to skim over and there are many good matches with nice details on each character. There is also a code block for "Miscellaneous Symbols and Arrows" and this website lists them here: https://codepoints.net/miscellaneous_symbols_and_arrows A: Here is another one - แž - Unicode U+141E / CANADIAN SYLLABICS GLOTTAL STOP A: Unicode arrows seem pretty much out, because as of 2021 Android phones do not seem to come installed with full Unicode fonts that contain arrows (simply most top language fonts, ie Chinese, Arabic, etc); and a webpage asking to download a decent Unicode font, such as Arial Unicode MS, will put a 22Meg hit on your download time. FontAwesome is quite useful for these kinds of dingbats. Version 4.7 font-awesome.min.css weighs in at 30KB. sort-up, sort-down, chevron-up, chevron-down provide your characters. https://fontawesome.com/v4.7/get-started/ Works great in regular HTML (text, etc). However it requires rewriting, and so inside literal span contexts is more tricky to use. jquery already supports icons that people can use, by quietly downloading a 6.8K font image and then taking chunks out of it under the hood. Both carets (chevrons) and triangles (arrowheads). See https://api.jqueryui.com/theming/icons/ for a catalog. After including jquery, include a glyph by using code <span class="ui-icon ui-icon-arrowthick-1-n"></span>. The up and down arrows you requested are ui-icon-caret-1-n and ui-icon-caret-1-s (for north and south); the carets are better than triangles for looking pointy at low resolutions. And they can be colorized. Unfortunately, jquery currently appears hardwired to display icons at 16x16 pixel resolution--grain-of-sand on today's monitors. They can be enlarged using the transform function. But it starts to get sloppy. jquery icons can also be hacked by locally overriding with your own image, through background:url(). See the jquery docs. Bytesize Icons https://github.com/danklammer/bytesize-icons is not too bad. there are others.
{ "language": "en", "url": "https://stackoverflow.com/questions/2701192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1370" }
Q: return first instance of unmatched regex scala Is there a way to return the first instance of an unmatched string between 2 strings with Scala's Regex library? For example: val a = "some text abc123 some more text" val b = "some text xyz some more text" a.firstUnmatched(b) = "abc123" A: Regex is good for matching & replacing in strings based on patterns. But to look for the differences between strings? Not exactly. However, diff can be used to find differences. object Main extends App { val a = "some text abc123 some more text 321abc" val b = "some text xyz some more text zyx" val firstdiff = (a.split(" ") diff b.split(" "))(0) println(firstdiff) } prints "abc123" Is regex desired after all? Then realize that the splits could be replaced by regex matching. The regex pattern in this example looks for words: val reg = "\\w+".r val firstdiff = (reg.findAllIn(a).toList diff reg.findAllIn(b).toList)(0)
{ "language": "en", "url": "https://stackoverflow.com/questions/38022320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SAS IOM Data Provider - Access Denied - SSIS connection I'm looking for guidance into how to integrate with the SAS IOM Data Provider through SSIS. It works fine when using SAS software but when trying to connect using the SAS IOM Data Provider in SSIS I receive the error message "Access is denied". The server name and credentials are identical. A: Try and get the specific error message you receive and what O/S you are running on (SAS O/S and SSIS O/S). It is most likely using the wrong credentials. Check SSIS logs and the Event Viewer. You need to determine which system is rejecting the call. Most likely it is SAS which means you are coming across, to SAS, as a different user than you think you are. Also, provide your connection string to IOM or double-check it at https://www.connectionstrings.com/sas-iom-provider/.
{ "language": "en", "url": "https://stackoverflow.com/questions/58888755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print one line from ArrayList based on a textfile? Right now we can print out one line from out from a textfile by pressing the line number. Problem is when we are able to print out a line number again (products), until we reach the limit of products in our textfile. How can we stop the loop so it only print the one line we choose? static ArrayList<Product> printOneLine() { ArrayList<Product> oneLineList = new ArrayList<Product>(); Scanner oneLine = readDetails("Products-JavaBikes.txt"); while (oneLine.hasNextLine()) { oneLineList.add(getProduct(oneLine.nextLine())); Scanner input = new Scanner (System.in); System.out.print("Please enter a number:"); for (int i = input.nextInt(); i < oneLineList.size();) { System.out.println(oneLineList.get(i)); break; } } return oneLineList; } A: It's a bit unclear from your question. But I think you're trying to break from your while loop on finding the product entered. I changed the redundant for loop to an if statement, so that you can break from the while loop. Your break is just breaking from the for loop, not the while loop. static ArrayList<Product> printOneLine() { ArrayList<Product> oneLineList = new ArrayList<Product>(); Scanner oneLine = readDetails("Products-JavaBikes.txt"); while (oneLine.hasNextLine()) { oneLineList.add(getProduct(oneLine.nextLine())); System.out.print("Please enter a number:"); Scanner input = new Scanner (System.in); if(input.nextInt() < oneLineList.size()) { System.out.println(oneLineList.get(i)); break; } } return oneLineList; }
{ "language": "en", "url": "https://stackoverflow.com/questions/43740502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Custom-shaped tags with background images I'm trying to implement a popover design. Each popover has a header with a dynamically generated background image on it. The design calls for a pointer at the top of the header, but I cannot think of a way to implement this and maintain the background image. Here's the current markup, sans pointer: <div class="popup"> <header class="popup-header" style="background-image: url(http://thebusstopsherefoundation.com/images/bettis_wave.jpg);"> <h1> <a class="resourceName" href="" target="_blank"></a> </h1> <div class="overlay"></div> </header> <main class="popup-body"> <section class="details"> <div class="resourceDescription"> <p></p> </div><!-- /resource-description--> <div class="attributes"> </div><!-- attronites--> </section><!-- / details--> <section class="organization"> <h3>Organization Information</h3> <h2 class="orgName"> <a href="" target="_blank"></a> </h2> <div class="orgDescription"> </div><!-- /orgdescription--> </section><!-- /organization--> </main> <section class="cta"> <a class="btn" href="" target="_blank">Participate</a> </section><!-- cta--> </div><!--popup--> Every CSS shape implementation I know requires borders or box shadows, neither of which will apply here. Any idea on how to implement this? A: This can be achieved using css clip-path and using a polygon as the parameter. Here is an example: <div class="dialog"></div> And the CSS .dialog{ position: absolute; top: 10px; left: 10px; right: 10px; bottom: 10px; width: 500px; height: 200px; background-color: #d3d0c9; background-image: url(http://lorempixel.com/400/200/sports/1/Dummy-Text/); background-size: cover; background-position: center center; -webkit-clip-path: polygon(0% 25%, 85% 25%, 100% 0%, 100% 100%, 0% 100%); clip-path: polygon(0% 25%, 85% 25%, 100% 0%, 100% 100%, 0% 100%); } <div class="dialog"></div> Browser support is limited to modern browsers though. You can play around using this tool : http://bennettfeely.com/clippy/ A: Here's a solution that uses transforms to accomplish the desired corner effect. Although the solution is more complicated than the accepted one, it can be implemented on pretty much all modern browsers. By using several of the transform polyfills, the solution can be implemented across the board. The algorithm behind this solution achieves a corner element via skewX() transform that is equally applied on the image (set as a background) and its container, just in different directions (e.g., -63.43deg and 63.43deg, depending on the dimensions of the corner element). Then the generated corner element is perfectly aligned with the heading's background. Here's a fiddle: http://jsfiddle.net/bLbt11a3/. HTML: <div class = "popup"> <header> <h1>DIY Gardener</h1> <div class = "corner-holder"> <div class = "corner"></div> </div> </header> </div> CSS: * { margin: 0; padding: 0; border: 0; } body { padding: 10px; background-color: #eee; } .popup { box-shadow: 0 0 10px #ccc; height: 240px; width: 186px; position: fixed; top: 50px; background-color: #fff; } .popup h1 { font: bold 20px/3 Sans-Serif; color: #fff; padding: 0 20px; background: url(http://thebusstopsherefoundation.com/images/bettis_wave.jpg) no-repeat -80px -90px/600px; } .popup header { position: relative; } .corner-holder { position: absolute; right: 0; top: 0; height: 30px; width: 60px; overflow: hidden; transform: translateY(-100%); } .corner-holder .corner, .corner-holder .corner:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform-origin: bottom left; /* webkit trick to get rid of jagged edges */ -webkit-backface-visibility: hidden; } .corner-holder .corner { overflow: hidden; transform: skewX(-63.43deg); } .corner-holder .corner:before { content: ""; background: url(http://thebusstopsherefoundation.com/images/bettis_wave.jpg) no-repeat -206px -60px/600px; transform: skewX(63.43deg); }
{ "language": "en", "url": "https://stackoverflow.com/questions/31735240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In Python, convert list to dict so that n-th element is a key Question: how to efficiently and pythonically convert a list of lists my_list to a dict my_dict so that zeroth element of every nested list is the key and remaining elements are a value (also list). Example: Input: my_list = [['a', 'b'], ['b', 'c', 'd', 'e', 'f'], ['g'], ['h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']] Output: my_dict = {'a': ['b'], 'b': ['c', 'd', 'e', 'f'], 'g': None, 'h': ['i', 'j'], 'k': ['l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']} Side notes: My dataset is huge so the method needs to be clean and efficient. While iterating over the list is acceptable, I would rather avoid nesting loops (to keep O(n) complexity). I managed to write a function that gets the job done by iterating over the input list and pops the zeroth element but popping is itself O(n) making whole solution O(n*n). A: Use a dictionary comprehension. The value lists or None are created by short-circuiting the list slice from index one with None using the or operator: dct = {lst[0]: lst[1:] or None for lst in my_list} pprint(dct) {'a': ['b'], 'b': ['c', 'd', 'e', 'f'], 'g': None, 'h': ['i', 'j'], 'k': ['l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']} Complexity: The complexity of this dict. comp. is O(n*m), where n is the number of items in the list and m is the length of the largest slice. The gain here does not come in a reduction in time complexity but in CPU time. A: You can use dict comprehension : >>> { i[0]:i[1:] or None for i in my_list} {'a': ['b'], 'b': ['c', 'd', 'e', 'f'], 'g': None, 'h': ['i', 'j'], 'k': ['l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']} A: You could do, { item[0]: item[1:] or None for item in my_list } A: This provides a O(n) solution. my_list = [['a', 'b'], ['b', 'c', 'd', 'e', 'f'], ['g'], ['h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']] print(my_list) my_dict={} for x in my_list: my_dict[x[0]]=x[1:] print(my_dict) But keep in mind that There should not be any duplicates in keys A: List slice has O(N) complexity, same if you are using tuples. I am afraid you can't get better than O(N*N) with given input data structure. A: Using dict cmprh {i[0]:i[1:] or None for i in my_list} Output : {'a': ['b'], 'h': ['i', 'j'], 'k': ['l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'], 'b': ['c', 'd', 'e', 'f'], 'g': None}
{ "language": "en", "url": "https://stackoverflow.com/questions/44698288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to send or stream live audio from system input over the internet with C# in windows form I want to develop an online streaming or radio app like https://mixlr.com I wish to use C#, any framework is fine, ASP.NET MVC, Windows Forms, anything... I would like to stream the audio from a web app. The app will stream my laptop microphone or any input device to the internet. I don't know how to go about this, where to start or which plugin to use, I've been searching for over a month now but still don't have a breakthrough yet. I'll appreciate your help.
{ "language": "en", "url": "https://stackoverflow.com/questions/67554802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript index of class I want to loop on each object(building) of a class in javascript, like doing my own .each() jQuery function (because sometimes, I just need the first buildings, not the whole class). Is there a way to get the index of an element in a Javascript class ? Are the classes structured like an array so I can access to an element like $('.Building)[i] ? my Class : function Building (name, height, width) { this.name = name; this.height = height; this.width = width; } When I add a building to the class : var b1 = new Building("Building1", 1, 2); var b2 = new Building("Building2", 3, 4); And then I want to display them by using a tool like for (var i=0; i<$('.Building').length; i++){ displayOnMap($('.Building')[i]); } Is it possible ? How should I code that ? EDIT ** @MESSIAH: Sure you can make javascript classes, check here ;) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript @Ralph: No, I am not confusing, actually it works pretty well in my code. the .each() function is not only for the CSS class, but also working on JavaScript class made as seen above. It works like this : $('.Building').each(function() { getData(this); }); A: Maybe what you are looking for is to add your Building objects into an array: var buildings = []; buildings.push(b1); buildings.push(b2); Then, you can loop as you need to: for (var i=0, len=buildings.length; i < len; i++){ displayOnMap(buildings[i]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/18000797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HIVE - Remove database name from heading when exporting to excel I have a table = Table_name,has 3 columns, Select * from Table_name Results appear exactly as below (column headings) Table_name.Col1 | Table_name.Col2 | Table_name.Col3 However, When I export to Excel. Column names are Table_name.Col1 | Table_name.Col2 | Table_name.Col3 Is there away to keep the headings as Col1 Col2 Col3 New to Hive hope someone can help. Thanks A: Add the below property before your select statement! set hive.resultset.use.unique.column.names=false Then hive doesn't printout the tablename as part of column names.
{ "language": "en", "url": "https://stackoverflow.com/questions/60106738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does firebase verifyIdToken fail on one device after same user logs in on another device? I can successfully log a user into firebase with the signInWithEmailAndPassword and then store the generated id token in local storage. That's all working fine and well. When I log that same user in on another device I get a new id token and store it. Now the first device will fail to verify the stored id token, probably because it doesn't match the newer token. But shouldn't firebase recognize both of these id tokens as valid until they expire? What should the approach be to get firebase to accept all current active tokens?
{ "language": "en", "url": "https://stackoverflow.com/questions/67578724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gammu-smsd RunOnReceive script results exit status 2 I want to forward an SMS using gammu-smsd RunOnReceive. That is the script I want to run (/var/spool/gammu/forward.sh) and it goes perfectly if I run it from a sudoer or using sudo -u gammu -g gammu /var/spool/gammu/forward.sh #!/bin/bash SMS_MESSAGES=1 for i in `seq $SMS_MESSAGES` do number="SMS_${i}_NUMBER" text="SMS_${i}_TEXT" eval "gammu-smsd-inject TEXT my_number_goes_here -text \"${!number}: ${!text}\"" done And here is the problem I am experiencing: Thu 2015/01/29 23:08:57 gammu-smsd[2549]: Starting run on receive: /var/spool/gammu/forward.sh IN20150130_000850_00_+37368214400_00.txt Thu 2015/01/29 23:08:57 gammu-smsd[2154]: Process failed with exit status 2 Output of ls -l /etc/gammu-smsdrc /var/spool/gammu/ /usr/bin/gammu-smsd*: -rw-r--r-- 1 root root 457 Jan 29 22:44 /etc/gammu-smsdrc -rwxrwxrwx 1 root root 14336 Jun 10 2012 /usr/bin/gammu-smsd -rwxrwxrwx 1 root root 51164 Jun 10 2012 /usr/bin/gammu-smsd-inject -rwxrwxrwx 1 root root 9972 Jun 10 2012 /usr/bin/gammu-smsd-monitor /var/spool/gammu/: total 24 drwxrwxrwx 2 gammu gammu 4096 Jan 28 16:02 error -rwxrwxrwx 1 gammu gammu 189 Jan 29 22:13 forward.sh drwxrwxrwx 2 gammu gammu 4096 Jan 29 23:08 inbox -rw-rw-r-- 1 gammu gammu 3702 Jan 29 23:08 log drwxrwxrwx 2 gammu gammu 4096 Jan 29 23:07 outbox drwxrwxrwx 2 gammu gammu 4096 Jan 29 23:07 sent What happens if I just do ./forward.sh (not root) - so all is OK: gammu-smsd-inject[2606]: Created outbox message OUTC20150029_231213_00_my_number_here_sms0.txt Written message with ID /var/spool/gammu/outbox/OUTC20150029_231213_00_my_number_here_sms0.txt Here is my /etc/gammu-smsdrc # Configuration file for Gammu SMS Daemon [gammu] port = /dev/ttyUSB0 connection = at [smsd] service = files logfile = /var/spool/gammu/log debuglevel = 2 commtimeout = 1 sendtimeout = 15 statusfrequency = 0 outboxformat = unicode transmitformat = unicode RunOnReceive = /var/spool/gammu/forward.sh inboxpath = /var/spool/gammu/inbox/ outboxpath = /var/spool/gammu/outbox/ sentsmspath = /var/spool/gammu/sent/ errorsmspath = /var/spool/gammu/error/ ps -fe | grep gammu: gammu 2154 1 0 23:05 ? 00:00:02 /usr/bin/gammu-smsd --daemon --user gammu --pid /var/run/gammu-smsd.pid cubie 2644 2403 0 23:20 pts/0 00:00:00 grep gammu Please, help A: I had the same problem and I solved it this way: * *First add gammu user to sudoers, with no password: type: $ sudo visudo and add: gammu ALL=(ALL) NOPASSWD: ALL *Then run gammu-smsd as root user: in /etc/init.d/gammu-smsd change USER=gammu to USER=root save it and don't forget to restart daemon: service gammu-smsd restart *In RunOnReceive script add sudo in front of gammu-smsd-inject: e.g.: sudo gammu-smsd-inject TEXT my_tel_num -text "Hello world!" I hope this will work for you too! P.S.: I use Gammu version 1.31.90.
{ "language": "en", "url": "https://stackoverflow.com/questions/28225682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What version of .NET does OTP.NET use? 1.1 or 2.0 runtime? Also has anyone got any exprience using OTP.NET? A: It's last version uses .NET Framework 2.0. Years ago I gave it a try. But that was not interesting to me those days. :(
{ "language": "en", "url": "https://stackoverflow.com/questions/7094761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to create correct JSON against csv file in Groovy within JSR Preprocessor Complete noob in JMeter.Been trying create a json using CSV file with Groovy and pass the same in the request body in jmeter but unable to create the JSON in required format: Sample2.csv Work Registration - External,3423,115 Jmeter HTTPRequest --JSR223Preprocessor For above csv, the following code in JSR223Preprocessor provides output import groovy.json.* def builder = new groovy.json.JsonBuilder() @groovy.transform.Immutable class WKList { String wkname int Wkid int numId } def WKLists = new File("Sample2.csv") .readLines() .collect { line -> new WKList(Integer.parseInt(line.split(",")[0]), Integer.parseInt(line.split(",")[1])),line.split(",")[2] } builder( Place:'RA', Serial: 2, SerialDate: 'Dec 30 ,2021', WKList: WKLists.collect(), ) log.info(builder.toPrettyString()) Output: { "Place": "RA", "Serial": 2, "SerialDate": "Dec 30 ,2021", "WKList": [ { "wkid": 3423, "numId": 115, "wkname": "Work Registration - External" } ] } First 3 columns are hardcoded. But if original csv file is as follows RA,8,Dec 30, 2021,Work Registration - External,3423,233 KA,92,Dec 20, 2021,State Registration - Internal,121,3 How can the code be modified to include values from csv rather than fetching hard coded values as done earlier ? Also if CSV Data Set Config JMeter is used, does it read per line for each user for each iteration ? A: This line looks very suspicious: new WKList(Integer.parseInt(line.split(",")[0]), Integer.parseInt(line.split(",")[1])),line.split(",")[2] } Your WKList class takes a String as a first parameter followed by 2 Integers So my expectation is that you should change it to something like: new WKList(line.split(",")[0], Integer.parseInt(line.split(",")[1]), Integer.parseInt(line.split(",")[2])) Also your code assumes the following CSV file structure: Work Registration - External,3423,115 If you need to include use the following file format: RA,8,Dec 30, 2021,Work Registration - External,3423,233 we need to know what is the "required format" of the JSON. In the meantime you can get familiarized with the following material: * *Apache Groovy - Parsing and producing JSON *Apache Groovy - Why and How You Should Use It A: This would work for csv file line RA,8,"Dec 30, 2021",Work Registration - External,3423,233 import groovy.json.* class WKList {String wkname; int Wkid ;int numId} List<WKList> WKDetList = new ArrayList<>(); def lines =new File("Sample2.csv").readLines() def content = [:] def articles = [] def article = [:] for (int i=1;i<lines.size();i++) { String[] splitData = lines[i].split(','); content.put('Place', splitData[0]) content.put('Serial', splitData[1]) content.put('SerialDate', splitData[2]) article.put('wkname', splitData[3]) article.put('wkid', splitData[4]) article.put('numId', splitData[5]) articles.add(article) content.put('WKList', articles) } sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(content).toPrettyString(), '') sampler.setPostBodyRaw(true) log.info(JsonOutput.prettyPrint(JsonOutput.toJson(content)))
{ "language": "en", "url": "https://stackoverflow.com/questions/70675822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to locally test a letsencrypt client? Is there a way to develop a letsencrypt ACME client locally without having a real domain that can be verified? Eg. would is there some test domain that can be used together with the LE sandbox server to fake successful domain verifications? Or is the only way to test and debug a letsencrypt client by deploying it to a real domain and generating real certificates? How could this be integrated into CI? A: The simplest way I could find is using https://ngrok.com/ - It opens a tunnel to your local webserver that can be browsed via a public subdomain on ngrok.io. You can then easily test the full circle of domain verification for this subdomain. You can even start multiple tunnels and have multiple subdomains for testing SAN certificates. ngrok provides a local Web-API from where the current tunnel address can be read, this way tests could be automated in continuous integration.
{ "language": "en", "url": "https://stackoverflow.com/questions/38977858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Not showing 10 random boxes $(function() { max = 25; min = 1; var i = 0; do { var match = Math.ceil(Math.random() * (max - min )- min); $('td').each(function() { i++; console.log( match ); if (i == match) { $(this).addClass('active'); } }) } while ($('td.active').length == 10); }) My problem is that I do not return 10 random boxes but only one. A: Change } while ( $('td.active').length == 10 ); to } while ( $('td.active').length < 10 ); while != until But if you have less than 10 td, you'll loop indefinitely. And it will very often break as i always grows bigger. I think you want this : $(function() { var max = 25; // don't forget the "var", if you don't want to declare global variables var min = 1; do { var match = Math.ceil(Math.random() * (max - min )- min); $('td').eq(match).addClass('active'); } while ($('td.active').length < 10); }) A: Try this : if you are sure that their are minimum 10 td's $(function() { max = 25; min = 1; var i = 0; var y=0; do { var match = Math.ceil(Math.random() * (max - min )- min); $('td').each(function() { i++; console.log( match ); if (i == match) { $(this).addClass('active'); y++; } }) } while (y<10); }) A: You haven't said much about what the code is attempting to do, but in addition to the other suggestions, I think you also mean var match= Math.ceil(Math.random() * (max - min )+ min); Note the '+ min' instead of minus.
{ "language": "en", "url": "https://stackoverflow.com/questions/14361151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binary XML file, Error inflating class I have searched for the issue, but haven't found a solution. This is my AndroidManifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.solinpromex.vivegrancanaria" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="19" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="key hidden"/> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CALL_PHONE"></uses-permission> <uses-permission android:name="android.permission.INTERNET"/> <permission android:name="com.solinpromex.vivegrancanaria.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name="com.solinpromex.vivegrancanaria.permission.MAPS_RECEIVE"/> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-feature android:glEsVersion="0x00020000" android:required="true"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.solinpromex.vivegrancanaria.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".categorias_list" android:label="Categorias de Ofertas y Descuentos"> </activity> <activity android:name=".SingleContactActivity" android:label="@string/app_name"> </activity> <activity android:name=".Empresas_MainActivity" android:label="@string/app_name"> </activity> <activity android:name=".Ofertas_list" android:label="@string/app_name"> </activity> <activity android:name=".Ofertas_Application" android:label="@string/app_name"> </activity> <activity android:name=".Ofertas_MainActivity" android:label="@string/app_name"> </activity> <activity android:name=".Ofertas_ApplicationAdapter" android:label="@string/app_name"> </activity> <activity android:name=".Ofertas_FetchDataListener" android:label="@string/app_name"> </activity> <activity android:name=".Ofertas_FetchDataTask" android:label="@string/app_name"> </activity> <activity android:name=".Empresas_SingleItemView" android:label="@string/app_name"> </activity> <activity android:name=".Facebook" android:label="@string/app_name"> </activity> <activity android:name=".Mapa_MainActivity" android:label="@string/app_name"> </activity> </application> </manifest> This is XML layout file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> And this my activity code: import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.app.Activity; import android.widget.Toast; public class Mapa_MainActivity extends FragmentActivity { private GoogleMap map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapa_activity_main); map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap(); } } And this log cat text for the exception: 04-19 18:51:35.817: E/AndroidRuntime(1482): FATAL EXCEPTION: main 04-19 18:51:35.817: E/AndroidRuntime(1482): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.solinpromex.vivegrancanaria/com.solinpromex.vivegrancanaria.Mapa_MainActivity}: android.view.InflateException: Binary XML file line #6: Error inflating class fragment 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.ActivityThread.access$600(ActivityThread.java:130) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.os.Handler.dispatchMessage(Handler.java:99) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.os.Looper.loop(Looper.java:137) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.ActivityThread.main(ActivityThread.java:4745) 04-19 18:51:35.817: E/AndroidRuntime(1482): at java.lang.reflect.Method.invokeNative(Native Method) 04-19 18:51:35.817: E/AndroidRuntime(1482): at java.lang.reflect.Method.invoke(Method.java:511) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 04-19 18:51:35.817: E/AndroidRuntime(1482): at dalvik.system.NativeStart.main(Native Method) 04-19 18:51:35.817: E/AndroidRuntime(1482): Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.Activity.setContentView(Activity.java:1867) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.solinpromex.vivegrancanaria.Mapa_MainActivity.onCreate(Mapa_MainActivity.java:23) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.Activity.performCreate(Activity.java:5008) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 04-19 18:51:35.817: E/AndroidRuntime(1482): ... 11 more 04-19 18:51:35.817: E/AndroidRuntime(1482): Caused by: java.lang.IllegalStateException: A required meta-data tag in your app's AndroidManifest.xml does not exist. You must have the following declaration within the <application> element: <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.common.GooglePlayServicesUtil.t(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.maps.internal.q.B(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.maps.internal.q.A(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.maps.SupportMapFragment$b.gW(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.maps.SupportMapFragment$b.a(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.dynamic.a.a(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.dynamic.a.onInflate(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:290) 04-19 18:51:35.817: E/AndroidRuntime(1482): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676) 04-19 18:51:35.817: E/AndroidRuntime(1482): ... 21 more What am I missing? A: Replace ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap(); with ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); plz update your minimum version to 12 and <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="key hidden"/> should be inside application tag A: In the XML you are using SupportMapFragment android:name="com.google.android.gms.maps.SupportMapFragment" hence you should use SupportMapFragment and getSupportFragmentManager instead of MapFragment and getFragmentManager map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap(); Change the above line to map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); I can see that you have android.support.v4.app.Fragment imported. Import com.google.android.gms.maps.SupportMapFragment Also make sure that you have android.support.v4.jar in your libs folder and in the project build path.
{ "language": "en", "url": "https://stackoverflow.com/questions/23174166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby/Rails CalDAV API So I've searched high and low for this, and I can't really seem to find anything conclusive. This seems to be the general case for most things concerning calendars, scheduling, events and the like. So I'm well along in my project, and I've been working on implementing calendaring, events and the like. Using full calendar with my rails app, it gets the job done. I've been thinking lately, I could get that to a suitable level, but because I can't find any comprehensive calendaring solution (can't imbed google calendar functionality etc), what if I created a "restful?" interface for CalDAV to connect to? I'm not quite sure where to begin, or if CalDAV even uses anything like a RESTful interface... How do Google and Apple do it? If I could get that working, then I could just let people use their calendar app of choice. Anyway. Do you guys have any thoughts or insights into this realm? Cheers! ~ D
{ "language": "en", "url": "https://stackoverflow.com/questions/15191623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error Create Datasource JBOSS 7.1.1 FINAL Error when deploying the server I get this error in jboss 7.1.1 final log Error: 09:44:28,645 INFORMACIร“N [org.jboss.modules] JBoss Modules version 1.1.1.GA 09:44:28,865 INFO [org.jboss.msc] JBoss MSC version 1.0.2.GA 09:44:28,935 INFO [org.jboss.as] JBAS015899: JBoss AS 7.1.1.Final "Brontes" starting 09:44:29,924 INFO [org.xnio] XNIO Version 3.0.3.GA 09:44:29,924 INFO [org.jboss.as.server] JBAS015888: Creating http management service using socket-binding (management-http) 09:44:29,944 INFO [org.xnio.nio] XNIO NIO Implementation Version 3.0.3.GA 09:44:29,954 INFO [org.jboss.remoting] JBoss Remoting version 3.2.3.GA 09:44:29,975 INFO [org.jboss.as.configadmin] JBAS016200: Activating ConfigAdmin Subsystem 09:44:29,988 INFO [org.jboss.as.logging] JBAS011502: Removing bootstrap log handlers 09:44:30,005 INFO [org.jboss.as.security] (ServerService Thread Pool -- 44) JBAS013101: Activating Security Subsystem 09:44:30,017 INFO [org.jboss.as.security] (MSC service thread 1-2) JBAS013100: Current PicketBox version=4.0.7.Final 09:44:30,067 INFO [org.jboss.as.naming] (ServerService Thread Pool -- 38) JBAS011800: Activating Naming Subsystem 09:44:30,097 INFO [org.jboss.as.osgi] (ServerService Thread Pool -- 39) JBAS011940: Activating OSGi Subsystem 09:44:30,097 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 31) JBAS010280: Activating Infinispan subsystem. 09:44:30,109 INFO [org.jboss.as.naming] (MSC service thread 1-4) JBAS011802: Starting Naming Service 09:44:30,125 INFO [org.jboss.as.webservices] (ServerService Thread Pool -- 48) JBAS015537: Activating WebServices Extension 09:44:30,179 INFO [org.jboss.as.mail.extension] (MSC service thread 1-3) JBAS015400: Bound mail session [java:jboss/mail/Default] 09:44:30,241 INFO [org.jboss.as.connector] (MSC service thread 1-5) JBAS010408: Starting JCA Subsystem (JBoss IronJacamar 1.0.9.Final) 09:44:30,341 INFO [org.jboss.ws.common.management.AbstractServerConfig] (MSC service thread 1-5) JBoss Web Services - Stack CXF Server 4.0.2.GA 09:44:30,350 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3) 09:44:30,386 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010404: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1) 09:44:30,390 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010404: Deploying non-JDBC-compliant driver class com.mysql.fabric.jdbc.FabricMySQLDriver (version 5.1) 09:44:30,393 ERROR [org.jboss.as.controller.management-operation] (ServerService Thread Pool -- 27) JBAS014612: Operation ("add") failed - address: ([ ("subsystem" => "datasources"), ("jdbc-driver" => "mysql") ]): org.jboss.msc.service.DuplicateServiceException: Service jboss.jdbc-driver.mysql is already registered at org.jboss.msc.service.ServiceRegistrationImpl.setInstance(ServiceRegistrationImpl.java:154) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceControllerImpl.startInstallation(ServiceControllerImpl.java:227) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceContainerImpl.install(ServiceContainerImpl.java:560) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceTargetImpl.install(ServiceTargetImpl.java:201) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceControllerImpl$ChildServiceTarget.install(ServiceControllerImpl.java:2228) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceBuilderImpl.install(ServiceBuilderImpl.java:307) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.as.controller.OperationContextImpl$ContextServiceBuilder.install(OperationContextImpl.java:955) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.connector.subsystems.datasources.JdbcDriverAdd.startDriverServices(JdbcDriverAdd.java:164) [jboss-as-connector-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.connector.subsystems.datasources.JdbcDriverAdd.performRuntime(JdbcDriverAdd.java:128) [jboss-as-connector-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractAddStepHandler$1.execute(AbstractAddStepHandler.java:50) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:385) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:272) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.completeStep(AbstractOperationContext.java:200) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.connector.subsystems.datasources.DataSourceEnable$1.execute(DataSourceEnable.java:91) [jboss-as-connector-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:385) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:272) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.completeStep(AbstractOperationContext.java:200) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.connector.subsystems.datasources.DataSourceEnable$1.execute(DataSourceEnable.java:91) [jboss-as-connector-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:385) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:272) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.AbstractOperationContext.completeStep(AbstractOperationContext.java:200) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.controller.ParallelBootOperationStepHandler$ParallelBootTask.run(ParallelBootOperationStepHandler.java:311) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final] at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_72] at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_72] at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_72] at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.0.0.GA.jar:2.0.0.GA] 09:44:30,836 INFO [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-4) Arrancando Coyote HTTP/1.1 en puerto http-localhost-127.0.0.1-8080 jboss-as-7.1.1.Final\standalone\configuration\standalone.xml <?xml version='1.0' encoding='UTF-8'?> <server xmlns="urn:jboss:domain:1.2"> <extensions> <extension module="org.jboss.as.clustering.infinispan"/> <extension module="org.jboss.as.configadmin"/> <extension module="org.jboss.as.connector"/> <extension module="org.jboss.as.deployment-scanner"/> <extension module="org.jboss.as.ee"/> <extension module="org.jboss.as.ejb3"/> <extension module="org.jboss.as.jaxrs"/> <extension module="org.jboss.as.jdr"/> <extension module="org.jboss.as.jmx"/> <extension module="org.jboss.as.jpa"/> <extension module="org.jboss.as.logging"/> <extension module="org.jboss.as.mail"/> <extension module="org.jboss.as.naming"/> <extension module="org.jboss.as.osgi"/> <extension module="org.jboss.as.pojo"/> <extension module="org.jboss.as.remoting"/> <extension module="org.jboss.as.sar"/> <extension module="org.jboss.as.security"/> <extension module="org.jboss.as.threads"/> <extension module="org.jboss.as.transactions"/> <extension module="org.jboss.as.web"/> <extension module="org.jboss.as.webservices"/> <extension module="org.jboss.as.weld"/> </extensions> <management> <security-realms> <security-realm name="ManagementRealm"> <authentication> <properties path="mgmt-users.properties" relative-to="jboss.server.config.dir"/> </authentication> </security-realm> <security-realm name="ApplicationRealm"> <authentication> <properties path="application-users.properties" relative-to="jboss.server.config.dir"/> </authentication> </security-realm> </security-realms> <management-interfaces> <native-interface security-realm="ManagementRealm"> <socket-binding native="management-native"/> </native-interface> <http-interface security-realm="ManagementRealm"> <socket-binding http="management-http"/> </http-interface> </management-interfaces> </management> <profile> <subsystem xmlns="urn:jboss:domain:logging:1.1"> <console-handler name="CONSOLE"> <level name="INFO"/> <formatter> <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/> </formatter> </console-handler> <periodic-rotating-file-handler name="FILE"> <formatter> <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/> </formatter> <file relative-to="jboss.server.log.dir" path="server.log"/> <suffix value=".yyyy-MM-dd"/> <append value="true"/> </periodic-rotating-file-handler> <logger category="com.arjuna"> <level name="WARN"/> </logger> <logger category="org.apache.tomcat.util.modeler"> <level name="WARN"/> </logger> <logger category="sun.rmi"> <level name="WARN"/> </logger> <logger category="jacorb"> <level name="WARN"/> </logger> <logger category="jacorb.config"> <level name="ERROR"/> </logger> <root-logger> <level name="INFO"/> <handlers> <handler name="CONSOLE"/> <handler name="FILE"/> </handlers> </root-logger> </subsystem> <subsystem xmlns="urn:jboss:domain:configadmin:1.0"/> <subsystem xmlns="urn:jboss:domain:datasources:1.0"> <datasources> <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true"> <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url> <driver>h2</driver> <security> <user-name>sa</user-name> <password>sa</password> </security> </datasource> <datasource jndi-name="java:jboss/datasources/EvelingDs" pool-name="EvelingDs" enabled="true" use-java-context="true"> <connection-url>jdbc:mysql://localhost:3306/proyectoEveling</connection-url> <driver>mysql</driver> <security> <user-name>infra</user-name> <password>infra_pass</password> </security> </datasource> <drivers> <driver name="h2" module="com.h2database.h2"> <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class> </driver> <driver name="mysql" module="com.mysql"/> </drivers> </datasources> </subsystem> <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1"> <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000"/> </subsystem> <subsystem xmlns="urn:jboss:domain:ee:1.0"/> <subsystem xmlns="urn:jboss:domain:ejb3:1.2"> <session-bean> <stateless> <bean-instance-pool-ref pool-name="slsb-strict-max-pool"/> </stateless> <stateful default-access-timeout="5000" cache-ref="simple"/> <singleton default-access-timeout="5000"/> </session-bean> <pools> <bean-instance-pools> <strict-max-pool name="slsb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/> <strict-max-pool name="mdb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/> </bean-instance-pools> </pools> <caches> <cache name="simple" aliases="NoPassivationCache"/> <cache name="passivating" passivation-store-ref="file" aliases="SimpleStatefulCache"/> </caches> <passivation-stores> <file-passivation-store name="file"/> </passivation-stores> <async thread-pool-name="default"/> <timer-service thread-pool-name="default"> <data-store path="timer-service-data" relative-to="jboss.server.data.dir"/> </timer-service> <remote connector-ref="remoting-connector" thread-pool-name="default"/> <thread-pools> <thread-pool name="default"> <max-threads count="10"/> <keepalive-time time="100" unit="milliseconds"/> </thread-pool> </thread-pools> </subsystem> <subsystem xmlns="urn:jboss:domain:infinispan:1.2" default-cache-container="hibernate"> <cache-container name="hibernate" default-cache="local-query"> <local-cache name="entity"> <transaction mode="NON_XA"/> <eviction strategy="LRU" max-entries="10000"/> <expiration max-idle="100000"/> </local-cache> <local-cache name="local-query"> <transaction mode="NONE"/> <eviction strategy="LRU" max-entries="10000"/> <expiration max-idle="100000"/> </local-cache> <local-cache name="timestamps"> <transaction mode="NONE"/> <eviction strategy="NONE"/> </local-cache> </cache-container> </subsystem> <subsystem xmlns="urn:jboss:domain:jaxrs:1.0"/> <subsystem xmlns="urn:jboss:domain:jca:1.1"> <archive-validation enabled="true" fail-on-error="true" fail-on-warn="false"/> <bean-validation enabled="true"/> <default-workmanager> <short-running-threads> <core-threads count="50"/> <queue-length count="50"/> <max-threads count="50"/> <keepalive-time time="10" unit="seconds"/> </short-running-threads> <long-running-threads> <core-threads count="50"/> <queue-length count="50"/> <max-threads count="50"/> <keepalive-time time="10" unit="seconds"/> </long-running-threads> </default-workmanager> <cached-connection-manager/> </subsystem> <subsystem xmlns="urn:jboss:domain:jdr:1.0"/> <subsystem xmlns="urn:jboss:domain:jmx:1.1"> <show-model value="true"/> <remoting-connector/> </subsystem> <subsystem xmlns="urn:jboss:domain:jpa:1.0"> <jpa default-datasource=""/> </subsystem> <subsystem xmlns="urn:jboss:domain:mail:1.0"> <mail-session jndi-name="java:jboss/mail/Default"> <smtp-server outbound-socket-binding-ref="mail-smtp"/> </mail-session> </subsystem> <subsystem xmlns="urn:jboss:domain:naming:1.1"/> <subsystem xmlns="urn:jboss:domain:osgi:1.2" activation="lazy"> <properties> <!-- Specifies the beginning start level of the framework --> <property name="org.osgi.framework.startlevel.beginning">1</property> </properties> <capabilities> <!-- modules registered with the OSGi layer on startup --> <capability name="javax.servlet.api:v25"/> <capability name="javax.transaction.api"/> <!-- bundles started in startlevel 1 --> <capability name="org.apache.felix.log" startlevel="1"/> <capability name="org.jboss.osgi.logging" startlevel="1"/> <capability name="org.apache.felix.configadmin" startlevel="1"/> <capability name="org.jboss.as.osgi.configadmin" startlevel="1"/> </capabilities> </subsystem> <subsystem xmlns="urn:jboss:domain:pojo:1.0"/> <subsystem xmlns="urn:jboss:domain:remoting:1.1"> <connector name="remoting-connector" socket-binding="remoting" security-realm="ApplicationRealm"/> </subsystem> <subsystem xmlns="urn:jboss:domain:resource-adapters:1.0"/> <subsystem xmlns="urn:jboss:domain:sar:1.0"/> <subsystem xmlns="urn:jboss:domain:security:1.1"> <security-domains> <security-domain name="other" cache-type="default"> <authentication> <login-module code="Remoting" flag="optional"> <module-option name="password-stacking" value="useFirstPass"/> </login-module> <login-module code="RealmUsersRoles" flag="required"> <module-option name="usersProperties" value="${jboss.server.config.dir}/application-users.properties"/> <module-option name="rolesProperties" value="${jboss.server.config.dir}/application-roles.properties"/> <module-option name="realm" value="ApplicationRealm"/> <module-option name="password-stacking" value="useFirstPass"/> </login-module> </authentication> </security-domain> <security-domain name="jboss-web-policy" cache-type="default"> <authorization> <policy-module code="Delegating" flag="required"/> </authorization> </security-domain> <security-domain name="jboss-ejb-policy" cache-type="default"> <authorization> <policy-module code="Delegating" flag="required"/> </authorization> </security-domain> </security-domains> </subsystem> <subsystem xmlns="urn:jboss:domain:threads:1.1"/> <subsystem xmlns="urn:jboss:domain:transactions:1.1"> <core-environment> <process-id> <uuid/> </process-id> </core-environment> <recovery-environment socket-binding="txn-recovery-environment" status-socket-binding="txn-status-manager"/> <coordinator-environment default-timeout="300"/> </subsystem> <subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false"> <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/> <virtual-server name="default-host" enable-welcome-root="true"> <alias name="localhost"/> <alias name="example.com"/> </virtual-server> </subsystem> <subsystem xmlns="urn:jboss:domain:webservices:1.1"> <modify-wsdl-address>true</modify-wsdl-address> <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host> <endpoint-config name="Standard-Endpoint-Config"/> <endpoint-config name="Recording-Endpoint-Config"> <pre-handler-chain name="recording-handlers" protocol-bindings="##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM"> <handler name="RecordingHandler" class="org.jboss.ws.common.invocation.RecordingServerHandler"/> </pre-handler-chain> </endpoint-config> </subsystem> <subsystem xmlns="urn:jboss:domain:weld:1.0"/> </profile> <interfaces> <interface name="management"> <inet-address value="${jboss.bind.address.management:127.0.0.1}"/> </interface> <interface name="public"> <inet-address value="${jboss.bind.address:127.0.0.1}"/> </interface> <!-- TODO - only show this if the jacorb subsystem is added --> <interface name="unsecure"> <!-- ~ Used for IIOP sockets in the standard configuration. ~ To secure JacORB you need to setup SSL --> <inet-address value="${jboss.bind.address.unsecure:127.0.0.1}"/> </interface> </interfaces> <socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}"> <socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}"/> <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/> <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9443}"/> <socket-binding name="ajp" port="8009"/> <socket-binding name="http" port="8080"/> <socket-binding name="https" port="8443"/> <socket-binding name="osgi-http" interface="management" port="8090"/> <socket-binding name="remoting" port="4447"/> <socket-binding name="txn-recovery-environment" port="4712"/> <socket-binding name="txn-status-manager" port="4713"/> <outbound-socket-binding name="mail-smtp"> <remote-destination host="localhost" port="25"/> </outbound-socket-binding> </socket-binding-group> </server> jboss-as-7.1.1.Final\modules\com\mysql\module.xml <module xmlns="urn:jboss:module:1.1" name="com.mysql"> <resources> <resource-root path="mysql-connector-java-5.1.34-bin.jar"/> <!-- Insert resources here --> </resources> <dependencies> <module name="javax.api"/> <module name="javax.transaction.api"/> <module name="javax.servlet.api" optional="true"/> </dependencies> </module> Thank you for the help you can... A: Although this one looks old for the benefit of others who happen to stumble upon the same one please add <driver-class>com.mysql.jdbc.Driver</driver-class> to your driver definition in standalone.xml complete entry <drivers> <driver name="com.mysql" module="com.mysql"> <driver-class>com.mysql.jdbc.Driver</driver-class> <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class> </driver> </drivers>
{ "language": "en", "url": "https://stackoverflow.com/questions/26803956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: unable to use R's future package for lasso regression with glmnet I recently discovered R's future package and have already successfully used it. However I am unable to use this package together with predictions for lasso regressions. In the following toy example I first create some toy data, then fit a lasso regression and finally I make a prediction for new data. I do this procedure twice: once without the future package and then with the future package: library(tidyverse) library(glmnet) set.seed(1) a <- tibble(id = rep(letters[1:2], each = 100), x1 = rnorm(200), x2 = rnorm(200), y = 1 + 2*x2 + rnorm(200)) newdata <- as.matrix(data.frame(x1 = rnorm(200), x2 = rnorm(200))) pred_func <- function(z) predict(z, newx = newdata)[,1] b1 <- a %>% group_by(id) %>% nest(.key = data) %>% mutate(lasso = map(data, function(z){glmnet(x = as.matrix(select(z, x1, x2)), y = z$y, intercept = T, alpha = 1)})) %>% mutate(myprediction = map(lasso, pred_func)) This works just fine. Now with the future package: library(future) plan(multiprocess) b2 <- a %>% group_by(id) %>% nest(.key = data) %>% mutate(lasso = map(data, function(z){glmnet(x = as.matrix(select(z, x1, x2)), y = z$y, intercept = T, alpha = 1)})) %>% mutate(myprediction_future = map(lasso, ~future(pred_func(.x)))) %>% mutate(myprediction = values(myprediction_future)) This terminates with an error (which is in german). Basically it tells me that it cannot use predict for an object of class elnet, glmnet. I first thought that maybe there is a different predict function in the future package but this does not seem to be the case. Since I do not really understand what happens behind the curtains of the future functions I feel stuck with this one. EDIT: here is the error message in english: Error in mutate_impl(.data, dots) : Evaluation error: no applicable method for 'predict' applied to an object of class "c('elnet', 'glmnet')". A: There's a predict.glmnet() in glmnet package. Just define a new function. pred_func2 <- function(z) predict.glmnet(z, newx = newdata)[,1] And run. plan(multiprocess) b2 <- a %>% group_by(id) %>% nest(.key=data) %>% mutate(lasso=map(data, function(z) { glmnet(x=as.matrix(select(z, x1, x2)), y=z$y, intercept=TRUE, alpha=1) })) %>% mutate(myprediction_future=map(lasso, ~future(pred_func2(.x)))) %>% mutate(myprediction=values(myprediction_future)) Yielding > b2 # A tibble: 2 x 5 id data lasso myprediction_future myprediction <chr> <list> <list> <list> <list> 1 a <tibble [100 x 3]> <S3: elnet> <S3: MultisessionFuture> <dbl [200]> 2 b <tibble [100 x 3]> <S3: elnet> <S3: MultisessionFuture> <dbl [200]>
{ "language": "en", "url": "https://stackoverflow.com/questions/51533058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP ftp_connect does nothing I've configured a couple of php codes that connects to my server with the use of ftp connect. It works perfectly when I'm testing it locally, it connects, it goes in, i can access stuff. BUT when I upload it online and try it there. The php code does nothing. It executes all lines before "ftp_connect" then from that line onwards, it doesn't get processed. It doesn't show any errors, warnings, etc on screen but the code execution from the line of "ftp_connect" just stops. What seems to be the problem? A: Your host probably has error reporting turned off, try turning on error reporting with ini_set('display_errors',1); error_reporting(E_ALL|E_STRICT); at the top of your file, or check for a file called error_log in the directory of your script.
{ "language": "en", "url": "https://stackoverflow.com/questions/1954890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Did the city search data from the Facebook Ads API suddenly change? The City Search call used to return a response where each city had the form: { "name": "Dublin, CA", "key": 220522764, "subtext": "CA, United States" } Now the API returns: { "name": "Dublin", "key": 220522764, "subtext": "California, United States" } The first format is still listed in the API docs here: https://developers.facebook.com/docs/reference/ads-api/get-autocomplete-data/ Is this a permanent change? A: Yes, last week. No warning from Facebook. A: Our apologies for this change - we've reverted this change and will take precaution to avoid these things in the future. Thank you for the report. We've added another parameter to use in your query if you want to get the city name without the state. Documentation updated: https://developers.facebook.com/docs/reference/ads-api/get-autocomplete-data/
{ "language": "en", "url": "https://stackoverflow.com/questions/16847107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Task timed out after..." when connecting to a MongoDB database in an AWS Lambda function I am have Node.js script where in the beginning of it I connect to my MongoDB database and get a specific collection and use that within the script. I set this script up in an AWS Lambda function with a timeout of 10 seconds. When I test the AWS Lambda with a configured test event, I get a "Task timed out after 10.00 seconds". My script is still suppose to run after it connects and finish the rest of the script. However, it stops and I get a timeout error from AWS Lambda. If I set a timeout higher, such as 15 minutes, I get the timeout error 15 minutes after I connect to the MongoDB database within the script (I got this my looking at the CloudWatch logs for the AWS Lambda function). I experimented with different timeout timings and found that for x seconds I set the timeout, my script will give the timeout error x seconds after I connect to the MongoDB database. I followed all best practices mentioned in this article about connecting to MongoDB from AWS Lambda and they are are: defining the MongoDB client connection outside the handler function and setting the context property callbackWaitsForEmptyEventLoop to false. I am not sure how to fix this. Below is some relevant code I used in my script: main.ts: import { connectToDatabase } from './mongodb' import mongodb from 'mongodb' export const handler = async (event: any, context: any, callback: any) => { context.callbackWaitsForEmptyEventLoop = false const db = await connectToDatabase().then((db: mongodb.Db) => db).catch(error => error) var collection: mongodb.Collection = db.collection("{collection-name}") // Rest of the script } mongodb.ts: import mongodb, { MongoClient } from "mongodb" let uri: undefined | string = process.env.MONGODB_URI let dbName: undefined | string = process.env.MONGODB_DB let cachedClient: null | mongodb.MongoClient = null let cachedDb: null | mongodb.Db = null export async function connectToDatabase() { if (cachedClient && cachedDb) { return cachedDb } if (!uri) { throw new Error( "Please define the MONGODB_URI environment variable inside .env.local" ) } if (!dbName) { throw new Error( "Please define the MONGODB_DB environment variable inside .env.local" ) } const client = await MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, }) const db = client.db(dbName) cachedClient = client cachedDb = db return db } Other info: I use serverless to push the script to AWS Lambda and also using serverless plugin "serverless-webpack" for TypeScript files. A: The best practice linked in your article says Define the MongoDB client connection outside of your handler function. In your case you should change const db = ... to db = ... and declare db outside of your handler function and change it to let db = null like in the example in the article, so you can reuse the connections in different Lambda invocations. For example: let db = null; export const handler = async (event, context, callback) => { if (!db) { db = connectToDatabase(); } // do something with your db callback(); }; Besides that, take @hoangdv 's advice and call the callback function to signal AWS Lambda that you're done with handling the event. That should do the trick. A: I found that AWS Lambda functions can only run for a maximum of 15 minutes (even if the code is still running after that amount of time). If I wanted to run the script for more than 15 minutes, I guess I would have to use an AWS EC2 instance. Source: https://aws.amazon.com/lambda/faqs/ A: I have a similar issue with trying so many different approaches, having a larger maximum memory, and having a longer latency time. but they fail to solve it. Then I found a solution by not using the whole parameter, its' value may be changed, outside of functions. Because cache can store the param in memory. it may lead the program to read the value from cache memory. So put cachedClient, cachedDb defining in function:connectToDatabase not out of function.
{ "language": "en", "url": "https://stackoverflow.com/questions/65856399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't the 'Add' type satisfy the constraint 'number'? I tried practicing type gymnastics with typescript.And my goal is Implementing mathematical operations on numeric literals. First of all,I implemented type BuildArray: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown[] = [] > = Arr['length'] extends Length ? Arr : BuildArray<Length, Ele, [...Arr, Ele]>; type MyArray = BuildArray<3> // type MyArray = [unknown, unknown, unknown] Then,I implemented type Add: type Add<Num1 extends number, Num2 extends number> = [...BuildArray<Num1>, ...BuildArray<Num2>]['length'] type AddResult = Add<2, 5> // type AddResult = 7 However, when I tried implementing Multiply based on Add,it occured error: type Multiply<Num1 extends number, Num2 extends number, Counter extends number = 0, Result extends number = 0> = Counter extends Num2? Result: Multiply<Num1, Num2, Add<Counter, 1>, Add<Num1, Result>> type MultiplyResult = Multiply<4, 5> // type MultiplyResult = 20 Though the result is correct, it occured compile error: Playground link Can someone please tell me why this compilation error occurs? A: When you are passing Counter in Add<Counter, 1>, it's extending the type number, but it's still unknown number. When it's passed from Add to BuildArray, you then have this check: Arr['length'] extends Length? and based on that check, you have different expected types Arr or BuildArray<Length, Ele, [...Arr, Ele]> which will again have the same issue. Going back to Add, in the case of unknown number, TypeScript won't achieve that this length prop is the prop of an Array, which is already a number. So you get the value correctly, but the type itself is still not sure that this is a number, because the check Arr['length'] extends Length? in BuildArray is not resolved to know that the Arr is the type that we are trying to access length from. I am not sure if this was clear enough, but TL;DR: To achieve what you need with the minimum changes, you need to tell TypeScript that this Add type will always be a number instead of relying on TypeScript to learn that by itself. For example, you can force this info by adding & number: type Add<Num1 extends number, Num2 extends number> = [...BuildArray<Num1>, ...BuildArray<Num2>]['length'] & number // โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’โˆ’^^^^^^^^ or have any kind of type checks. Playground link A: This is because here you are extending with number Counter extends number = 0, Result extends number = 0 and your Add<num1, num2> type returns a narrowed number. For example: type AddResult = Add<2, 5> // type AddResult = 7 when you do typeof AddResult, the output would be 7 (for TS it is unknown) and not number and that's why the error occured.
{ "language": "en", "url": "https://stackoverflow.com/questions/73863654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Doctrine2 Custom Type Not Returning Data iam regreting for last two days since came to my mind that i could create encrypted custom type, so that encryption and decryption of data would be done in that type so that i dont need to call those functions evrytime, generally to make my life easier but it turn it into living hell :/ My custom type is inserting encrypted data in the database as i intended but problem is when i need to retrive data, here is print of object that holds retrived data from database Uapi\CoreBundle\Entity\Request Object ( [id:Uapi\CoreBundle\Entity\Request:private] => 2 [clientIPAdress:Uapi\CoreBundle\Entity\Request:private] => [clientHost:Uapi\CoreBundle\Entity\Request:private] => [clientISP:Uapi\CoreBundle\Entity\Request:private] => [clientOS:Uapi\CoreBundle\Entity\Request:private] => [clientOSVersion:Uapi\CoreBundle\Entity\Request:private] => [clientBrowser:Uapi\CoreBundle\Entity\Request:private] => [clientBrowserVersion:Uapi\CoreBundle\Entity\Request:private] => [clientLanguage:Uapi\CoreBundle\Entity\Request:private] => [clientCountry:Uapi\CoreBundle\Entity\Request:private] => [clientCity:Uapi\CoreBundle\Entity\Request:private] => [possibleProxy:Uapi\CoreBundle\Entity\Request:private] => [proxyIPAdress:Uapi\CoreBundle\Entity\Request:private] => [torExitNode:Uapi\CoreBundle\Entity\Request:private] => [maliciousInput:Uapi\CoreBundle\Entity\Request:private] => [maliciousInputLog:Uapi\CoreBundle\Entity\Request:private] => [serverIPAdress:Uapi\CoreBundle\Entity\Request:private] => [serverPort:Uapi\CoreBundle\Entity\Request:private] => [requestMethod:Uapi\CoreBundle\Entity\Request:private] => [requestTimeFloat:Uapi\CoreBundle\Entity\Request:private] => P๏ฟฝa๏ฟฝ; ) Here is my Encrypted type class definition use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Platforms\AbstractPlatform; use Uapi\CoreBundle\Provider\EncryptionProvider; class EncryptedType extends Type { const ENCRYPTED = 'encrypted'; public function getName() { return self::ENCRYPTED; } public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); } public function convertToDatabaseValue($value, AbstractPlatform $platform) { return ($value === null)? null : base64_encode(EncryptionProvider::getCrypter()->encrypt($value)); } public function convertToPHPValue($value, AbstractPlatform $platform) { return ($value === null)? null : base64_decode(EncryptionProvider::getCrypter()->decrypt($value)); } } And i did register it within boot function in core bundle class $connection = $this->container->get('doctrine')->getConnection(); if(!Type::hasType('encrypted')) { Type::addType('encrypted', 'Uapi\CoreBundle\System\DBALType\EncryptedType'); $connection->getDatabasePlatform()->registerDoctrineTypeMapping('encrypted', 'encrypted'); } A: I did fix this on my own, its not general issue but ill explain here.I needed to firstly define a EncryptionProvider wich is my class that implements PHPSecLib\AES.So this is correct public function boot() { new EncryptionInit(); EncryptionProvider::setCrypter(EncryptionProvider::AES, $this->container->getParameter('uapi_core.security_key'), $x = array()); $connection = $this->container->get('doctrine')->getConnection(); if(!Type::hasType('encrypted')) { Type::addType('encrypted', 'Uapi\CoreBundle\System\DBALType\EncryptedType'); $connection->getDatabasePlatform()->registerDoctrineTypeMapping('encrypted', 'encrypted'); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/20253166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Ansible to create AWS Application Load Balancer rules I'm trying to use Ansible to create rules for an unconfigured HTTP listener on my existing ALB. I kick things off by retrieving facts for the alb and then use those facts to define an Ansible ALB resource adding the rules I want, but I'm hitting an issue. I would like Ansible to loop through my group_vars file (which it already does for other tasks successfully) to create these multiple rules. However when looping through, instead of appending rules to the listener it destroys/creates them. So when the playbook completes you are just left with a single rule referencing whichever item is defined at the end of the vars file (in my case Surrey). My code is below (for the sake of brevity I have excluded the parts which get & set facts): - name: Add HTTP listener rules elb_application_lb: state: present name: "{{ albinfo.load_balancer_name }}" subnets: - "{{ albinfo.availability_zones[0].subnet_id }}" - "{{ albinfo.availability_zones[1].subnet_id }}" - "{{ albinfo.availability_zones[2].subnet_id }}" security_groups: - "{{ albinfo.security_groups[0] }}" listeners: - Protocol: HTTP Port: 80 DefaultActions: - Type: forward TargetGroupName: default Rules: - Conditions: - Field: host-header Values: "{{ item.url }}" Priority: "{{ item.priority }}" Actions: - TargetGroupName: "{{ item.name }}" Type: forward purge_listeners: no with_items: "{{ regions }}" And my "regions" vars file looks like this: regions: - name: manchester priority: 1 url: - manchester.example.com - name: surrey priority: 2 url: - surrey.example.com A: The way you are using with_items to iterate the elb_application_lb module will not work as you have found out. Executing multiple commands will have the effect that the last one will 'win', as it will overwrite the existing elb rule set. What you would need to do is define each rule on a single call to elb_application_lb instead, you can not layer on rules with multiple calls to this module. You might be able to create a dict that defines all your rules instead like this: - name: Add HTTP listener rules elb_application_lb: state: present name: "{{ albinfo.load_balancer_name }}" subnets: - "{{ albinfo.availability_zones[0].subnet_id }}" - "{{ albinfo.availability_zones[1].subnet_id }}" - "{{ albinfo.availability_zones[2].subnet_id }}" security_groups: - "{{ albinfo.security_groups[0] }}" listeners: - Protocol: HTTP Port: 80 DefaultActions: - Type: forward TargetGroupName: default Rules: - "{{ region_rules }}" purge_listeners: no Where region rules var looks like this: region_rules: - Conditions: - Field: host-header Values: manchester.example.com Priority: 1 Actions: - TargetGroupName: manchester Type: forward - Conditions: - Field: host-header Values: surrey.example.com Priority: 2 Actions: - TargetGroupName: surrey Type: forward
{ "language": "en", "url": "https://stackoverflow.com/questions/48566902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any reason to make a template template parameter non variadic? If I expect a template template parameter to have one arguement then I could declare it as follows: template<template<typename> class T> struct S { T<int> t_; //other code here } however if I later want to provide a template template parameter which takes two arguements where the second has a default value (like std::vector) T<int> t_; would still work but the template would not match template<typename> class T. I could fix this by making template<typename> class T into a variadic template template template<typename...> class T. Now my code is more flexible. Should I make all my template template parameters variadic in future? Is there any reason I should not (assuming C++11 support is already required for my code for other reasons)? A: First, documentation. If the parameter is variadic, the user now needs to check some other source to find out that this really wants something that will takes one template parameter. Second, early checking. If you accidentally pass two arguments to T in S, the compiler won't tell you if it's variadic until a user actually tries to use it. Third, error messages. If the user passes a template that actually needs two parameters, in the variadic version the compiler will give him an error message on the line where S instantiates T, with all the backtrace stuff in-between. In the fixed version, he gets the error where he instantiates S. Fourth, it's not necessary, because template aliases can work around the issue too. S<vector> s; // doesn't work // but this does: template <typename T> using vector1 = vector<T>; S<vector1> s; So my conclusion is, don't make things variadic. You don't actually gain flexibility, you just reduce the amount of code the user has to write a bit, at the cost of poorer readability. A: If you know already that you will need it with high probability, you should add it. Otherwise, You Ain't Gonna Need It (YAGNI) so it would add more stuff to maintain. It's similar to the decision to have a template parameter in the first place. Especially in a TDD type of environment, you would refactor only when the need arises, rather than do premature abstraction. Nor is it a good idea to apply rampant abstraction to every part of the application. Rather, it requires a dedication on the part of the developers to apply abstraction only to those parts of the program that exhibit frequent change. Resisting premature abstraction is as important as abstraction itself Robert C. Martin Page 132, Agile Principles, Patterns and Practices in C# The benefits of variadic templates can be real, as you point out yourself. But as long as the need for them is still speculative, I wouldn't add them.
{ "language": "en", "url": "https://stackoverflow.com/questions/21042024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to deliver multiple application versions without confusion? We currently work on multiple branches of our web application. The VCS of choice is SVN. We have: * *v1: /trunk, live application, bugfixing *v2: /branches/1, additional features, without trunk bugfixes There are more steps planned. The current plan is to have a stable and client accepted v1 and then merge v2 into v1. At that point it's for sure that v3 will pop up. The problem is that the client needs more transparency, he can currently only see and test v1. If i'd make v2 available to them too, it's very likely that they can't tell the versions apart and report v1 (fixed) bugs again for v2. It would be a mess, imo. I also don't like the idea of a daily merge because it would be even harder to tell new and old bugs apart. I have the feeling that this is more a problem with our development process than an technical one. Any inspirations to solve the problem or to make both sides feel more convenient about future development are welcome. Thanks. edit One partial problem is also that my co-workers aren't too deep into version-control, using 2 branches is already inconvenient for them. However if i find a better strategy i'll probably force them to do it right. edit2 Thanks all for the answers. After some thinking it turns out that the whole problem is even bigger, because we keep binary files within SVN. Without very strict policies merging will be impossible and probably will be crippled anyway. A: It seems kind of unorganized. Merging version 2 into version 1? Eh? What version are you left with? Still version 1? With the features of version 2? Wha..? What I like for smallish projects: Trunk: This is where things get committed when the developer is confident that it's working. Do internal QA testing on the trunk. Tags: Make a new tag for each release, by copying from the trunk. Name your tags "/tags/v1.0" or "/tags/v1.1" or however you want to do it. If you need an external client to test something, name your tag something like "/tags/v1.0-beta" and give them that to test. Don't let them test with the trunk, because while they're testing you're still going to be developing! Branches: When you've got a feature that's going to take some time to develop, you can't commit it to the trunk before it's done. Make a branch. Name it after the feature you're implementing, like "/branches/user_logins". Bugfixes get committed to the trunk and are included in the next tagged release. If there's an emergency bugfix which must be released TODAY, but there's stuff in the trunk which can not yet be released yet, make another tag but copy from the tag of the buggy release instead of from the trunk, call it something like "v1.0.1", fix the bug there, give them a new release, and then merge that bugfix into the trunk. A: * *"without trunk bugfixes" *"it would be even harder to tell new and old bugs apart." *"I have the feeling that this is more a problem with our development process than an technical one." Damn straight. Your development process fails to acknowledge failures in V1. How can you hope that V2 will be better than V1 if you don't carry over the corrections in V1 to V2?! Bug fixes are always more important than new features. If the old features are broken and not worth fixing then remove them. Get off your lazy ass; if you, or someone, has made the effort to fix a defect in V1, then make sure it doesn't reappear in V2. FIX IT! If your code is so rubbish that this is a daily occurrence then stop working on V2 and focus on getting the bug fixes down to less often. If you can't get V1 features working properly then you'll never make it to V3. I might also suggest "mercurial" or "git" or "bazaar" rather than svn. They're much better at keeping management types at bay if you find and use the "cherrypicking" and "queue" functionalities: you can add a feature and pull the-ONE-that-management-think-will-save-them into production without pulling all the other half-baked ideas they came up with then abandoned. If politics prevent a move to distributed version control just use it yourself and only push the stuff you deliver (and they want) to svn. A: For me it seems that you switched the terms branch and trunk. Normally trunk is the active development branch, where releases live on their own bugfix branches. It looks that you use trunk as release1 bugfix branch, while /branches/1 is the real development trunk, and are stuck since you can't create a second trunk for release2. If I'm right I would recommend to move your current trunk into a /branches/v2 branch, and your /branches/1 branch to /trunk. With this scenario you can have as many release branches as you need (but try to keep them as low as possible), while the main development line is in /trunk. See http://nvie.com/posts/a-successful-git-branching-model/ for more details. While it is for git, there is a lot of VCS-independent information. A: I agree to you other fellow posters. c0rnh0li0 You need to rethink your checkin & merge policies. Look at your repository layout and try to define rules that can easily be repeated by anyone in the team and that help to populate changes consequently from stable to unstable. For me this allows merges mostly in one direction. Example layout for a maintainance-branch scenario branches/v1 -approved and shipped/deploy -Only bugfixes allowed branches/v2 -is not approved by the client but nearly ready -Fixes and feature-commits allowed that focus on getting v2 stable & ready -receive bugfixes commited in v1 (merge down) branches/v3 -is not approved by the client and far from ready -Fixes and feature-commits allowed that focus on getting v3 stable & ready -receive bugfixes commited in v2 (merge down) trunk -All syntax-error free commits allowed (mainline) -receive merges from LATEST stable branch (merge down from v3 in this case) The top branch is the oldest with the fewest features but the highes stability (well tested, not many featurs been added in the recent past). The trunk on the other hand is pretty unstable and receives bleeding-edge features. v2 and v3 are Somewhet in between. You could also add featrue branches "below" the trunk which would be even more unstable than the trunk. Merge directions remain the same. I'd like to quote the mantra "merge down, copy up". The more concurrent releases you prepare/maintain the more merges you will have to do though. But thanks to mergetracking it is not so much of a task IMHO and it ensures no bugfix is left behind and has to be re-discovered and fixed again manually. I didnt mention tags here. If you can create them and do not release from a branch directly. Now while this should fix your change-flow management to a great deal and help isolate high-risk development from low-risk, there is the issue left of visualizing to the client what he is testing/previewing. Visualising application VCS origin to the client Possibilities: * *If it is a web-projekt host, the versions on URLs that contain the branch-name *For any project: Just check in a logo or text property that contains something like "version 3.x" and display it in your application *Coolest solution is to use svn keywords and parse the value of $HeadURL$ in your app to dynamically display the branch name this build originates from
{ "language": "en", "url": "https://stackoverflow.com/questions/3996176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cross join two dataframes by key column using condition in R I have two dataframes. mydata1=structure(list(ID_WORKES = c(58005854L, 58005854L, 58002666L, 58002666L), ID_SP_NAR = c(463L, 1951L, 21L, 465L), KOD_DEPO = c(3786L, 3786L, 1439L, 1439L), KOD_DOR = c(58L, 58L, 92L, 92L), COLUMN_MASH = c(6L, 6L, 5L, 5L), prop_violations = structure(c(1L, 2L, 2L, 2L), .Label = c("0.2", "1"), class = "factor"), mash_score = c(0L, 2L, 2L, 2L)), .Names = c("ID_WORKES", "ID_SP_NAR", "KOD_DEPO", "KOD_DOR", "COLUMN_MASH", "prop_violations", "mash_score"), class = "data.frame", row.names = c(NA, -4L)) mydata2=structure(list(ID_SP_NAR = c(463L, 1951L, 21L, 465L, 500L, 600L )), .Names = "ID_SP_NAR", class = "data.frame", row.names = c(NA, -6L)) i need crossjoin merge these dataframes by ID_SP_NAR. Mydata2 contatins only key variable ID_SP_NAR. I need join this in such a way that if the id_workers does not have any codes from the ID_SP_NAR from mydata2, then these code are inserted into the dataset, but for them in variables prop_violations and mash_score must be inserted zero values. I.E. SP_ID_NAR in mydata2 has such values ID_SP_NAR 463 1951 21 465 500 600 ID_workes =58005854 has 463, 1951 but another not have. and ID_workes =58002666 has 21 and 465 and not anonter! So desired output after cross join ID_WORKES ID_SP_NAR KOD_DEPO KOD_DOR COLUMN_MASH prop_violations mash_score 1 58005854 463 3786 58 6 0.2 0 2 58005854 1951 3786 58 6 1 2 3 58005854 21 3786 58 6 0 0 4 58005854 465 3786 58 6 0 0 5 58005854 500 3786 58 6 0 0 6 58005854 600 3786 58 6 0 0 7 58002666 21 1439 92 5 1 2 8 58002666 465 1439 92 5 1 2 9 58002666 500 1439 92 5 0 0 10 58002666 600 1439 92 5 0 0 11 58002666 463 1439 92 5 0 0 12 58002666 1951 1439 92 5 0 0 KOD_DEPO,KOD_DOR,COLUMN_MASH have fixed value , it must be saved too. How to do that? merge(mydata1,mydata2, by = ID_SP_NAR) is not working( i try use via left join doesn't work), it doesn't insert zeros as i want . A: We could use complete from tidyr to expand the dataset based on the 'ID_WORKES' and the valuse of 'ID_SP_NAR' in the second dataset library(tidyverse) mydata1 %>% mutate_if(is.factor, as.character) %>% complete(ID_WORKES, ID_SP_NAR = mydata2$ID_SP_NAR, fill = list(prop_violations = '0', mash_score = 0)) %>% fill(3:5) # A tibble: 12 x 7 # ID_WORKES ID_SP_NAR KOD_DEPO KOD_DOR COLUMN_MASH prop_violations mash_score # <int> <int> <int> <int> <int> <chr> <dbl> # 1 58002666 21 1439 92 5 1 2 # 2 58002666 463 1439 92 5 0 0 # 3 58002666 465 1439 92 5 1 2 # 4 58002666 500 1439 92 5 0 0 # 5 58002666 600 1439 92 5 0 0 # 6 58002666 1951 1439 92 5 0 0 # 7 58005854 21 1439 92 5 0 0 # 8 58005854 463 3786 58 6 0.2 0 # 9 58005854 465 3786 58 6 0 0 #10 58005854 500 3786 58 6 0 0 #11 58005854 600 3786 58 6 0 0 #12 58005854 1951 3786 58 6 1 2
{ "language": "en", "url": "https://stackoverflow.com/questions/57695829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MyBatis select query with IN but without forEach how can I use a select query where I have only two values for one column without using for each loop ? A: Without using IN, you can use OR: SELECT * FROM `table` WHERE co1 = `value1` OR col1 = `value2`
{ "language": "en", "url": "https://stackoverflow.com/questions/44209427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android app timeout how to apply? when it minimized I want to make a exam app I want to apply a feature in my app in this feature when student minimize app then exam will automatically cancelled. so they can't cheat so please tell me what will and how will I do this in Android app in adt. A: In your exam activity, override onPause() and paste cancel exam method before super.onPause(). Edit: I think you need onPause() instead of onStop(). Learn more about Activity Life cycle A: When you minimize app, onStop will called. Called when you are no longer visible to the user So inside onStop you can cancel the example @Override protected void onStop() { super.onStop(); // cancel exam here }
{ "language": "en", "url": "https://stackoverflow.com/questions/41626567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Login error connecting to salesforce.com from Flex Has anyone suddenly encountered login errors from their users trying to connect to salesforce.com from a Flex app using as3salesforce.swc? I get the following error... password removed to protect the innocent... App Domain = null Api Server name = na3.salesforce.com _internalServerUrl = https://na3.salesforce.com/services/Soap/u/14.0 loading the policy file: https://na3.salesforce.com/services/Soap/cross-domain.xml Your application must be running on a https server in order to use https to communicate with salesforce.com! login with creds loading the policy file: https://na3.salesforce.com/services/crossdomain.xml Your application must be running on a https server in order to use https to communicate with salesforce.com! invoke login intServerUrl is null intServerUrl = https://na3.salesforce.com/services/Soap/u/14.0 _invoke login '5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer set destination to 'DefaultHTTPS'. Method name is: login 'direct_http_channel' channel endpoint set to http://localhost/pm_server/pm/ '5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer sending message 'E32C7199-72C1-B258-B483-FFBC1641173D' 'direct_http_channel' channel sending message: (mx.messaging.messages::HTTPRequestMessage)#0 body = "<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/"><se:Header xmlns:sfns="urn:partner.soap.sforce.com"/><se:Body><login xmlns="urn:partner.soap.sforce.com" xmlns:ns1="sobject.partner.soap.sforce.com"><username>simon.palmer@dialectyx.com</username><password>******</password></login></se:Body></se:Envelope>" clientId = (null) contentType = "text/xml; charset=UTF-8" destination = "DefaultHTTPS" headers = (Object)#1 httpHeaders = (Object)#2 Accept = "text/xml" SOAPAction = """" X-Salesforce-No-500-SC = "true" messageId = "E32C7199-72C1-B258-B483-FFBC1641173D" method = "POST" recordHeaders = false timestamp = 0 timeToLive = 0 url = "https://na3.salesforce.com/services/Soap/u/14.0" '5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer connected. Method name is: login Error: Ignoring policy file at https://na3.salesforce.com/crossdomain.xml due to meta-policy 'by-content-type'. '5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer acknowledge of 'E32C7199-72C1-B258-B483-FFBC1641173D'. responseType: Fault Saleforce Soap Fault: sf:INVALID_LOGIN INVALID_LOGIN: Invalid username, password, security token; or user locked out. Comunication Error : sf:INVALID_LOGIN : INVALID_LOGIN: Invalid username, password, security token; or user locked out. : [object Object] A: Obviously nobody else out there is building Flex apps on top of salesforce.com.. yippee, I'm first. Anyhow, I just found out that this is a bug at salesforce.com as at 6th December 2008. The issue is that the scripts which handle login do not cope adequately with the redirect necessary because of load balancing on the salesforce.com servers. It should be possible to go through the www front door of salesforce.com's api with a URL such as... "https://www.salesforce.com/services/Soap/u/13.0"; where the 13 represents the version of their API you are targetting. However, all users are actually assigned to a specific server, so the front door should redirect the login request to the approriate place, and it doesn't if you are coming from Flex. A workround is to specify your server in the URL, such as... "https://na5.salesforce.com/services/Soap/u/13.0"; ...which is what I was doing. That's fine if you are a single user accessing the same resources continually and your account remains attached to that server. However if... * *You are distributing your app so anyone who has a salesforce.com enterprise account can log in OR *Your account gets moved because of some internal load balancing (which is what happened to me) then the approach of providing a fixed server won't work. The bug (as far as I understand it) is that the www route doesn't adequately redirect to your host server. Last intelligence was that it will be fixed "soon". I wish I could mark this as the answer...
{ "language": "en", "url": "https://stackoverflow.com/questions/339487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Call Python from Julia I am new to Julia and I have a Python function that I want to use in Julia. Basically what the function does is to accept a dataframe (passed as a numpy ndarray), a filter value and a list of column indices (from the array) and run a logistic regression using the statsmodels package in Python. So far I have tried this: using PyCall py""" import pandas as pd import numpy as np import random import statsmodels.api as sm import itertools def reg_frac(state, ind_vars): rows = 2000 total_rows = rows*13 data = pd.DataFrame({ 'state': ['a', 'b', 'c','d','e','f','g','h','i','j','k','l','m']*rows, \ 'y_var': [random.uniform(0,1) for i in range(total_rows)], \ 'school': [random.uniform(0,10) for i in range(total_rows)], \ 'church': [random.uniform(11,20) for i in range(total_rows)]}).to_numpy() try: X, y = sm.add_constant(np.array(data[(data[:,0] == state)][:,ind_vars], dtype=float)), np.array(data[(data[:,0] == state), 1], dtype=float) model = sm.Logit(y, X).fit(cov_type='HC0', disp=False) rmse = np.sqrt(np.square(np.subtract(y, model.predict(X))).mean()) except: rmse = np.nan return [state, ind_vars, rmse] """ reg_frac(state, ind_vars) = (py"reg_frac"(state::Char, ind_vars::Array{Any})) However, when I run this, I don't expect the results to be NaN. I think it is working but I am missing something. reg_frac('b', Any[i for i in 2:3]) 0.000244 seconds (249 allocations: 7.953 KiB) 3-element Array{Any,1}: 'b' [2, 3] NaN Any help is appreciated. A: In Python code you have strs while in Julia code you have Chars - it is not the same. Python: >>> type('a') <class 'str'> Julia: julia> typeof('a') Char Hence your comparisons do not work. Your function could look like this: reg_frac(state, ind_vars) = (py"reg_frac"(state::String, ind_vars::Array{Any})) And now: julia> reg_frac("b", Any[i for i in 2:3]) 3-element Array{Any,1}: "b" [2, 3] 0.2853707270515166 However, I recommed using Vector{Float64} that in PyCall gets converted in-flight into a numpy vector rather than using Vector{Any} so looks like your code still could be improved (depending on what you are actually planning to do).
{ "language": "en", "url": "https://stackoverflow.com/questions/63686791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loading Large Datasets in Parallel With Python Multiprocessing TLDR; * *I want to read many files from disk in parallel *My code loads these files very quickly, but merging them into the main process' memory is slow *Am I doing this correctly? Is there a better way to share memory across processes? Background: I'm currently working on a project with a private hospital dataset (only 3 GB!) and would like to be able to load it faster (their disks are slow). I work on a 36 CPU server, so I should be able to speed it up using multiple processes. However, I am having trouble seeing an improvement. The setup: I have split my dataset over 12 binary PyTorch files ('.pt') which I load with torch.load(filename). These files each contain a list of images inside a dict E.G. the 0th list: {0:ListOfImages}. I would like to load these files simultaneously with different processes, then merge them into a list in their original order. I am currently able to do that, but cannot seem to merge the data into the main process faster than it would take to load sequentially. Sequential baseline load: 74 seconds What I tried: * *multiprocessing.Pool().map() (150 Seconds) *multiple iterations of process.start() + process.join() (300 Seconds +) *multithreading: I load the dataset in exactly the same amount of time as sequentially (74 Seconds) Multiprocessing code thus far: import multiprocessing as mp import time CORES = 12 def loadWorker(sharedDict,filename): t1 = time.time() temp = torch.load(filename) print("Dict Loaded in :{} seconds".format(time.time()-t1)) t1=time.time() sharedDict.update(temp) print("Dict updated in :{} seconds".format(time.time()-t1)) filenames = ["namingconvention{}.pt".format(i) for i in range(CORES)] jobs=[] manager = mp.Manager() sharedDict = manager.dict() t1 = time.time() for i,filename in enumerate(filenames): print("starting Process: {}".format(i)) p = mp.Process(target=loadWorker, args=(sharedDict,filename)) jobs.append(p) p.start() for i,proc in enumerate(jobs): print("join Process {}".format(i)) process.join() print("dict created of length: {} in {} seconds".format( len(sharedDict),time.time()-t1) ) images = [] for i in range(CORES): print("Appending Images: {}".format(i)) images = images + list(images) print("Images appended in {} seconds".format(time.time()-t1)) Am I doing something wrong? Is there a better way to share memory between these processes? OUTPUT: The output of the above: Image of the stdout The output of the above code with CORES=1 and logger.setLevel(mp.SUBDEBUG) Image of debug stdout
{ "language": "en", "url": "https://stackoverflow.com/questions/68422076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why delegate protocol method is not recognized in UINavigationController I looked at lots of threads about delegation but couldn't find why this isn't working I have UINavigationController in storyboard in Xcode 5 and here is how the delegate is assigned: in MasterViewController I have: // // MasterViewController.h // @protocol MyViewDelegate @required - (void) getBackContacts:(NSArray *)c andEmails:(NSArray *)e; @end @interface ListContactsViewController : UITableViewController <MyViewDelegate> { } @property (strong, nonatomic) NSString* myString; @property (strong, nonatomic) ABContact* currentML; @end // // MasterViewController.m // - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. DetailtViewController *vc = [segue destinationViewController]; vc.delegate = self; vc.currentML = _currentML; vc.contacts = _contacts; vc.emails = _emails; } - (void) getBackContacts:(NSArray *)c andEmails:(NSArray *)e { _contacts = [NSMutableArray arrayWithArray:c]; _emails = [NSMutableArray arrayWithArray:e]; } for DetailViewController I have: // // DetailViewController.h // @protocol MyViewDelegate; @interface SelectContactViewController : UITableViewController { id< MyViewDelegate > delegate; } -(IBAction) save; @property (nonatomic, strong) id< MyViewDelegate > delegate; @property (strong, nonatomic) ABContact* currentML; @property (strong, nonatomic) NSMutableArray* contacts; @property (strong, nonatomic) NSMutableArray* emails; // // DetailViewController.m // - (IBAction) save { // *** this line compiles with error [delegate getBackContacts:_contacts andEmails:_emails]; } When I compile compiler says: No known instance method for selector 'getBackContacts:andEmails:'
{ "language": "en", "url": "https://stackoverflow.com/questions/20728495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting size to be the same as window? I'm trying to use jQuery to set the height of a div so that it takes up the entire window + the height of a header (so that you can scroll the header off the page) but no more than that. I would think the height of the div would be the height of the window + the height of the header I'm trying to hide. When I set the div to window height, however, it creates overflow. Here's the rough code: var $body = $("#body"), $container = $("#container"), $window = $(window), $content = $("#mainContent"), $header = $("#header"), bodyHeight = window.innerHeight + $header.height(); $body.css("height", window.innerHeight); $container.css("height", bodyHeight); div { display: block; width: 100%; margin: 0; } #body { overflow-y: scroll; } #container { overflow-y: hidden; } #header { overflow: hidden; } #navbar { height: 10px; background-color: brown; } #mainContent { height: 200px; overflow-y: scroll; } #contentP { height: 400px } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="body"> <div id="container"> <div id="header"> <h1>Header</h1> </div> <div id="navbar"> </div> <div id="mainContent"> <p id="contentP">This is content</p> </div> </div> </div> Why is there overflow if the div is sized to fit in the window? EDIT: So far, answers haven't helped. This is the site I'm working on. It's joomla. I want the nav bar to lock at the top of the screen. $(document).ready(function() { //Declare some variables var $window = $(window), $body = $(".body"), $mainContent = $("#maincontent"), headerGap = parseFloat($("#headerimg").css("margin-top")), headerHeight = headerGap + $("#header").height() + parseFloat($("#navbar").css("margin-top")), navbarHeight = $("#navbar").height(), footerHeight = $("#footer").height(); //set the height of the body and the maincontent resizePage(); //Set the listeners for resizing and scrolling $window.resize(resizePage); $window.scroll(scrollHandler); //When you scroll, see if the navbar is at the top. Set maincontent overflow //to scroll when the navbar is at the top of the window. Set it to hidden otherwise function scrollHandler() { if ($window.scrollTop() < headerHeight - 1) { $mainContent.css("overflow", "hidden"); } else { $mainContent.css("overflow", "auto"); } } //Set the body and the mainContent to be the correct sizes when the window size is changed. In theory, the body should be: // windowHeight + headerHeight // maincontent should be: // windowHeight - (headerHeight + navbarHeight + footerHeight) // But that doesn't quite work out. function resizePage() { //Deal with the changing CSS due to media queries if ($(window).width() > 768) { headerGap = parseFloat($("#headerimg").css("margin-top")); headerHeight = headerGap + $("#header").height() + parseFloat($("#navbar").css("margin-top")) - 1; $(".nav.menu.nav-pills").css("width", "92.5%"); } else { headerHeight = $("#header").height(); $(".nav.menu.nav-pills").css("width", $window.width()); } //The header and navbar height change at certain sizes, so grab them again to be safe. navbarHeight = $("#navbar").height(); footerHeight = $("#footer").height(); var windowHeight = $window.height(), contentHeight = windowHeight - (footerHeight + navbarHeight); //if we account for headerHeight too, maincontent is too big resizeContent(contentHeight); resizeBody(windowHeight); } //The body should take up the whole height of the window, plus the header //and margin heights at the top. This way, you scroll to the navbar. // But it doesn't work this way. // -7 and -27 are from eyeballing it. function resizeBody(windowHeight) { if($window.width() > 728) { $body.css("height", windowHeight - 7); } else { $body.css("height", windowHeight - 27); } } // The content should go from the bottom of the navbar to the bottom of the footer. // function resizeContent(contentHeight) { $mainContent.css("top", (headerHeight + navbarHeight)); $mainContent.css("bottom", (0 - headerHeight)); //For the background slideshow on the Furniture page // Again, + 5 was eyeballed $("div.moduletable").css("height", contentHeight + 5); if ( (contentHeight + 5) < ($(window).width()) /2 ) { $(".wk-slideshow img").css("width", "100%"); $(".wk-slideshow img").css("height", "auto"); } else { $(".wk-slideshow img").css("height", contentHeight + 5); $(".wk-slideshow img").css("width", "auto"); } } }); It works for a lot of sizes, but one you get to small resolutions it falls apart. EDIT 2: I was able to get the effect I was going for by adding another div. I set the body to be the height of the window and the new div to be the size of the body + the height of the header. The body has "overflow-y: scroll". The container would have "overflow-y: hidden" (See updated snippet). This doesn't totally answer my question, but at least it helps? A: I've taken a look at your code and altered it. Try this and see if this is what you're looking for. In my example i'm looking for the element by getElementById and then I set it's style.height to window.innerHeight - 10px without taking the 10px it wouldn't show the border fully on the page. So you just remove 10px's. The example has been tested on different screen sizes. Javascript example: function autoResizeDiv() { document.getElementById('body').style.height = window.innerHeight - 10 + 'px'; console.log(window.innerHeight - 10 + 'px'); } window.onresize = autoResizeDiv; autoResizeDiv(); #body { display: block; border: 5px solid black; } body { overflow: hidden; margin: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="body"> </div> A: The following worked for me: $(".body").height($(window).height()); A: I figured out the biggest problem. I was using some absolutely positioned elements without giving a parent any other position. This made things show up wonky when I was trying to size other things. I also needed to have an extra div as a container for all the content on the page that would be the height of the window + the height of the header. Thanks to everyone who answered, it helped!
{ "language": "en", "url": "https://stackoverflow.com/questions/30877507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Redirection to base url with GET array in codeigniter I'm trying to make the pagination work with the get parameter. Only that, the rest of the site will use uri. The problem is this, as soon as I append ?something=zyx it redirects to the base url. Config: $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-&='; $config['allow_get_array'] = TRUE; htaccess: RewriteEngine on RewriteCond $1 !^(index\.php|lib|robots\.txt|upload) RewriteRule ^(.*)$ /mysite/index.php/$1 [L] Why does this happen? Thanks EDIT: AFTER A LONG RESEARCH I FOUND THE PROBLEM. I post it here in case somebody else has the same problem. If you are planning to use GET vars in whatever form, even a hybrid solution like mine you must set: $config['uri_protocol'] = "PATH_INFO"; in the config file. A: Since you only want to use query strings while using pagination, the following code should be enough: $this->load->library('pagination'); ... $config['page_query_string'] = TRUE; ... $this->pagination->initialize($config); echo $this->pagination->create_links(); You should check the rest of the Pagination Class documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/8310382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add an Internet Gateway to a VPC using AWS CDK? I am trying to produce the correct CDK scripts (TypeScript) to create an environment with a Lambda (accessed via API Gateway) that can call an RDS (Sql Server instance). I believe I have it mostly working, but I wanted to connect to the RDS instance from my development machine to run some queries and check on a few things. My RDS instance is in a private subnet, and so I believe in order to connect to it I need to add an Internet Gateway and security group to allow access on the appropriate ports. For the life of me I can figure out the last piece, how to add the internet gateway using CDK. The latest script I have tried is as follows: const privateSubnectConfiguration = { cidrMask: 26, name: 'private-subnet', subnetType: SubnetType.PRIVATE, }; const publicSubnectConfiguration = { cidrMask: 26, name: 'public-subnet', subnetType: SubnetType.PUBLIC, }; const vpc = new Vpc(this, props.generateId('vpc'), { maxAzs: 2, subnetConfiguration: [privateSubnectConfiguration, publicSubnectConfiguration], natGateways: 1, }); vpc.addGatewayEndpoint(props.generateId('internet-gateway'), { service: { name: "ig-service" } }) Which then errors with The Vpc Endpoint Service 'ig-service' does not exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidServiceName; I see references to the CfnInternetGateway in the docs, but just can't figure out how to attach a new one to my VPC? Can you please help with the syntax? A: First of all, you cannot directly access a database in a private subnet. You have to deploy a proxy instance in your public subnet and forward the required ports to access your database. When using CDK VPC construct, an Internet Gateway is created by default whenever you create a public subnet. The default route is also setup for the public subnet. So you should remove addGatewayEndpoint() from your code, which adds a Gateway VPC Endpoint that you don't need. You may also consider using SubnetType.ISOLATED to create a private subnet without a NAT GW, which may be redundant in your case. SubnetType.PRIVATE creates a NAT Gateway by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/58812479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how do i select value from dropdownlist to mode or to controller mvc Model public class Company { public int ID { get; set; } .... public int WorkZoneID { get; set; } public IEnumerable<SelectListItem> WorkZones { get; set; } Controller: ViewBag.Workzones = cmpRep.GetWorkzoneDrop(); Repository: public List<SelectListItem> GetWorkzoneDrop() { SqlDataReader DR; DR = Ado.ExecDataReaderProc("WorkZoneSelectActive"); List<SelectListItem> selectWorkZoneListItems = new List<SelectListItem>(); CompanyVMList C = new CompanyVMList(); C.Companies = new List<Company>(); while (DR.Read()) { SelectListItem selectListItem = new SelectListItem { Text = Convert.ToString(DR["Name"]), Value = Convert.ToString(DR["ID"]), }; selectWorkZoneListItems.Add(selectListItem); } return selectWorkZoneListItems; } View @Html.DropDownList("Workzones") I want to assign selected dropdownlist value to int work zone int the mode how do i select value from dropdownlist to model or to controller A: You need to bind your dropdownlist to property WorkZoneID @Html.DropDownListFor(m => m.WorkZoneID, Model.Workzones) and if your wanting to preselect an option, you need to set the value in the controller before you pass the model to the view. And since your model contains a property for the SelectList, then use it (don't use ViewBag) Company model = new Company { WorkZoneID = 1 // set to a value that matches one of your options Workzones = cmpRep.GetWorkzoneDrop(); }; return View(model); and when you submit to [HttpPost] public ActionResult Edit(Company model) the value of model.WorkZoneID will contain the value of the selected option.
{ "language": "en", "url": "https://stackoverflow.com/questions/35279612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to decouple user Identity from the application data I am part of a new startup with some friends from school, and I am developing a REST API as back-end for a web application/website. I have recently gratuated and does not have much experience with large projects. Without going in detail about the specific business idea, it will be sort of a "share economy" service, like for example uber or airbnb, where users register as either a customer or provider of a specific service. So users need to register an account and have data related to that account. The API is developed with ASP.NET Web API. For authentication/authorization I am using ASP.NET Identity and JWT as Oauth bearer tokens with OWIN OAuth middleware. I have used a guide for part of the setup, with some changes to fit our project. (Just search "bitoftech Implement OAuth JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1" to find it if you are interested). For those that don't know, the ASP.NET Identity database looks like this: ASP.NET Identity database diagram. So we have an AppUser table that represents the user, with roles, claims and logins attached in different tables in the Identity database. Now, the user has much other data related to his account in our application, like messages (users can message each other), events (like a ride if this was uber), categories, reviews, files, and other data. All in separate tables. So, since all these other tables are related to the user identity, what I did was put all these other tables in the same database with a Foreign Key to the Id in the AppUser table. Each user has a role of either Customer or Provider (as in customer or driver in the Uber example) in the IdentityRole table. This way I can authorize users based on role, and also query data based on role. Now for the catch: Unexpected requirement changes. The company has decided that they (we) want to create a similar service (with customers and providers), but in a different business domain, and with the same user identity. So users that have already registered with one site should not be required to register again with a new account for the other site, but just use their existing account (and maybe sign up for the new site by clicking a button in their profile or something). So if the first site was uber, now we want to create airbnb (not really, but as an example). The data in the new site will be very similar to the first site. Users will have messages, events, categories, files, etc. But the events table will maybe be a little different, and maybe some new or different tables for the new site. We will try to keep the data very similar at first, so we can use much of the existing code, but we expect โ€“ if the the site(s) become popular โ€“ that they will drift apart (in terms of code and data) in time. So first I thought: "how can I change the existing database schema so that it will fit both services?". But as I thought more about it, I think this will maybe only create problems in the future. In the Oauth flow diagram, you have a separate resource server and authorization server. Even though I use Oauth now, my API is both a Resource Server and Authorization Server I guess, and that would probably be ok if they had not had been coupled in the way I have described? So my question after all this is this is: 1: Should I use one (separate) database for the User Identity (IdentityDbContext), and another database for all the other data (events, messsages etc..)? That way Identity can run on a totally different server if need be, and not be coupled to any specific domain/site/service. Is that a good idea? 2: If so, how would I create a relationship between databases? The only thing I can think of is to create a separate user table with only the UserId (from the Identity database) in the "Uber" database, and this will be created the first time a user registers for a site, and all the other data is related to this key. Then I would need to query data from two databases and put them together for some operations, for example, when a user queries his incoming messages, the message itself would be in one database and the name of the sender in another. Is there a better way? 3: Should I use separate databases for the first and second website/service (One for Uber and one for Airbnb, as in the example)? Or is there a better way? 4: Is there a different solution that I have not thought about that would be better? Many people have probably faced these problems before, so I would appreciate if any experienced developers could tell me what is the best practice. Last, it is not unprobable that even more services will be "attached" to the user Identity in the future if our current endevours are successful, so I really need a future-proof solution to this problem. Thank you for any responses. A: This approach seems somewhat common: * *Maintain a completely separate identity database. There should be no connection at all with any of the Line-Of-Business (LOB) databases. *Each LOB database should have its own user table, with appropriate referential integrity constraints with other LOB tables, e.g. events or messages in your case. *When a user hits one of your LOB web sites for the first time, he should be "enrolled" in the LOB database. A LOB user record is inserted. Use the access token to call the identity server to get any demographic information your LOB site will need. *When a user hits one of your LOB web sites for the Nth time, you can use the access token to call the identity server and get the most recent, up-to-date demographic information, just in case any of it has changed since his last visit. You can then store this information in the LOB user table so that it is available to you offline, e.g. if you need to push marketing emails you'll have a copy of the email address. The advantage of this approach is separation of concerns and the ability to support more than one authentication provider (e.g. in the future you could support Facebook or Google+ logins as well). Also you avoid any dependencies between the identity server and the LOB servers, so you can add or remove lines of business as needed, and you keep the identity server nice and lightweight.
{ "language": "en", "url": "https://stackoverflow.com/questions/42189415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking if a directory exists in Linux using perl I am programming in linux using perl. I am creating a program where a user can input a directory and a filename. The program will then check if the given directory exists or not and also searches the given filename in that directory. But my problem is verifying if the inputted directory is valid. A: You must have specified if the path to the directory is absolute or relative. If it is absolute, you can check with -e to see if it exists and with -d if the input given it is a directory or not. if ( -e $dir and -d $dir) { print "\nyour folder exists"; } If the path is relative, then you must create the absolute path. For that you will have to use as $base your drvives (you need to do that for each drive) and after, use rel2abs to find an absolute path for the given relative path. If the folder exists, $abs_path will contain the absolute path, else it's value will be undef. Bellow as an example for searching your folder with a relative path on drive c:\: $base = 'c:\'; $abs_path = File::Spec->rel2abs( $relative_path ) ; $abs_path = File::Spec->rel2abs( $relative_path, $base ) ; if ( defined $abs_path ) { print "\n folder exists "; } For more options, see perldoc -f -X
{ "language": "en", "url": "https://stackoverflow.com/questions/38692927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Python - filtering in Django I'm new in python/django and i have a problem, i'm trying to use checkbox filtering in my html table and i don't really know how to do it. This is what i have now I want to add these models.py class Tags(models.Model): tag_frequency = models.CharField(max_length=250) views.py @login_required(login_url='/login/') def index(request): title = 'Tags' all_tags = Tags.objects.all() return render(request, 'tag/index.html' ,{'all_tags':all_tags, 'title':title}) How do i use filter with these, i tried something like this but doesn't work: LF = 125 - 134.2 KHz HF = 13.56 MHz UHF = 860 - 960 MHz LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2) A: In order to make your query works, you have to change your field to FloatField: class Tags(models.Model): tag_frequency = models.FloatField(default=0.00, null=True, blank=True) Set null, blank and default values based on your needs. Then, put your checkboxes (or radio inputs) in your html form like this: <form action="" method="post"> <!-- other form fields and csrf_token here --> <div><label for="input_lf"><input type="checkbox" name="is_lf" id="input_lf"> LF</label></div> <div><label for="input_hf"><input type="checkbox" name="is_hf" id="input_hf"> HF</label></div> <div><label for="input_uhf"><input type="checkbox" name="is_uhf" id="input_uhf"> UHF</label></div> <input type="submit" value="Submit"/> </form> Then in your view, you can try something like this: def form_view(request): if request.method == 'POST': # these strings come from HTML Elements' name attributes is_lf = request.POST.get('is_lf', None) is_hf = request.POST.get('is_hf', None) is_uhf = request.POST.get('is_uhf', None) # Now make your queries according to the request data if is_lf: LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2) if is_hf: # another query here # and rest of your view
{ "language": "en", "url": "https://stackoverflow.com/questions/43780923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to have MySQL return multiple column of values based on a different benchmark? I have a MySQL database table (sales) consisting of sales data with their dates. | Sales ID | Date | Values | |---------------------------------| | 1 | 01/01/2020 | 1,500 | | 2 | 02/01/2020 | 2,000 | | 3 | 07/02/2020 | 1,000 | | 4 | 12/03/2020 | 2,000 | | 5 | 21/06/2020 | 1,000 | | 6 | 11/08/2020 | 4,200 | I have a SQL query that relies on a specific date benchmark. ``` SET @benchmark = "31/01/2020"; SELECT SUM(Values) FROM sales WHERE (date < @benchmark); ``` This query supposedly returns only one numeric value. Now I set the condition to be dependant on the benchmark. The problem is, I don't want this benchmark to stay constant. I need the query to return 14 values for each end of month benchmark from January 2020 to February 2021. So the result would probably be something like this, | SUM(Values) | |-------------------------------------| |(result for benchmark = "31/01/2020")| |(result for benchmark = "29/02/2020")| |(result for benchmark = "31/03/2020")| โ‹ฎ |(result for benchmark = "31/01/2021")| |(result for benchmark = "28/02/2021")| Which sets the benchmark for every end of the month. Note that I do not have access to CREATE anything. I was thinking of a while loop or a temporary table, but those require me to CREATE something which always returns "Error Code: 1142. CREATE command denied to the user ...." or "Error Code: 1044. Access denied for the user ....". Thanks for any help or feedback. A: You can list the dates you want and aggregate: select m.eom, sum(s.sales) from (select '2020-01-31' as eom union all select '2020-02-29' union all . . . ) m left join sales s on s.date < m.eom group by m.eom; Note that you can also generate the dates using a recursive CTE or calendar table. For this particular query, you could also use a cumulative sum: select last_day(date) as eom, sum(sales), sum(sum(sales)) over (order by last_day(date)) from sales group by eom; That works for your particular example, but might not work for other logic.
{ "language": "en", "url": "https://stackoverflow.com/questions/66444063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: do a task for each server from a specific group I have a host file with: [synology] 192.168.1.111 ansible_sudo_pass='dfg78G67' [web] 139.59.xx:8682 server_name=do1 sql_server_id=1 sql_auto_increment_increment=1 139.59.xx:8682 server_name=do2 sql_server_id=2 sql_auto_increment_increment=2 For each server I have his ssh public key I would like to add it to my synology - name: "Add ssh key" authorized_key: user=admin key="{{ lookup('file', 'ssh_keys/id_rsa_{{ item.server_name }}.pub') }}" with_items: "{{ groups['web'] }}" but Ansible responds TASK [synology_init : Add ssh key] ********************** fatal: [192.168.1.111]: FAILED! => {"failed": true, "msg": "'unicode object' has no attribute 'server_name'"} Thx A: - name: "Add ssh keys" authorized_key: user=admin key="{{ lookup('file', 'ssh_keys/id_rsa_{{ hostvars[item].server_name }}.pub') }}" with_items: "{{ groups['web'] }}"
{ "language": "en", "url": "https://stackoverflow.com/questions/36885855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to support large dropdowns Say I have a report that can be restricted by specifying some value in a dropdown. This dropdown list references a table with > 30,000 records. I don't think this would be feasible to populate a dropdown with! So, what is the best way to provide the user the ability to select a value given this situation? These values do not really have categories and even if I subdivided (by having some nesting dropdown situation) by the first letter of the value, that may still leave a few thousand entries. What's the best way to deal with this? A: Search, don't categorise. You can display the control as a simple text box, and when the user types in a few characters, you could pop up an autocomplete-like dropdown to select the final value. Here's a link to the jQuery plugin for autocomplete. A: I really wouldn't have a 30,000 element drop-down. The GUI is supposed to make it easier on the user rather than harder. If you have no other way to categorise the data other than alphabetically, you're not restricted to using a two-stage approach with just the first character. Make it reliant on the first two characters. This would give you at most 676 (assuming alphas only) in the first drop-down and (on average) 44 in the second. We've actually taken two approaches to this problem. BIRT (which we use) allows for cascading parameters which can easily run that second-level query whenever you change the first drop-down box. However, some of our customers care absolutely zero for nice GUI stuff (other than the output of nice 9-point Verdana and beautiful charts to placate management, of course). They prefer a free-form text entry field where they can just type in "SYS_PAX_%" to change their queries. Of course, these are the customers that know exactly what data is in their database and use values which lend themselves to categorisation with SQL LIKE clauses. Others prefer the ability to search. A: I had this same question about 2 years ago concerning a asp.net dropdown box. Trust me, don't even try it. Use the auto complete suggestions above. I've found that displaying anything above 5000 records tends to crash the browser. Just my 2 cents. A: +1 @pax. Still i'd like to see a 30K dropdown! :) @JustAProgrammer, perhaps you could do a text box where people can type in the beginning of what they are looking for and you can filter as they type in. A: If you're asking from a performance perspective rather than a usability perspective I would consider using a live-list approach that loads only a subset of the list items on demand as you scroll up or down. If the user clicks down the list quickly, to say the middle, it will load another 10 elements corresponding to that position. Both render time and load time will be much faster. Like paging, but 'fluid'. A: Auto complete drop down as suggested above is best to have. But it will require the users to have some idea about the type of entries to start with. If the users are familiar with data, go for it. Alternatively, if you can categorize your data, then you can start with the categories first and then based on the selection you can populate the dependent drop down with actual values which will be a subset of original values.
{ "language": "en", "url": "https://stackoverflow.com/questions/2444951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: adding/embedding youtube videos in asp.net page I want to add youtube videos thumbnails to my asp.net website like the videos section in http://jtsplatmaster.com/. On this website, If you click the right thumbnails, video will start playing in the main section without page refresh. Which control so I need to use. I know that object tag can be used to embed youtube videos in asp.net page. Please suggest. A: I found this API http://youtube.codeplex.com/. May be helpful for someone in future. Regards, Asif Hameed
{ "language": "en", "url": "https://stackoverflow.com/questions/12389662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Matrix Cyberpunk Solver I have input data like this: 4 #length of way BD 1C BD 55 #way 5 #matrix size (5x5 now) 1C BD 1C 55 55 #matrix 55 55 55 1C 1C E9 1C 55 55 E9 BD 1C 1C 1C BD 55 BD E9 55 1C I need to print the right way to solving matrix. The rules of solving are this: * *At this input i have a BD 1C BD 55 code to find. I take the first line (1C BD 1C 55 55) and find BDin it. It is the 2nd element *Now I take the 2nd vertical (BD 55 1C 1C BD) and find 1C in it. It can be 3rd and 4th. And that's my problem for now. The program should check the 3rd way and the 4th. As you can see, there is no BD element in the third line (E9 1C 55 55 E9), but there is a BD element at the fourth line (BD 1C 1C 1C BD). So it is the first element. *Now i continue doing finding this untill i get all way. So i print the way and the answer for this input is 2 4 1 2. If there is more than one answer, I can choose any one. Here is the visualisating Here is my code. arrway = [] waylen = int(input()) wayin = list(map(str, input().split())) for i in range(waylen): arrway.append(wayin[i]) k = int(input()) array = [[0 for j in range(k)] for i in range(k)] for i in range(k): a = list(map(str, input().split())) for j in range(k): array[i][j] = a[j] ANS = [] ############## print(array) # The array for the example is [['1C', 'BD', '1C', '55', '55'], ['55', '55', '55', '1C', '1C'], ['E9', '1C', '55', '55', 'E9'], ['BD', '1C', '1C', '1C', 'BD'], ['55', 'BD', 'E9', '55', '1C']] ############# currentNum = 0 currentPos = 0 for i in range(waylen): currentElement = arrway[currentNum] if i % 2 == 0: for jk in range(k): # horizontal if array[currentPos][jk] == currentElement: ANS.append(jk + 1) currentPos = jk currentNum += 1 else: for jkl in range(k): # vertical if array[jkl][currentPos] == currentElement: ANS.append(jkl + 1) currentPos = jkl currentNum += 1 ########## print(ANS) # the ANS for example is [2, 3, 4, 1, 2] but no [2, 4, 1, 2]. ########## So, as you can see, the problem is about checking the right way of the several elements. Now my code have the two-dimensional array of matrix. Hope you can help me. Thank you. A: If your input is reasonably small, then you can try using recursion (however if the input is big, you might fail with a stack overflow). You first call find_on_row giving it the whole list of way elements, the whole array, and also indices of the current way element we find (in the beginning it's 0) and the index of a row you want to search over (in the beginning it's 0, as you said). find_on_row goes over all elements in the specified row, and for each elements that is equal to the needed way element it calls find_on_col function (since you have BD only once on the first row, the function find_on_col is called once with this column. find_on_col does the similar thing - it goes over all elements in the specified column, looks for the next way elements and calls find_on_row for each match (2 times in this case, since 1C can be found twice on the first column. These two calls now search the answer separately, one from the 3rd row, the other from the 4th row. They go until either the whole way is found (i.e. way_index is the maximum possible), or if there's no match for the current way elements (so no answer from this search path). def find_on_row(way, array, way_index, row_index): if way_index == len(way): # found answer return [] for col_index in range(len(array[0])): if array[row_index][col_index]== way[way_index]: candidate_answer = find_on_col(way, array, way_index + 1, col_index) if not candidate_answer is None: # unwind answer return [col_index] + candidate_answer return None def find_on_col(way, array, way_index, col_index): if way_index == len(way): # found answer return [] for row_index in range(len(array)): if array[row_index][col_index] == way[way_index]: candidate_answer = find_on_row(way, array, way_index + 1, row_index) if not candidate_answer is None: # unwind answer return [row_index] + candidate_answer return None way = ['BD', '1C', 'BD', '55'] array = [['1C', 'BD', '1C', '55', '55'], ['55', '55', '55', '1C', '1C'], ['E9', '1C', '55', '55', 'E9'], ['BD', '1C', '1C', '1C', 'BD'], ['55', 'BD', 'E9', '55', '1C']] print(f'Starting from first row the answer is {find_on_row(way, array, 0, 0)}') # Starting from first row the answer is [1, 3, 0, 1] It prints indices starting from 0, so to get your desired output you can increment each value by 1 (I don't do that, because it's more convenient to work with indices starting from 0)
{ "language": "en", "url": "https://stackoverflow.com/questions/65979095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replace/fill columns base on agg of multiple columns I have a DF as follows: | feat1 | feat2 | feat3 | feat4 | label | |--------:|---------|----------|---------|-------| | 0.1856 | -0.186 | 1.681 | 0.56781 | 0 | | 0.78671 | 0.1761 | -0.671 | 0.176 | 0 | | -1.681 | 0.15689 | -0.18689 | 0.681 | 0 | I want to replace the label column where the mean of all feat features is > 0. I tried this: feat = [f for f in df.columns if "feat" in f] df.loc[df[feat].mean() > 0, "label"] = 1 But it does not seem to work right. A: You can use df.filter to filter all columns containing feat and calculate mean across axis=1 , and convert to int after comparison. df['label'] = df.filter(like='feat').mean(1).gt(0).astype(int) print(df) feat1 feat2 feat3 feat4 label 0 0.18560 -0.18600 1.68100 0.56781 1 1 0.78671 0.17610 -0.67100 0.17600 1 2 -1.68100 0.15689 -0.18689 0.68100 0
{ "language": "en", "url": "https://stackoverflow.com/questions/65489859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: U-Boot SPL Debug Messages I've been trying to get U-Boot SPL to print debug messages. I've noticed plenty of debug() functions that aren't printing to the serial console, however when I define the DEBUG preprocessor macro, I still don't see those messages. Is this something the SPL can even do? Especially since the serial console is initialized in preloader_console_init() can any messages be sent before that function is executed? A: Assuming that your UART is configured correctly, you should see messages once preloader_console_init has been run. Prior to that, you can (depending on your platform) see about getting DEBUG_UART to function in your environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/45721081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scroll to div with some px in less I find here in Stack Overflow a simple script written in jQuery which allows to have a smooth scroll to a specific div id, clicking a button: $("#button").click(function() { $('html, body').animate({ scrollTop: $("#myDiv").offset().top }, 2000); }); Everything works perfectly, but I have a little problem: in the site I have a fixed menu, that clutters this script. When I click the button for scroll to a specific div, the menu takes a part of the div that I want to see (overwrap the div), so the div is not visible to 100%. I want to ask if there is a manner to scroll to a specific div removing some px, equivalent to the height in px of the menu. Example: Page: I click the button, and I get this effect: But I want this effect: A: Just get the height of the menu bar and subtract it from the offset like for example if the menu is 60px $("#button").click(function() { $('html, body').animate({ scrollTop: $("#myDiv").offset().top-60 }, 2000); });
{ "language": "en", "url": "https://stackoverflow.com/questions/36308535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Attempting to access the member of a struct through a property on an enclosing class I get an error when trying to run this code. I can't seem to find the root cause. public class MyClass { public MyClass() { ListView listView; listView = new ListView(); listView.Size.Width = 5; } } A: Try listView.Width = 5; or listView.Size = new Size(5, listView.Height); Size is a struct, so accessing its property will get a copy of it; hence modifying it is not actually modifying the original struct. You're modifying the copy of it. So compiler complains that this is not what you intended. A: Try the following lines instead. ListView lvi = new ListView(); MyStruct ms; ms.Width = 5; lvi.Size = ms;
{ "language": "en", "url": "https://stackoverflow.com/questions/23080398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Log vscode command execution for shortcuts mapped to multiple commands Is there a way to find what vscode command was executed. For example, 'tab' is a keyboard shortcut for a lot of commands (depending on the context). Now I wish to find a way to display which specific command was pressed (insertSnippet or insertNextSuggestion or something else...) in the console or anywhere
{ "language": "en", "url": "https://stackoverflow.com/questions/54777933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Insert "element" among other "elements" of the array (loop) php my code causes the images to appear randomly within the page. But how to insert an "element" (in my case would be a div) between these images? <?php $myImagesList = array ( 'image1.png', 'image2.png', 'image3.png', 'image4.png' ); shuffle ($myImagesList); for ($i=0; $i<4; $i++) { echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />'; } ?> Example: The original code displays the images as follows: image3.png image4.png image2.png image1.png F5 refresh page image2.png image1.png image4.png image3.png F5 refresh page image4.png image2.png image3.png image1.png I needed it this way: image2.png image1.png content image4.png image3.png F5 refresh page image4.png image2.png content image1.png image3.png F5 refresh page image2.png image3.png content image4.png image1.png A: You would want something like this... $myImagesList = array ( 'image1.png', 'image2.png', 'image3.png', 'image4.png' ); shuffle ($myImagesList); $i = 0; foreach ($myImagesList as $img) { $i++; if ($i % 3 === 0) { /* show content */ } echo '<img src="/image/' . $img . '" width="200" height="140" border="0" />'; } This will give you the content section every third iteration, no matter the size of the list. A: If you want to add a div(content) between those two pairs of images - add additional condition into your loop: ... for ($i=0; $i<4; $i++) { if ($i == 1) echo '<div>some content ...</div>'; echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />'; } A: Go with the most readable solution - the one that doesn't make you fall and debug later when changing something. $splitAtNumber = 2; // or dynamically use count($myImagesList) / 2 or .... // output first part of the array for ($i = 0; $i < $splitAtNumber; $i++) { echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />'; } // Output your content echo 'content'; // Output second part of the array for ($i = splitAtNumber; $i < count($myImagesList); $i++) { echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/38285086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: OpenCV Surf and Outliers detection I know there are already several questions with the same subject asked here, but I couldn't find any help. So I want to compare 2 images in order to see how similar they are and I'm using the well known find_obj.cpp demo to extract surf descriptors and then for the matching I use the flannFindPairs. But as you know this method doesn't discard the outliers and I'd like to know the number of true positive matches so I can figure how similar those two images are. I have already seen this question: Detecting outliers in SURF or SIFT algorithm with OpenCV and the guy there suggests to use the findFundamentalMat but once you get the fundamental matrix how can I get the number of outliers/true positive from that matrix? Thank you. A: Here is a snippet from the descriptor_extractor_matcher.cpp sample available from OpenCV: if( !isWarpPerspective && ransacReprojThreshold >= 0 ) { cout << "< Computing homography (RANSAC)..." << endl; vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs); vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs); H12 = findHomography( Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold ); cout << ">" << endl; } Mat drawImg; if( !H12.empty() ) // filter outliers { vector<char> matchesMask( filteredMatches.size(), 0 ); vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs); vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs); Mat points1t; perspectiveTransform(Mat(points1), points1t, H12); double maxInlierDist = ransacReprojThreshold < 0 ? 3 : ransacReprojThreshold; for( size_t i1 = 0; i1 < points1.size(); i1++ ) { if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) <= maxInlierDist ) // inlier matchesMask[i1] = 1; } // draw inliers drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask #if DRAW_RICH_KEYPOINTS_MODE , DrawMatchesFlags::DRAW_RICH_KEYPOINTS #endif ); #if DRAW_OUTLIERS_MODE // draw outliers for( size_t i1 = 0; i1 < matchesMask.size(); i1++ ) matchesMask[i1] = !matchesMask[i1]; drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 0, 255), CV_RGB(255, 0, 0), matchesMask, DrawMatchesFlags::DRAW_OVER_OUTIMG | DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); #endif } else drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg ); The key lines for the filtering are performed here: if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) <= maxInlierDist ) // inlier matchesMask[i1] = 1; Which is measuring the L2-norm distance between the points (either 3 pixels if nothing was specified, or user-defined number of pixels reprojection error). Hope that helps! A: you can use the size of the vector named "ptpairs" in order to decide how similiar the pictures are. this vector contains the matching keypoints, so his size/2 is the number of matches. i think you can use the size of ptpairs divided by the total number of keypoints in order to set an appropriate threshold. this will probably give you an estimation to the similiarty between them.
{ "language": "en", "url": "https://stackoverflow.com/questions/8855020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Terminate a process and close all its opened listening ports On my Qt application, I run an external executable on a separate process like this: QProcess *server = new QProcess(); server->start("./server.exe"); External executable starts a server on 127.0.0.1 listening on port 18383. Then at some point, I terminate the process like this: server->terminate(); The problem is that by terminating the server process, many times its used port i.e. 18383 remains open. Consequently, when I try to start the server again, I receive these errors: "Server -2 Could not setup server. listen tcp :18383: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted. How can I terminate the process and close all its opened listening ports? A: sometimes I receive these errors while terminating the process: QProcess: Destroyed while process (" ... server.exe ...") is still running It seems you are not waiting for the process to gracefully terminate. Here is a generic way to terminate a process you launched : server->terminate(); server->waitForFinished(timeoutMS); if (server->state() == QProcess::Running) { server->kill(); } Terminate will send a polite "can you please stop" signal, kill will abruptly stop the target process. How much time does it take for the server to shut down (it may be several seconds)? so you should have a generous timeout period which take this in account.
{ "language": "en", "url": "https://stackoverflow.com/questions/54017612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Rails: Convert future meeting time in one time zone to another time zone Using flatpickr, I allow the user to specify the time and date of a future meeting that includes their time zone. The result is the following value: Mon May 25 2020 12:00:00 GMT-0600 (Mountain Daylight Time) They can choose a team member to meet with and that time member will have set their current time zone and I'm storing that value using ActiveSupport::TimeZone (https://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html) I am trying to figure out how to take the date result above and display to the user who is scheduling the meeting, "It will be 7pm for X." I send the attendeeZone and meetingTime to a Rails endpoint: def time_for_attendee attendeeZone = params["attendeeZone"] # => "Tokyo" meetingTime = params["meetingTime"] # => "Mon May 25 2020 12:00:00 GMT-0600 (Mountain Daylight Time)" attendeeTime = ??? render json: { attendeeZone: attendeeZone, meetingTime: meetingTime, attendeeTime: attendeeTime } end How would I convert that meetingTime to the attendeeTime based on their time zone? I got close with Time.zone.now.in_time_zone(attendeeZone) but I'm not sure how to convert the format of meetingTime to replace now. A: It's .parse() Time.zone.parse(params["meetingTime"]).in_time_zone(attendeeZone) Alternatively, if you assign it to a model, then it will be parsed automatically already.
{ "language": "en", "url": "https://stackoverflow.com/questions/61823816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java.util.MissingResourceException I am getting below exception while running an application. This application read abc.properties file, Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name abc, locale en_US at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:853) at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:822) at java.util.ResourceBundle.getBundle(ResourceBundle.java:566) at com.ibm.dst.DailyExtract.getResourceBundle(DailyExtract.java:104) at com.ibm.dst.DailyExtract.main(DailyExtract.java:131) abc.properties file reside at the workspace. I am using RSA7 as IDE, is there any setting problem? any suggestions are welcome..... Thanks a lot in advance A: You just need to add the package name while getting the file For example if your properties name is "ABC.properties" in package a.b.c then the below code will work perfectly ResourceBundle labels = ResourceBundle.getBundle("a.b.c.ABC"); A: Just copy the resource file over to where your class files are. In my case my directory was: bin - com - brookf - all my packages here. copy your resource file to the bin folder. A: Follow the hints in this post and see if you made one of those mistakes, which could be (copy pasted from the link): * *These resource properties files are loaded by classloader, similar to java classes. So you need to include them in your runtime classpath. *These resources have fully-qualified-resource-name, similar to a fully-qualified-class-name, excerpt you can't import a resource into your java source file. Why? because its name takes the form of a string. *ResourceBundle.getBundle("config") tells the classloader to load a resource named "config" with default package (that is, no package). It does NOT mean a resource in the current package that has the referencing class. *ResourceBundle.getBundle("com.cheng.scrap.config") tells the classloader to load a resource named "config" with package "com.cheng.scrap." Its fully-qualified-resource-name is "com.cheng.scrap.config" A: Loading the Properties file for localization stuff is also affected by the package naming. If you put your Properties file in a package like org.example.com.foobar and load it just by its name abc you have to add the prefix org.example.com.foobar, too. If you have the properties at a different location (like in the root directory or in another subdir) you have to change either the name to load or the classpath. I run fine in placing the properties file in the same location where the .java file is and using something like private static ResourceBundle RES = ResourceBundle.getBundle(NameOfTheCurrentClass.class.getCanonicalName()); A: I had the same issue today and it took me a while until I figured out a fix (I'm using Eclipse as an IDE). My project folder contains the *.properties-Files in the following path: project/src/strings Since strings is a sub-folder of src and src is already in the build path of the project (see Property Window), all I needed was to add an Inclusion-Pattern for the *.properties-Files: **/*.properties There should be already an Inclusion-Pattern for *.java-Files (**/*.java) Maybe there is something similar for your IDE A: Is the file in your classpath? If it is, try renaming it to abc_en_US.properties
{ "language": "en", "url": "https://stackoverflow.com/questions/2636521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Signal handlers reset every time I'm writing a C program that does the following: Monitors which signals are sent to it. Counts how many times SIGUSR1 and SIGUSR2 have been sent. Terminates when SIGTERM has been sent but first prints out how many times SIGUSR1 and SIGUSR2 have been sent. Please note that this is a problem from class, so it's not supposed to really have any usage, just to test us. Also, no other signals except for the mentioned three will be sent. This is what I got: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> int sigUsr1Count = 0; int sigUsr2Count = 0; static void sighandler(int signum){ switch(signum){ case SIGUSR1: sigUsr1Count++; break; case SIGUSR2: sigUsr2Count++; break; case SIGTERM: printf("%d %d\n", sigUsr1Count, sigUsr2Count); exit(0); } } int main(int argc, char ** argv){ pid_t mypid = getpid(); fprintf(stderr, "My PID is %d\n", mypid); struct sigaction sa; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sa.sa_handler = sighandler; iAssert(-1 != sigaction(SIGUSR1, &sa, NULL), "sigaction1 failed"); iAssert(-1 != sigaction(SIGUSR2, &sa, NULL), "sigaction1 failed"); iAssert(-1 != sigaction(SIGTERM, &sa, NULL), "sigaction1 failed"); while(true){ fprintf(stderr, "Waiting...\n"); sleep(3); } return 0; } I've read on a forum somewhere that, when using sigaction, signal handlers will NOT be reset to default unless the sa_flags field is set to SA_RESETHAND. However, that does not seem to be the case with me. (The man page describes the SA_RESETHAND flag but is not explicit about the action in the situation where it's omitted.) When I run the program, it will only go to my handlers the first time SIGUSR1 or SIGUSR2 are sent, after that the program terminates with the message: User defined signal 1 (or 2) In that sense, the program only outputs the correct values if either: SIGUSR1 and SIGUSR2 haven't been sent at all, or each of them has been sent at most once. The iAssert macro & function: #define iAssert(cond, msg) crash(cond, msg, __LINE__) void crash(bool cond, char * msg, int line){ if(!cond){ perror(msg); fprintf(stderr, "at line %d\n", line); exit(EXIT_FAILURE); } } Compilation methods that I've already tried (same with each of them): gcc 1.c gcc -std=c99 1.c gcc -std=c11 1.c Any ideas? Thanks. A: Well since all the comments turned out to be equally useless (no offence), I've decided to take a different approach. Instead of sigaction I've used the signal system call. I've also modified a few other things. Since printf is not a signal-safe function I've introduced a global variable named shouldStop which is by default set to false and then changed to true with SIGTERM handler. The printing is then done inside the main function. Here's the code: int sigUsr1Count = 0; int sigUsr2Count = 0; bool shouldStop = false; static void sighandler(int signum){ switch(signum){ case SIGUSR1: sigUsr1Count++; break; case SIGUSR2: sigUsr2Count++; break; } } static void termhandler(int signum){ shouldStop = true; } int main(int argc, char ** argv){ pid_t mypid = getpid(); fprintf(stderr, "My PID is %d\n", mypid); iAssert(SIG_ERR != signal(SIGUSR1, sighandler), "signal1 failed"); iAssert(SIG_ERR != signal(SIGUSR2, sighandler), "signal2 failed"); iAssert(SIG_ERR != signal(SIGTERM, termhandler), "signal3 failed"); do{ }while(!shouldStop); printf("%d %d\n", sigUsr1Count, sigUsr2Count); return 0; } And it works fine the way I wanted it. Thanks anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/54064015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql throwing query error yet finishing query just fine-why? I am getting Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in *filename* on line 81 While running a query to build a chart. The query gets data from the mysql db and uses it to build the chart. Usually, I get this error and go to the code and find where I've screwed up, fix it, and move on. The tricky part about this problem is that the query is actually running and the chart is being built and displayed accurately. Why is my server (localhost on xampp) telling me that the query result is bad when it can utilize the resource just fine? Here is the full query: $chart=array(); $roll=array(); //select used terms $rosh=mysql_query("select distinct term from search_terms"); while($roshrow=mysql_fetch_assoc($rosh)){ extract($roshrow); $roll[]=$term; } //select term_number for each term foreach($roll as $sterm){ $termarray=array(); **//following is line 81** $bashq="select term_number from search_terms where term ='$sterm'"; $bash=mysql_query($bashq); while($brow=mysql_fetch_assoc($bash)){ extract($brow); //put results into array to sum $termarray[]=$term_number; } $termsum=array_sum($termarray); //put term=>number array for chart script $chart[$sterm]=$termsum; } //sort array so high numbers at beginning arsort($chart); //slice top 10 terms $chart=array_slice($chart,0,10); A: Do this: $rosh=mysql_query("select distinct term from search_terms") or die("Error with query: " . mysql_error()); and this: $bash=mysql_query($bashq) or die("Error with query: " . mysql_error(); That will tell you when it fails. You are correct though, you're getting that message because mysql_query has returned "false" and isn't a valid result resource. A: Because your querying within a loop, one of the terms isn't processed (probably because search_terms is missing rows for that specific turn. Which is odd, since you're querying the same table. However, since it's a Warning, and not a fatal Error, it will still continue. Either way, it's seems like wrong way to pulling your data, you can probably do taht with one query, adequate sorting (ORDER BY) directly in the SQL server, GROUP BY and SUM() for getting the sum of your terms. You should read up on your SQL instead :) SELECT term, SUM(term_number) as term_sum FROM search_terms GROUP BY terms ORDER BY term_sum DESC LIMIT 10 then just copy it to your hashtable and it should already be sorted, aswell as limited to 10 entries.
{ "language": "en", "url": "https://stackoverflow.com/questions/288603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to redirect a URL without a query string to a URL with a query string? I've looked around for the answer to my question but only to be confused even more. I'm hoping somebody can help me... I need to redirect this URL: http://www.testsite.co.uk/ecommerce/cabinets/aluminium_cabinets To: http://www.testsite.co.uk/products/cabinets/?types[]=illuminated-aluminium-cabinets&types[]=non-illuminated-aluminium-cabinets Please help :) A: Try : RedirectMatch ^/ecommerce/cabinets/aluminium_cabinets/?$ http://www.testsite.co.uk/products/cabinets/?types[]=illuminated-aluminium-cabinets&types[]=non-illuminated-aluminium-cabinets
{ "language": "en", "url": "https://stackoverflow.com/questions/34515164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Android alert dialog blank space when setting a view I have a question. I made an alert dialog that is showing an message and view with a "do not show again" check-box. When i'm running this app on android KK it is displaying fine, however when I run it on android JB it is showing me a blank space like on this image(i also get this blank space when the view contains only a linear layout with a height of 0dp): http://foto.modelbouwforum.nl/images/2014/08/15/Screenshot2014-08-15-14-33-40.png My code of the alert dialog: final SharedPreferences sharedPreferences=getSharedPreferences("appPrefs", Context.MODE_PRIVATE); if(!sharedPreferences.getBoolean("isTutorialMainScreenChecked", false)){ View checkBoxView = View.inflate(MainScreenHandler.this, R.layout.checkbox_alert_dialog,null); checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox); AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setMessage(getString(R.string.alertDialog_main_screen_tutorial)); builder.setCancelable(false); builder.setView(checkBoxView); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if(checkBox.isChecked()){ SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putBoolean("isTutorialMainScreenChecked", true); editor.commit(); } dialogInterface.dismiss(); } }); builder.setNegativeButton(getString(R.string.alertDialog_cancel), new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialogInterface, int i){ dialogInterface.cancel(); } }); alertDialog = builder.create(); alertDialog.show(); And here is my checkbox layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:baselineAligned="false"> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#ffff3bb2"/> <CheckBox style="@android:style/TextAppearance.Small" android:textColor="#ff000000" android:text="@string/alertDialog_checkbox_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/checkbox"/> </LinearLayout> Thanks in advance P.s: This is how it looks on android KK: http://foto.modelbouwforum.nl/images/2014/08/15/QuickMemo2014-08-15-14-42-41.png A: I looked through sources of alert_dialog.xml layout in API 19 and found the following layout for inserting a custom view: <FrameLayout android:id="@+id/customPanel" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> <FrameLayout android:id="@+android:id/custom" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="5dip" android:paddingBottom="5dip" /> </FrameLayout> Then I tried to set background to see which view takes the space. customPanel was colored in red, custom view was colored in green. AlertDialog d = builder.create(); d.show(); View v = (View)d.getWindow().findViewById(android.R.id.custom).getParent(); v.setBackgroundColor(Color.RED); This picture means that customPanel should have some paddings, or custom should have non-zero layout params or something else. After checking those attributes which were equal to zero I tried to test minimumHeight of the customPanel and got 192 on xxhdpi or 64dp. This setting cause the frame to be larger than a nested custom view. I haven't figured out where this setting is applied, but here is the workaround: AlertDialog d = builder.create(); d.show(); View v = (View)d.getWindow().findViewById(android.R.id.custom).getParent(); v.setMinimumHeight(0); Tested on API 18,19. A: In addition to vokilam's answer: If you're using android.support.v7.app.AlertDialog. Tested on API 27 (pretty sure this works on API 28 too) The layout: <FrameLayout android:id="@+id/contentPanel" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="48dp"> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="wrap_content" android:clipToPadding="false"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <Space android:id="@+id/textSpacerNoTitle" android:visibility="gone" android:layout_width="match_parent" android:layout_height="@dimen/dialog_padding_top_material" /> <TextView android:id="@+id/message" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingEnd="?attr/dialogPreferredPadding" android:paddingStart="?attr/dialogPreferredPadding" style="@style/TextAppearance.Material.Subhead" /> <Space android:id="@+id/textSpacerNoButtons" android:visibility="gone" android:layout_width="match_parent" android:layout_height="@dimen/dialog_padding_top_material" /> </LinearLayout> </ScrollView> </FrameLayout> <FrameLayout android:id="@+id/customPanel" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="48dp"> <FrameLayout android:id="@+id/custom" android:layout_width="match_parent" android:layout_height="wrap_content" /> </FrameLayout> The android:minHeight="48dp" for contentPanel and customPanel are causing the unwanted blank space. Unwanted space dialog What I did is: alertDialog.SetView(view); alertDialog.show(); ... View customPanel = (View) view.getParent().getParent(); if (customPanel != null) customPanel.setMinimumHeight(0); View contentPanel = (View) alertDialog.findViewById(android.R.id.message).getParent().getParent().getParent(); if (contentPanel != null) contentPanel.setMinimumHeight(contentPanel.getMinimumHeight() * 2 / 3); Result: Blank space removed A: Did you try playing around with paddings and margins? You could copy your layout in res/layout-vXX and set a specific (negative) margin.
{ "language": "en", "url": "https://stackoverflow.com/questions/25326665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: QueryDSL DateTime field formatted projection I trying to do a query that returns the date and time part of a Datetime field using QueryDSL. The query in plain SQL looks like this: select convert(varchar, FELectura, 103) as sDate, convert(varchar, FELectura, 108) as sTime from dbo.T2_LecturaEstacionClima; Where FELectura is a DateTime field and the Database is SQL Server 2012. This query gives the following output: sDate sTime ------------------------------ ------------------------------ 02/01/2012 00:00:00 02/01/2012 01:00:00 02/01/2012 02:00:00 02/01/2012 03:00:00 02/01/2012 08:00:00 02/01/2012 09:00:00 02/01/2012 10:00:00 How can i achieve this same output using QueryDSL? A: If you use Querydsl SQL this should work Expression<String> dateExpr = Expressions.stringTemplate("convert(varchar, {0}, 103)", table.feLecutra); Expression<String> timeExpr = Expressions.stringTemplate("convert(varchar, {0}, 108)", table.feLectura); List<Tuple> results = query.from(table).list(dateExpr, timeExpr); And to access the columns from a Tuple instance String date = tuple.get(dateExpr); String time = tuple.get(timeExpr);
{ "language": "en", "url": "https://stackoverflow.com/questions/28548640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: No content after smarty gzip filter I tried smarty gzip plugin smarty gzip plugin. $stpl->loadFilter('output','gzip'); $stpl->display('file:'.$cnf->site_root.$cnf->client_tpl_path.$slang.'/main.tpl'); After this, my site look like that: I don't know why my browser not decoded gzip.
{ "language": "en", "url": "https://stackoverflow.com/questions/35030780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Encountering lag when updating a CardView item in a RecycleView i'm having an issue working with CardViews . I`ve created a CardView containing 1 TextView and 2 ImageViews , which gets displayed in an RecycleView . When i try to update the contents of one of the CardViews (created 5 cards for testing) the interface starts to lag when scrolling over the updated card, but goes back to normal when i pass the item. It only happens when ImageViews are present , when substituting the ImageViews for say, TextViews with some random text in them, it works normally. Now, here's my code , after that i'll add some more information that could be causing it. First , the Adapter class, which also contains the items class and List : public class MovieDetailsAdapter extends RecyclerView.Adapter<MovieDetailsAdapter.MovieViewHolder> { public List<MovieDetails> movieList; private static final String TAG = "MyAdapter"; public MovieDetailsAdapter() { movieList = new ArrayList< MovieDetails>(); } public void setItemCount(int count ,String title, Bitmap poster,Bitmap fanart ) { movieList.clear(); movieList.addAll(generateDummyData(count, title, poster , fanart)); notifyDataSetChanged(); } @Override public int getItemCount() { return movieList.size(); } public void addItem(int position,String title, Bitmap poster, Bitmap fanart) { if (position > movieList.size()) return; movieList.add(position, generateDummyItem(title, poster, fanart)); // notifyDataSetChanged(); notifyItemInserted(position); } public void updateItem(int position, String title, Bitmap poster, Bitmap fanart) { if (position > movieList.size()) return; movieList.add(position, generateDummyItem(title, poster, fanart)); notifyItemChanged(position); // notifyDataSetChanged(); } @Override public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater. from(viewGroup.getContext()). inflate(R.layout.card_layout_movies, viewGroup, false); Log.d(TAG, "create header view holder"); return new MovieViewHolder(itemView); } @Override public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) { Log.d(TAG, "bind header view holder"); MovieDetails mdet = movieList.get(i); movieViewHolder.vTitle.setText(mdet.Title); movieViewHolder.vPoster.setImageBitmap(mdet.imageViewPoster); movieViewHolder.vFanart.setImageBitmap(mdet.imageViewFanart); Log.d(TAG, "position: " + i + " holder: " + movieViewHolder + " text: " + movieViewHolder.vTitle); } public static class MovieViewHolder extends RecyclerView.ViewHolder { protected TextView vTitle; protected ImageView vPoster; protected ImageView vFanart; public MovieViewHolder(View v) { super(v); vTitle = (TextView) v.findViewById(R.id.title); vPoster = (ImageView) v.findViewById(R.id.imageViewPoster); vFanart = (ImageView) v.findViewById(R.id.imageViewFanart); } } public static class MovieDetails { protected String title; protected Bitmap imageViewPoster; protected Bitmap imageViewFanart; public MovieDetails(String title, Bitmap imageViewPoster,Bitmap imageViewFanart ) { this.title = title; this.imageViewPoster = imageViewPoster; this.imageViewFanart = imageViewFanart; } } public static MovieDetails generateDummyItem(String title, Bitmap poster, Bitmap fanart) { MovieDetails mov = new MovieDetails(title, poster, fanart); return mov; } public static List< MovieDetailsAdapter.MovieDetails> generateDummyData(int count, String title , Bitmap imageViewPoster, Bitmap imageviewFanart) { ArrayList<MovieDetailsAdapter.MovieDetails> items = new ArrayList<MovieDetailsAdapter.MovieDetails>(); for (int i=0; i < count; i++) { items.add(new MovieDetailsAdapter.MovieDetails(title, imageViewPoster, imageviewFanart)); } return items; } } Now, here is my main class , the activity class public class MoviesListActivity extends AppCompatActivity { public MovieDetailsAdapter ca = new MovieDetailsAdapter(); public RecyclerView recList; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movies_list); RecyclerView recList = (RecyclerView) findViewById(R.id.cardList); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); recList.setLayoutManager(llm); button = (Button) findViewById(R.id.button); MyOnClickListener Listener = new MyOnClickListener(); button.setOnClickListener(Listener); recList.setItemAnimator(null); Bitmap bittest1 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster_example, 640, 955); Bitmap bittest2 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart_example, 800, 450); ca.setItemCount(5, "TestingTitle", bittest1, bittest2); recList.setAdapter(ca); } public class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: Bitmap bittest12 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster2, 640, 955); Bitmap bittest22 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart2, 800, 450); Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show(); ca.updateItem(1, "test", bittest12, bittest22); // ca.addItem(1,"test",bittest12,bittest22); break; default: break; } } } //------methods used for resizing the images down to smaller ones before loading into memory---// public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } And finally, not that i probably matters, my CardView XML. <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="match_parent" card_view:cardCornerRadius="4dp" android:layout_margin="5dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="20dp" android:background="@color/bkg_card" android:text="Movie Title" android:gravity="center_vertical" android:textColor="@android:color/white" android:textSize="14dp"/> <ImageView android:elevation="5dp" android:scaleType="fitCenter" android:layout_width="100dp" android:layout_height="150dp" android:id="@+id/imageViewPoster" android:text="Poster" android:gravity="center_vertical" android:layout_below="@id/title" android:layout_marginTop="10dp" android:layout_marginLeft="5dp"/> <ImageView android:id="@+id/imageViewFanart" android:scaleType="fitCenter" android:layout_alignBottom="@+id/imageViewPoster" android:layout_toEndOf="@+id/imageViewPoster" android:layout_width= "235dp" android:layout_height="122dp" android:layout_marginRight="5dp"/> </RelativeLayout> Now , somebody in another discussion showed me this as a possible cause : Why RecyclerView.notifyItemChanged() will create a new ViewHolder and use both the old ViewHolder and new one? So i added the Log items inside the onBind and onCreate methods of the Adapter to see if that could be causing it, and indeed, it`s not just creatind one additional ViewHolders, but 3 of them, and each time i scroll over the newly updated card, it seems to be re-binding, the onBind method seems to be called each time. Setting the animation to 'null' as per the solution in the thread doesn't seem to have any effect in my case, so maybe that`s not what is causing it. Any ideas ? A: Well, i solved it. It seems to happen only when i'm loading the images via the XML method, if i load them with a 3rd party library like Picasso, the lag seems to dissapear. Something like : Picasso.with(context).load(MovieDetails.getPoster()) .error(R.drawable.placeholder) .placeholder(R.drawable.placeholder) .into(movieViewHolder.imageViewPoster); inside the onBindViewHolder and instead of passing around bitmaps, just pass a String for the URL or location of the image. And pass the Context to the Adapter class.
{ "language": "en", "url": "https://stackoverflow.com/questions/32554358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Next.JS build with websocket connection I'm trying to build a next.js application which uses signalr for to talk to webservices. However, during the build it tries to connect to the websocket which is not available at build-time and therefore the build fails with the following error: FailedToNegotiateWithServerError: Failed to complete negotiation with the server: FetchError: request to https://localhost:7021/hubs/hub/negotiate?negotiateVersion=1 failed, reason: connect ECONNREFUSED 127.0.0.1:7021 How can we use websockets which are not available runtime. This is how we create the websocket connection in the app: const socketInstance = new HubConnectionBuilder() .configureLogging(LogLevel.None) .withUrl(`${process.env.NEXT_PUBLIC_SOCKET_URL}`) .withAutomaticReconnect() .build(); socketInstance.start().then(() => {});
{ "language": "en", "url": "https://stackoverflow.com/questions/71766443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you find the index of an accordion tab containing a specific element within a jQuery UI Accordion? I have an accordion (an archive) of links/dates. When a user clicks one I am trying to have the accordion expand to the current selected link. To do this, I search the accordion for the link which matches the current URL and would like to then expand the accordion to that link. JSFiddle HTML <div class="desktop"> <div id="blog-archive-accordion"> <h3 id="archive" class="title">Archive</h3> <div id="blog-archive-accordion-year"> <h4>2016</h4> <ul> <li class="month">November (0)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=10">October</a> (5)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=9">September</a> (11)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=8">August</a> (8)</li> .... </ul> <h4>2015</h4> <ul> <li class="month">November (0)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=10">October</a> (5)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=9">September</a> (11)</li> <li class="month"><a class="current-archive-link" href="/website/archive?filter[year]=2016&amp;filter[month]=8">August</a> (8)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=7">July</a> (9)</li> .... </ul> <h4>2014</h4> <ul> <li class="month">November (0)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=10">October</a> (5)</li> <li class="month"><a class="" href="/website/archive?filter[year]=2016&amp;filter[month]=9">September</a> (11)</li> .... </ul> </div> </div> </div> Javascript // Accordionize the above structure. $(function() { $("#blog-archive-accordion").accordion({ header: "h3" }); $("#blog-archive-accordion-year").accordion({ header: "h4" }); }); // Find the current url in the accordion links (obv. doesn't work like this in JSFiddle) //var selectedArchiveLink = $('#blog-archive-accordion').find("a[href='" + location.pathname + location.search +"']").parent(); var selectedArchiveLink = $('#blog-archive-accordion').find(".current-archive-link").parent(); if(selectedArchiveLink.length > 0){ selectedArchiveLink.addClass("current-archive-link"); // Style the current link // How do I know where the found link was? $('#blog-archive-accordion-year').accordion('option', 'active', 1); } In the above example I'm forcing the accordion ope with .accordion('option', 'active', 1); but I would like to know how to find the index of the found link. Considering the index in accordions is based on heading tags and not the actual index in the accordion. IE: <h4></h4> <ul></ul> <div></div> <h4></h4> <div></div> would accordion on the two <h4> tags and the index of the second one is 3 not 1 like you would need for this .accordion() function. A: You can use the index function to get the index/place of the current element inside the parent (and you can use it also based on the tagname) selectedArchiveLink.parent().index('ul') Check the example: http://jsfiddle.net/tg4hc9zr/ A: you might be looking for this. Just add this function to your accordion function call and it will give you the index of h4 tag. Hope this helps. activate: function(evt, widget ) { var index = $(this).find("h4").index(widget.newHeader[0]); } $("#blog-archive-accordion-year").accordion({ header: "h4", activate: function(evt, widget ) { var index = $(this).find("h4").index(widget.newHeader[0]); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/40513347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Tensorflow frozen .pb model to keras model I have tensorflow .pb frozen model and i would like to retrain this model with new data and in order to do that i would like to convert the tf .pb frozen model to a keras model. i was able to visualise layers and weight values and i wana know if it is possible to convert this .pb model to a keras model in order to retain it or if there is another solution in order to retrain a .pb frozen model ? import tensorflow.compat.v1 as tf tf.disable_v2_behavior() detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile('weight/saved_model.pb', 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') conf = tf.ConfigProto() session = tf.Session(graph=detection_graph, config=conf) #layers name layers = [op.name for op in detection_graph.get_operations()] for layer in layers: print(layer) Const ToFloat Const_1 ToFloat_1 Const_2 ToFloat_2 image_tensor ToFloat_3 Preprocessor/map/Shape Preprocessor/map/strided_slice/stack Preprocessor/map/strided_slice/stack_1 Preprocessor/map/strided_slice/stack_2 Preprocessor/map/strided_slice Preprocessor/map/TensorArray Preprocessor/map/TensorArrayUnstack/Shape Preprocessor/map/TensorArrayUnstack/strided_slice/stack Preprocessor/map/TensorArrayUnstack/strided_slice/stack_1 Preprocessor/map/TensorArrayUnstack/strided_slice/stack_2 Preprocessor/map/TensorArrayUnstack/strided_slice Preprocessor/map/TensorArrayUnstack/range/start Preprocessor/map/TensorArrayUnstack/range/delta Preprocessor/map/TensorArrayUnstack/range Preprocessor/map/TensorArrayUnstack/TensorArrayScatter/TensorArrayScatterV3 Preprocessor/map/Const Preprocessor/map/TensorArray_1 Preprocessor/map/TensorArray_2 Preprocessor/map/while/Enter Preprocessor/map/while/Enter_1 Preprocessor/map/while/Enter_2 Preprocessor/map/while/Merge Preprocessor/map/while/Merge_1 Preprocessor/map/while/Merge_2 Preprocessor/map/while/Less/Enter Preprocessor/map/while/Less Preprocessor/map/while/LoopCond Preprocessor/map/while/Switch Preprocessor/map/while/Switch_1 Preprocessor/map/while/Switch_2 Preprocessor/map/while/Identity Preprocessor/map/while/Identity_1 Preprocessor/map/while/Identity_2 Preprocessor/map/while/TensorArrayReadV3/Enter Preprocessor/map/while/TensorArrayReadV3/Enter_1 Preprocessor/map/while/TensorArrayReadV3 Preprocessor/map/while/ResizeImage/stack Preprocessor/map/while/ResizeImage/resize_images/ExpandDims/dim Preprocessor/map/while/ResizeImage/resize_images/ExpandDims Preprocessor/map/while/ResizeImage/resize_images/ResizeBilinear Preprocessor/map/while/ResizeImage/resize_images/Squeeze Preprocessor/map/while/ResizeImage/stack_1 Preprocessor/map/while/TensorArrayWrite/TensorArrayWriteV3/Enter Preprocessor/map/while/TensorArrayWrite/TensorArrayWriteV3 Preprocessor/map/while/TensorArrayWrite_1/TensorArrayWriteV3/Enter Preprocessor/map/while/TensorArrayWrite_1/TensorArrayWriteV3 Preprocessor/map/while/add/y Preprocessor/map/while/add Preprocessor/map/while/NextIteration Preprocessor/map/while/NextIteration_1 Preprocessor/map/while/NextIteration_2 Preprocessor/map/while/Exit_1 Preprocessor/map/while/Exit_2 Preprocessor/map/TensorArrayStack/TensorArraySizeV3 Preprocessor/map/TensorArrayStack/range/start Preprocessor/map/TensorArrayStack/range/delta Preprocessor/map/TensorArrayStack/range Preprocessor/map/TensorArrayStack/TensorArrayGatherV3 Preprocessor/map/TensorArrayStack_1/TensorArraySizeV3 Preprocessor/map/TensorArrayStack_1/range/start Preprocessor/map/TensorArrayStack_1/range/delta Preprocessor/map/TensorArrayStack_1/range Preprocessor/map/TensorArrayStack_1/TensorArrayGatherV3 Preprocessor/sub/y Preprocessor/sub Shape FirstStageFeatureExtractor/Shape FirstStageFeatureExtractor/strided_slice/stack FirstStageFeatureExtractor/strided_slice/stack_1 FirstStageFeatureExtractor/strided_slice/stack_2 FirstStageFeatureExtractor/strided_slice FirstStageFeatureExtractor/GreaterEqual/y FirstStageFeatureExtractor/GreaterEqual FirstStageFeatureExtractor/Shape_1 FirstStageFeatureExtractor/strided_slice_1/stack FirstStageFeatureExtractor/strided_slice_1/stack_1 FirstStageFeatureExtractor/strided_slice_1/stack_2 FirstStageFeatureExtractor/strided_slice_1 FirstStageFeatureExtractor/GreaterEqual_1/y FirstStageFeatureExtractor/GreaterEqual_1 FirstStageFeatureExtractor/LogicalAnd FirstStageFeatureExtractor/Assert/Assert/data_0 FirstStageFeatureExtractor/Assert/Assert FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/Pad/paddings FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/Pad FirstStageFeatureExtractor/resnet_v1_101/conv1/weights FirstStageFeatureExtractor/resnet_v1_101/conv1/weights/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/conv1/Conv2D FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/gamma FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/gamma/read FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/beta FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/beta/read FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/moving_mean FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/moving_mean/read FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/moving_variance FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm/moving_variance/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/conv1/BatchNorm/FusedBatchNorm FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/conv1/Relu FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/pool1/MaxPool FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/weights FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/weights/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/Conv2D FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/gamma FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/gamma/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/beta FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/beta/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/moving_mean FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/moving_mean/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/moving_variance FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/moving_variance/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/FusedBatchNorm FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/weights FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/weights/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/Conv2D FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/gamma FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/gamma/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/beta FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/beta/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_mean FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_mean/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_variance FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_variance/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/FusedBatchNorm FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/Relu FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/weights FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/weights/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/Conv2D FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/gamma FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/gamma/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/beta FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/beta/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/moving_mean FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/moving_mean/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/moving_variance FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/moving_variance/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm/FusedBatchNorm FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/Relu FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/weights FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/weights/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/Conv2D FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/gamma FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/gamma/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/beta FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/beta/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/moving_mean FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/moving_mean/read FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/moving_variance FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/moving_variance/read FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm/FusedBatchNorm FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/add FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block1/unit_1/bottleneck_v1/Relu #visualise weight from tensorflow.python.framework import tensor_util weight_nodes = [n for n in od_graph_def.node if n.op == 'Const'] for n in weight_nodes: print("Name of the node - %s" % n.name) print("Value - " ) print(tensor_util.MakeNdarray(n.attr['value'].tensor)) Value - [-0.4540853 0.32056493 -0.22912885 0.2541284 -0.9532805 -0.25493076 -0.5082643 -0.33983043 -0.22494698 -0.3235537 -0.36385655 -0.28415084 -0.5575271 -0.1910503 -0.49338412 -0.42885196 -0.33558807 -0.6404074 -0.18031892 -0.2801433 -0.34614867 -0.5399439 -0.15712368 -0.2957037 0.15714812 -0.48186925 -0.33291766 -0.48722127 -0.2535558 -0.16819339 -0.43470743 -0.2855552 -0.3963132 -0.42684224 -0.3209245 -0.3658357 -0.30626386 -0.4134465 0.03801734 -0.43680775 -0.29162335 -0.36223125 -0.48077616 -0.43840355 -0.39883605 -0.31524658 -0.47961026 -0.41313347 -0.19943158 -0.9744824 -0.44492397 -0.62325597 -0.4503377 -0.32147056 -0.32696253 -0.3964685 -0.4328564 -0.28047583 -0.10022314 -0.20008062 -0.25767517 -0.32787508 -0.7490349 -0.26016906 -0.1388798 -0.00777247 -0.34971157 -0.37617198 -0.16701727 -0.49006486 0.25721186 -0.2046591 -0.39323628 -0.6523374 -0.5105675 -0.32751757 -0.2652611 -0.00875285 -0.2443423 -0.44029924 -0.37004694 -0.23282264 -0.3413406 -0.35088956 -0.46555945 -0.56252545 -0.5163544 -0.5306529 -0.62014216 -0.24062826 -0.06821899 -0.33485538 -0.4521361 -0.6593677 -0.46554345 -0.40829748 -0.49771288 -0.35069707 -0.0229042 -0.2298909 -0.25005338 -0.32683375 -0.49131876 -0.30173704 -0.29786837 -0.67599934 -0.35004795 -0.20007414 -0.16419795 -0.49680758 -0.42260775 -0.2726915 -0.6200565 -0.35487327 -0.3344669 -0.52208656 -0.4569452 -0.12290002 -0.5652516 -0.31340426 -0.3985747 -0.5281181 -0.7129867 -0.567227 -0.28814644 -0.1302681 -0.2001429 -0.10916138 -0.68222445 -0.29323065 -0.05704954 -0.22789052 -0.61558 -0.07655394 -0.52930903 -0.34198323 -0.24209192 -0.5053026 -0.4004574 -0.15969647 -0.35341594 -0.5591511 -0.40825605 -0.01070203 -0.7428409 -0.45172128 -0.43380788 0.2568167 -0.6722297 -0.35276502 -0.6669023 -0.20694211 -0.20189697 -0.5070727 -0.3972058 -0.00848175 -0.2994657 -0.34944996 -0.3389741 -0.17936742 -0.92425096 -0.05345222 -0.38853544 -0.39970097 -0.3607101 -0.7013903 -0.10112807 -0.2565767 -0.34176925 -0.52231157 -0.476935 -0.45604366 -0.5980594 -0.15625392 -0.42476812 -0.31922927 -0.31709027 -0.28081933 -0.2383788 -0.3822803 -0.58110493 -0.48278278 0.37628186 -0.28682145 -0.36748675 -0.34278873 -0.4303303 -0.31955504 -0.1693851 -0.4306607 -0.30947846 -0.29114336 -0.490207 -0.487192 -0.24403661 -0.30346867 -0.27445573 -0.35093272 -0.22612163 -0.41189626 -0.24778591 -0.31198287 -0.24912828 -0.40960005 -0.35579422 -0.43333185 -0.6709562 -0.844466 -0.14793177 -0.2053809 -0.5682712 -0.23429349 -0.35484084 -0.40705127 -0.16986188 -0.52707803 -0.371436 -0.3203282 -0.548174 -0.2454479 0.14760983 -0.23899662 -0.49904364 -0.5957814 -0.24498118 -0.15208362 -0.38576075 -0.4792993 -0.37565476 -0.48903054 -0.30210334 -0.5700767 -0.21236268 -0.57294637 -0.27853557 -0.46409875 -0.24420401 -0.48441198 -0.64328116 -0.47033066 -0.2866155 -0.24524617 -0.682954 0.22307628 -0.4910605 -0.6759475 -0.5597055 -0.08977205 -0.35018525 -0.326844 -0.407895 -0.4286294 -0.43290117 -0.43665645 -0.03084541 -0.38888484] Name of the node - FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv2/BatchNorm/moving_mean Value - [-0.15717725 0.07592656 0.10988383 -0.0490528 -0.0106115 -0.15786496 -0.11409757 -0.06248363 -0.06544019 -0.14081511 -0.17109169 -0.02211305 -0.03773279 -0.12710223 -0.12394962 -0.09206913 -0.16163616 -0.1723962 -0.20561686 -0.1415835 -0.06350002 -0.16257662 -0.09603897 -0.13460924 -0.02432729 -0.04199889 -0.1696589 -0.13546434 -0.06083817 -0.10085563 -0.09488994 0.04238822 -0.01342436 -0.15949754 -0.17468 -0.17448752 -0.07917193 -0.12688611 -0.22540613 0.0227522 -0.10866571 -0.05292162 -0.09184872 -0.15055841 -0.166075 -0.20481528 -0.0362504 -0.03834244 -0.0642691 0.0847474 -0.05358214 -0.01985169 -0.23435758 -0.14982411 -0.16710722 -0.15368192 -0.09551494 -0.16474426 -0.10215978 -0.16959386 -0.20461345 -0.03911749 -0.14563459 -0.00461106 -0.0700466 -0.0968714 0.00481458 -0.04512146 -0.14357145 -0.19567277 -0.19265638 -0.11200134 -0.07045556 -0.02379003 -0.10341825 -0.03273268 -0.11432283 -0.23813714 -0.02153216 -0.14714707 -0.1272525 -0.16946757 -0.1185687 -0.12256996 -0.10922257 0.11201918 -0.02812816 -0.02523885 0.03150908 -0.15362865 -0.1581234 0.00402692 -0.15670358 -0.04513093 -0.1437301 -0.01758968 -0.05778598 -0.14521386 0.01999546 -0.1154804 -0.19333984 -0.06223019 -0.07321492 -0.07283846 -0.12676379 -0.04754475 -0.12439732 -0.0936267 -0.1395944 -0.10460664 -0.1278241 -0.11326854 -0.08205313 -0.1579616 -0.04214557 -0.13230218 -0.15926664 -0.11025801 -0.17300427 -0.03396817 0.01946657 -0.02238615 -0.1087622 0.05757551 -0.06369423 -0.15768676 -0.24096929 -0.16477783 -0.08505792 -0.1452452 -0.1228498 -0.18778118 -0.10847382 -0.18381962 -0.09624809 -0.11529081 -0.08679712 -0.026652 -0.0709608 -0.13419388 -0.12301534 -0.0762615 -0.1779636 0.0712171 -0.02847089 -0.03589171 -0.16578905 0.06647447 -0.21369869 -0.11737502 -0.09483987 -0.1711197 -0.10486519 -0.13668095 -0.09134877 -0.17883773 -0.09831014 0.00876497 -0.01898824 -0.12447593 -0.11287156 -0.14073113 -0.14082104 -0.20715335 -0.0960372 -0.07659613 -0.05445954 -0.20973818 -0.1988086 -0.07440972 -0.01645763 -0.06222945 -0.10685738 -0.11946698 -0.02095333 -0.22138861 -0.03730138 -0.14171903 -0.2022561 -0.17174341 -0.10660502 -0.04700039 0.21646874 -0.2798932 -0.0933376 -0.15969937 -0.11783579 -0.08365067 -0.15353799 -0.09762033 -0.20146982 -0.10279506 -0.14905539 -0.12379898 -0.12730977 -0.06474843 -0.09232798 -0.07322481 -0.19277479 -0.04613561 -0.13307215 -0.1302453 -0.17341715 -0.07773575 -0.04985441 -0.10355914 -0.1078042 0.00853426 -0.13236587 -0.09865464 -0.00562798 -0.12181614 -0.22204153 -0.05784107 -0.18404393 -0.00629737 -0.10935344 -0.06820714 -0.0653091 -0.10879692 -0.12568252 -0.1386066 -0.10166074 -0.05466842 -0.09380525 -0.20807257 -0.09541806 -0.0593087 -0.12657529 -0.12999491 -0.08768366 -0.11886697 -0.11744718 -0.08663379 -0.1193763 -0.08805308 -0.1727127 -0.00644481 -0.11248584 0.00345422 -0.1572065 -0.07471903 -0.09579102 -0.08642395 -0.08458085 0.09465432 -0.0749066 0.04966704 -0.06954169 -0.05878955 -0.06419392 -0.03276661 -0.12470958 -0.05546655 -0.227529 -0.18447787] Name of the node - FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv2/BatchNorm/moving_variance Value - [0.0246328 0.15109949 0.08894898 0.18027042 0.17676981 0.03751087 0.04503109 0.05276729 0.07223138 0.0510329 0.05425516 0.03137682 0.03304449 0.04246168 0.03573015 0.04623629 0.04350977 0.03313071 0.04221025 0.04383035 0.04444639 0.03855932 0.03536414 0.03979863 0.12287893 0.03251396 0.03785344 0.03404477 0.05788973 0.05000394 0.03611772 0.04200751 0.03447625 0.04483994 0.03660354 0.05133959 0.03763206 0.03538596 0.0754443 0.03522145 0.03955411 0.03173661 0.0307942 0.04629485 0.04174245 0.06112912 0.03868164 0.03610169 0.03457952 0.03306652 0.03208408 0.03130876 0.04425795 0.0543987 0.04187379 0.05363455 0.04050811 0.03573698 0.03850965 0.0455887 0.03908563 0.03638468 0.03675755 0.03934622 0.03829562 0.05719311 0.03649542 0.02670012 0.03625882 0.03489691 0.1415123 0.04595942 0.04740899 0.0362278 0.03886651 0.02929924 0.03411594 0.05056536 0.04927529 0.03879778 0.04310857 0.03617069 0.03727381 0.03174838 0.03664678 0.11009517 0.02481679 0.03278335 0.05939993 0.03593603 0.03523111 0.02616766 0.03424251 0.0344963 0.04709259 0.03183395 0.03848327 0.03769235 0.04920188 0.03951766 0.03903662 0.03408873 0.03334353 0.03571996 0.06089876 0.05937878 0.03344719 0.04584214 0.04397506 0.03307587 0.03318075 0.04908697 0.03105905 0.05623207 0.05571087 0.03729884 0.0459931 0.04489287 0.04131918 0.03771564 0.04307055 0.03846145 0.05100024 0.043197 0.04114237 0.05911661 0.03956391 0.04361542 0.03280107 0.03139602 0.05827128 0.04082137 0.03654662 0.04679587 0.0309209 0.03587716 0.03316435 0.02562451 0.03213744 0.04613245 0.03237009 0.03835384 0.0523162 0.09062187 0.03235107 0.02755782 0.03724603 0.09937367 0.07468802 0.03093713 0.02697526 0.04269885 0.0421169 0.03236708 0.03591317 0.05501648 0.04456919 0.03508786 0.03599152 0.05607978 0.04522029 0.05920529 0.02929832 0.04003889 0.04818926 0.03470782 0.04554065 0.03561359 0.05097282 0.03162495 0.03105365 0.0479041 0.04201244 0.03967372 0.03850067 0.03719724 0.03236697 0.04217942 0.04472516 0.06050858 0.02926525 0.03916026 0.19374044 0.0456128 0.03878816 0.0363459 0.03911297 0.03797501 0.04174663 0.04230652 0.03831306 0.04085784 0.0427238 0.03057992 0.03531543 0.03794312 0.03533817 0.03804426 0.02861266 0.03188168 0.04924265 0.04050563 0.04611768 0.03238661 0.03605983 0.02848955 0.0390384 0.02533518 0.04691761 0.04362593 0.03430253 0.04009234 0.04348955 0.03593319 0.04101577 0.02840054 0.03196882 0.03733175 0.03510671 0.04594112 0.15954044 0.04420807 0.04092796 0.02599568 0.04426222 0.05545853 0.04792674 0.05130733 0.03689643 0.04262947 0.04004824 0.02642712 0.04293796 0.0296522 0.04023833 0.04849512 0.04770563 0.02930979 0.033105 0.03017242 0.03861351 0.03882564 0.03877705 0.10539907 0.03036495 0.0441276 0.02591156 0.07158393 0.03235719 0.04087997 0.02184044 0.03179693 0.04023989 0.03014399 0.06206222 0.06290652]
{ "language": "en", "url": "https://stackoverflow.com/questions/69828783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp( ) Performing hot reload... Syncing files to device Android SDK built for x86... Reloaded 0 libraries in 505ms. ======== Exception caught by widgets library ======================================================= The following FirebaseException was thrown building Builder: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() The relevant error-causing widget was: MaterialApp file:///E:/Programs/flutterLearning/flash-chat-flutter/lib/main.dart:16:12 When the exception was thrown, this was the stack: #0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5) #1 Firebase.app (package:firebase_core/src/firebase.dart:53:41) #2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47) #3 new _RegistrationScreenState (package:flash_chat/screens/registration_screen.dart:15:30) #4 RegistrationScreen.createState (package:flash_chat/screens/registration_screen.dart:11:45) ... A: did you do this? in your main() you have to call Firebase.initializeApp() void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); await GetStorage.init(); await load(); runApp(InitiateApp()); } A: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); // You are missing this statement runApp(MyApp()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/66937824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Display module in all pages of site except admin pages DNN7 I am using DNN7. I have added a HTML module on my DNN7 site which needs to displayed on all the pages except admin pages.So i configured in settings of the module which said display module on all pages.But the problem i am facing is when i check this option to display on all pages the module is getting displayed on admin pages too which i don't require.*Is their any option to disable the module on admin pages and show only site pages.*Please help. Thanks, A: I don't think there is such an option. You just have to remove it manually from the admin pages you mostly use
{ "language": "en", "url": "https://stackoverflow.com/questions/17696282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: R: Duplicating a subset of row values, based on condition, across a whole dataframe I have a dataframe df containing count data at different sites, across two days: day site count 1 A 2 1 B 3 2 A 10 2 B 12 I would like to add a new column day1count that represents the count value at day 1, for each unique site. So, on rows where day==1, count and day1count would be identical. The new df would look like: day site count day1count 1 A 2 2 1 B 3 3 2 A 10 2 2 B 12 3 So far I've created a new column that has duplicate values for day 1 rows, and NA for everything else: df$day1count= ifelse(df$day==1, df$count, NA) day site count day1count 1 A 2 2 1 B 3 3 2 A 10 NA 2 B 12 NA How can I now replace the NA entries with values corresponding to each unique site from day 1? A: I figured it out. It's not very elegant (and I invite others to submit a more efficient approach) but... Do NOT create the new column with df$day1count= ifelse(df$day==1, df$count, NA) as I did in the original example. Instead, start by making a duplicate of df, but which only contains rows from day 1 tmpdf = df[df$day==1,] Rename count as day1count, and remove day column tmpdf = rename(tmpdf, c("count"="day1count")) tmpdf$day = NULL Merge the two dataframes by site newdf = merge(x=df,y=tmpdf, by="site") newdf site day count day1count 1 A 1 2 2 2 A 2 10 2 3 B 1 3 3 4 B 2 12 3 A: With tidyverse you could do the following: library(tidyverse) df %>% group_by(site) %>% mutate(day1count = first(count)) Output # A tibble: 4 x 4 # Groups: site [2] day site count day1count <int> <fct> <int> <int> 1 1 A 2 2 2 1 B 3 3 3 2 A 10 2 4 2 B 12 3 Data df <- read.table( text = "day site count 1 A 2 1 B 3 2 A 10 2 B 12", header = T )
{ "language": "en", "url": "https://stackoverflow.com/questions/60871343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Take screenshot of element (jpg,png) and then download it. Javascript I want to make a JS function which can take the screenshot from element and then download it. <body> <h1>Sample text</h1> <h2>Sample text</h2> <table width="1080px" height="1920px" border="1" style="border-collapse:collapse"> <tbody><tr> <td colspan="2"> <img src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png" width="600px"> </td> <td> Sample text </td> </tr> <tr style="background:#b6ff00"> <td> Sample text </td> <td> Sample text </td> <td> Sample text </td> </tr> </tbody></table> <h1> sample text </h1> <h2>Sample text</h2> <br><br> <input type="button" value="Capture" onclick="capture()"> </body> After clicking capture button I want this td colspan="2" element to be screenshoted and downloaded on jpg or png format. A: Using html2canvas could help you, it converts an element into a canvas, and then you just need to add its data as a url into an a element function download(canvas, filename) { const data = canvas.toDataURL("image/png;base64"); const donwloadLink = document.querySelector("#download"); donwloadLink.download = filename; donwloadLink.href = data; } html2canvas(document.querySelector(".card")).then((canvas) => { // document.body.appendChild(canvas); download(canvas, "asd"); }); Check a full example here https://codepen.io/koseare/pen/NWpMjeP A: Try with html2canvas; <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="all"> <h2>Sample text</h2> <table width="1080px" height="1920px" style="border-collapse: collapse"> <tbody> <tr> <td colspan="2"> <img src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png" width="600px" /> </td> <td>Sample text</td> </tr> <tr style="background: #b6ff00"> <td>Sample text</td> <td>Sample text</td> <td>Sample text</td> </tr> </tbody> </table> </div> <br /> <input type="button" id="btn" value="Download" /> <script> document.getElementById("btn").addEventListener( "click", function () { var text = document.getElementById("all").value; var filename = "output.txt"; download(filename, function makeScreenshot() { html2canvas(document.getElementById("screenshot"), {scale: 1}).then(canvas => { document.body.appendChild(canvas); }); }); }, false ); </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/67850366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authentication failed when trying to download azure API Management locally I am trying to download the Azure API Management Repository locally using Git Bash following he steps on this page: https://learn.microsoft.com/en-us/azure/api-management/api-management-configuration-repository-git. The problem is that I keep getting the "Authentication failed" even though I have doubled checked the generated password multiple times. Steps I did to download the REPO: * *Saved the service config to the git repo. *Got the access credentials. *Tried to clone the repo locally first by using the unencode password and after that using the encoded one. (encoded it in terminal using echo "myPass" | base64 ) I did this multiple times by generating multiple passwords, same result: authentication failed git clone https://user:encodedPasswordInBase64@myDomain.scm.azure-api.net Are there any user rights that I am supposed to have in order to do this successfully? A: The only way I managed to make it work was by only providing the username to the git clone command: git clone https://user@myDomain.scm.azure-api.net Once I did that, a login pop up appeared and I was able to insert my password unencoded, managing to clone it. So from my point of view it might be a documentation error since adding the encoded password did not work. I have to mention that I encoded the password because the git bash stated that some of the passwords characters were not allowed in there
{ "language": "en", "url": "https://stackoverflow.com/questions/73501306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separating code into DLL's away from exe We update our WPF app multiple times a week, this is a pain point as Customers are repeatedly asked to let the exe through their firewall. To get around this, I will try taking most of the code (including xaml) out of the exe, so the exe never changes. The below method seems to work, is there any reason why I should not do it this way? e.g. is it ok to have multiple Application objects? Project: TestWpfSeperateCodeFromExe namespace TestWpfSeperateCodeFromExe { public class App { // Entry point method [STAThread] public static void Main(string[] args) { AppView.Main(args); } } } Project: View namespace View { public class AppView : Application { // Entry point method [STAThread] public static void Main(string[] args) { var app = new AppView(); app.Run(); } public AppView() { new MainWindow().Show(); } } } A: A much better approach would be to move your code (including XAML) to one or several User Control libraries. Then your main EXE would just load these controls. A: using another application-object will most likely break many things as you have no direct control over the process - you should avoid that and use simple function/method-calls instead, these work flawlessly and thats what DLLs are for. In fact, i actually think this wont be possible in the way you imagined it. Using DLLs like everbody does has loads of advantages, you can move 99% of your code into the DLL and make the primary entry-point (the EXE-file) absolutely static, theres no need to fiddle around with the application-object.
{ "language": "en", "url": "https://stackoverflow.com/questions/14464123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ECDSA sign using OpenSSL without ASN1 encoding the hash Im doing ECDSA signatures using dgst command with OpenSSL as follows: openssl dgst -sha256 -sign key.pem -out my_signature data_file which works just fine. However I read in this SO answer that it first SHA256 hashes the data_file, and ASN.1 encodes the hash before signing it. I would like to create the SHA256 hash of the data and make ECDSA sign just the raw bytes of this hash. (As this is the ECDSA signature, I cannot use rsautl as in the mentioned SO answer.) How do I achieve this using OpenSSL? A: You can do it with openssl pkeyutl which is a replacement for openssl rsautl that supports ECDSA. Suppose you want to hash and sign a 'data.txt' file with openssl. At first you need to hash the file: openssl dgst -sha256 -binary -out data.sha256 data.txt after you can sign it: openssl pkeyutl -sign -inkey private.pem -in data.sha256 -out data.sig However the signature is still in ASN.1 format. To receive r and s values of signature use openssl asn1parse: openssl asn1parse -inform DER -in data.sig
{ "language": "en", "url": "https://stackoverflow.com/questions/25421399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to update label.text in asp.net from code behind-values I want to popup a message everytime I click on a button. This popup shows some information and updates its labels according to my code behind-values. I tried different things like declare variable either protected or public: Protected test As string = "test" '(...) test = "another string" And in .aspx file: <%=test%> But then I noticed I can't have <%=%> blocks within the attributes of server-side controls (such as <asp:Label>). I tried to set the .Text property in the code-behind itself and it works on Page Load, but I want to set the .Text values in another function dynamically. Protected Sub Page_Load(object sender, EventArgs e) If Not Page.IsPostBack Then pagenumberLabel.Text = GetPagingCaptionString() End If End Sub I've also tried to create an hidden button and perform the click via javascript but the values are not being passed. [.ASPx.VB] Protected fileName As string = "" Protected Sub UpdatePopup(ByVal fileName As String) 'fileName = "write my file name" ASPxLabelName.Text = fileName ' this doens't work (filename="") End Sub ' OR Protected Sub UpdateButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles UpdateButton.Click fileName = "write my file name" ASPxLabelName.Text = fileName ' This works but it is not dynamic as wanted End Sub [.ASPx] <dx:ASPxPopupControl ID="ASPxPopupControl1" runat="server" ClientInstanceName="ShowMessageInfo" CloseAction="CloseButton" CloseOnEscape="True" EnableViewState="False" PopupHorizontalAlign="WindowCenter" PopupVerticalAlign="WindowCenter" HeaderText="HEADER" AllowDragging="True" Modal="True" PopupAnimationType="Fade" PopupAction="None" Width="400px"> <ContentCollection> <dx:PopupControlContentControl ID="PopupControlContentControl1" runat="server"> <dx:ASPxPanel ID="Panel1" runat="server"> <PanelCollection> <dx:PanelContent ID="PanelContent1" runat="server"> <table cellspacing="0" cellpadding="5" width="100%"> <tr> <td>Name:</td> <td><dx:ASPxLabel ID="ASPxLabelName" runat="server" Text=""> </dx:ASPxLabel></td> </tr> </table> <dx:ASPxButton ID="UpdateButton" runat="server" Text="Update Content" style="display:none" AutoPostBack="False"> <ClientSideEvents Click="function(s, e) { ShowMessageInfo.PerformCallback(); }" /> </dx:ASPxButton> </dx:PanelContent> </PanelCollection> </dx:ASPxPanel> </dx:PopupControlContentControl> </ContentCollection> </dx:ASPxPopupControl>
{ "language": "en", "url": "https://stackoverflow.com/questions/32439847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fucnction giving NaN response when calling it through another function If I use a click event to call this function it works fine: canvas = document.getElementById("svg"); function relMouseCoords(event){ var totalOffsetX = 0; //coordinates of corner of canvas var totalOffsetY = 0; var canvasX = 0; var canvasY = 0; var canvas = this; //what called the event do{ totalOffsetX += canvas.offsetLeft - canvas.scrollLeft; //relative coordinates totalOffsetY += canvas.offsetTop - canvas.scrollTop; } while(canvas = canvas.offsetParent) canvasX = event.pageX - totalOffsetX; canvasY = event.pageY - totalOffsetY; point = {x:canvasX, y:canvasY}; console.log(point.x + " " + point.y); return point; //object returned } But when i try and call it through this function using a click event it returns an object with two NaN values inside: function drawRectangle(event){ var startPoint; startPoint = relMouseCoords(event); console.log(startPoint); } Could anyone please explain to me why this is? and if there is a fix for it? I would not like to use JQuery if anyone has responses to do with it. Thanks A: This is answered in the comments on the original post. It was fixed by just removing var canvas = this;.
{ "language": "en", "url": "https://stackoverflow.com/questions/28625943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sphinx unable to import some modules I am using to generate documentation for codebase. While building the docs, I could see that they were built for some modules only and many were left undocumented with warning in console - failed to import <module-name>.Even after going through official documentation and multiple answers on stackoverflow, I am unable to get why it's not working. Following is structure of codebase:- docs โ”œโ”€โ”€ Makefile โ”œโ”€โ”€ make.bat โ”œโ”€โ”€ source โ”‚ โ”œโ”€โ”€ _templates โ”‚ โ”‚ โ”œโ”€โ”€ custom-class-template.rst โ”‚ โ”‚ โ””โ”€โ”€ custom-module-template.rst โ”‚ โ”œโ”€โ”€ conf.py โ”‚ โ””โ”€โ”€ index.rst extract โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ avro_converter โ”‚ โ”‚ โ”œโ”€โ”€ JSON_converter.py โ”‚ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ helpers โ”‚ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”‚ โ””โ”€โ”€ helpers.py In index.rst file, I am trying to import documentation for extract module as follows [ref]:- Welcome to documentation! ====================================== Modules ====================================== .. autosummary:: :toctree: _autosummary :template: custom-module-template.rst :recursive: extract Docs are rendered using following template:- custom-module-template.rst {{ fullname | escape | underline}} .. automodule:: {{ fullname }} {% block attributes %} {% if attributes %} .. rubric:: Module attributes .. autosummary:: :toctree: :nosignatures: {% for item in attributes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block functions %} {% if functions %} .. rubric:: {{ _('Functions') }} .. autosummary:: :toctree: :nosignatures: {% for item in functions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block classes %} {% if classes %} .. rubric:: {{ _('Classes') }} .. autosummary:: :toctree: :template: custom-class-template.rst :nosignatures: {% for item in classes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block exceptions %} {% if exceptions %} .. rubric:: {{ _('Exceptions') }} .. autosummary:: :toctree: :nosignatures: {% for item in exceptions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block modules %} {% if modules %} .. autosummary:: :toctree: :template: custom-module-template.rst :nosignatures: :recursive: {% for item in modules %} {{ item }} {%- endfor %} {% endif %} {% endblock %} For building docs, following is configuration in config.py :- import os import sys sys.path.insert(0, os.path.abspath('../..')) project = 'sample' copyright = '2021, Vineet Sharma' author = 'Vineet Sharma' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.coverage', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode' ] templates_path = ['_templates'] exclude_patterns = ['_build', '_templates'] html_theme = 'sphinx_rtd_theme' html_static_path = [] autosummary_generate = True For the file JSON_converter, there are few dependencies used by functions inside it as follows:- JSON_converter.py import json import multiprocessing import os import random import string import sys import traceback from configparser import ConfigParser from datetime import datetime from imp import reload import boto3 import fastavro import pandas as pd # get current directory current_dir = os.getcwd() sys.path.append(os.path.join(os.path.dirname(current_dir))) reload(sys) # helpers in another folder inside extract which contains a file named helpers.py; this file gets documented without any error from helpers.helpers import enqueue, make_local_dir, remove_dir, read_csv # parent directory config_path = os.path.join(os.path.dirname(current_dir), "config.ini") CONFIG = ConfigParser() CONFIG.read(config_path) .... .... On running make html command I get following error:- WARNING: [autosummary] failed to import 'extract.avro_converter.JSON_converter': no module named extract.avro_converter.JSON_converter /Users/espm2381/epi/titan/docs/source/_autosummary/extract.avro_converter.rst.rst:24: WARNING: autosummary: failed to import extract.avro_converter.JSON_converter One of the reason for such errors is not having modules installed in your environment. But, I have all dependencies installed in my environment as follows:- alabaster==0.7.12 awscli==1.19.16 Babel==2.9.1 beautifulsoup4==4.9.3 boto3==1.17.16 botocore==1.20.16 certifi==2021.5.30 charset-normalizer==2.0.3 click==8.0.1 colorama==0.4.3 docutils==0.15.2 et-xmlfile==1.0.1 fastavro==1.3.4 furo==2021.7.5b38 idna==3.2 imagesize==1.2.0 jdcal==1.4.1 Jinja2==2.11.3 jmespath==0.10.0 joblib==1.0.1 MarkupSafe==1.1.1 numpy==1.20.1 openpyxl==3.0.6 packaging==21.0 pandas==1.2.2 pyarrow==3.0.0 pyasn1==0.4.8 pydata-sphinx-theme==0.6.3 Pygments==2.9.0 pyparsing==2.4.7 python-dateutil==2.8.1 python-snappy==0.6.0 pytz==2021.1 PyYAML==5.4.1 requests==2.26.0 rsa==4.7.2 s3transfer==0.3.4 scikit-learn==0.24.1 scipy==1.7.0 sentry-sdk==1.1.0 six==1.15.0 snowballstemmer==2.1.0 soupsieve==2.2.1 Sphinx==4.1.2 sphinx-book-theme==0.1.1 sphinx-rtd-theme==0.5.2 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 threadpoolctl==2.2.0 urllib3==1.26.3 It has been a week since I have been trying to figure out the issue but all in vain. Would appreciate a suggestion or hint on the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/68613682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++: Undefined behavior caused by...? int size = 0; int sorted[] = {}; int symbols[] = {8, 9, 13, 16, 16, 16, 17, 17, 17, 18, 18, 18, 20, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 44, 45, 46, 48, 48, 48, 49, 49, 49, 49, 50, 50, 50, 50, 51, 51, 51, 51, 52, 52, 52, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 57, 57, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 160, 161, 161, 162, 162, 163, 164, 164, 165, 186, 186, 186, 187, 187, 187, 188, 188, 188, 188, 189, 189, 189, 190}; int i = 0; while(symbols[i] != 190){ size++; if(symbols[i+1] == 190) { size++; } i++; } int indx = 0; for(int i = 0; i < size-1; i++) { if(symbols[i] != symbols[i+1]) { sorted[indx] = symbols[i]; indx++; } } I cannot locate the problem. What could cause undefined behavior? Size variable after the for loop becomes 27 (supposed to be 123), which I do not change. Got totally lost and cannot figure out where the problem stems from. A: int sorted[] = {} OK... so sorted is an array with no elements. Some compilers will warn about this: test.cpp(217) : error C2466: cannot allocate an array of constant size 0 But let's assume it works for your compiler and creates an array of constant size 0... Then what? Your code does this: sorted[indx] = symbols[i]; Hey! What's going on here... sorted doesn't have space to store anything. That write results in undefined behavior - it may crash, it may overwrite memory or it may cause your computer to add... one... hundred... billion... dollars to your bank account. A: int sorted[] = {} This creates an array with 0 elements. A: It is always a good idea to run your compiler in a more... restrictive mode than it runs by default, just to disable the most thoughtless compiler extensions. This applies to virtually all compilers out there. In your case int sorted[] = {}; is completely ill-formed C++ code, which is required to trigger diagnostic message. An there's a very good reason for that diagnostic message to be an error message specifically, not a mere warning. Strictly speaking, even though there are quite a few weird extensions compilers implement, I'm still surprised that there's one that allowed this declaration to slip through. What compiler is that? Just tried it myself and discovered that GCC actually accepts this. What were they thinking this time? What is it for? To support local declarations for "struct hack"-ed objects with a trailing array of zero size? Something else?
{ "language": "en", "url": "https://stackoverflow.com/questions/17004164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.Net MVC2: ModelState is invalid, but I don't know why I'm using MVC2 with data annotations for validation on my page. I require a name and a valid birth date to be present. I'm providing both, and I break into the date validator to ensure that the birth date is valid (and it is), but for some reason Model.IsValid is false in my post action. I'm not seeing anything in my ValidationSummary. How can I find out what is invalid in the ModelState? A: You need to iterate through the ModelState collection checking the ModelState.Errors collection count for each property is greater than 0. To get the collection of modelstate items in error, something like ModelState["Property"].Where(ms => ms.Errors.Count > 0) Kindness, Dan
{ "language": "en", "url": "https://stackoverflow.com/questions/2001408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: LazyVStack ScrollView Performance The performance of a LazyVStack in a ScrollView is bad even with simple views. Whereas scrolling with a VStack is buttery smooth, scrolling with a LazyVStack is really choppy. struct ContentView: View { var body: some View { ScrollView { // VStack { // uncomment this to see the difference LazyVStack { // ForEach(0..<1000, id: \.self) { Text(String($0)) } } } } } Any tips for improving this performance? (I can't use a List for other reasons, and I can't use a VStack for the bad initial load performance)
{ "language": "en", "url": "https://stackoverflow.com/questions/65636204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot embed image url in Play 2.6 reusable block In Play 2.5.9 , I could embed images in a reusable block. Since moving to Play 2.6.3 , the images cannot be displayed. See https://github.com/raychenon/play-table-of-contents/blob/master/app/views/thankyou.scala.html#L5 Any full image urls on https or http cannot be displayed. You can have a look at the app running here. The current version running is in this branch. I'm pretty sure I'm missing one key in the application.conf. Or any idea how to embed images in Play 2.6 ?
{ "language": "en", "url": "https://stackoverflow.com/questions/46547126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF: how do I use a include with a where statement? I have an Employee with an Employment and I want to get a list of all employees with a valid employment. The valid code in SQL would be SELECT * FROM dbo.Employees AS employee INNER JOIN dbo.Employment AS employment ON employee.ID = employment.Employee_ID AND employment.StartDate <= '2022-3-31' AND (employment.EndDate IS NULL OR employment.EndDate >= '2022-3-31') If I try something like this I C# I would expect to be able to use this var date = DateTime.Now context.employee.include(x => x.Employment.Where(y => y.Employment.StartDate <= date && ((x.Employment.Enddate ==null) || (x.Employment.Enddate >= date)) But this doesn't work. I have also tried to include Z.EntityFramework.Plus.EFCore and use the following code var date = DateTime.Now context.employee.includeFilter(x => x.Employment.Where(y => y.Employment.StartDate <= date && ((x.Employment.Enddate ==null) || (x.Employment.Enddate >= date)) But this does give me results but will include also the people without an employment Could somebody give me a hint how to fix this? Maurice A: Why don't you just do context.Employees.Include(x => x.Employment) .Where(x => x.Employments.Any(employment => employment.StartDate <= date && (employment.EndDate == null || employment.EndDate > date))); Given that a person can be employed multiple times in the same company....
{ "language": "en", "url": "https://stackoverflow.com/questions/71693378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting Error: formGroup expects a FormGroup instance. Please pass one in I am new to Angular 2 and unable to resolve this issue even after going through other stack overflow answers. I have just now started learning angular reactive forms and want to try the first example but am stuck. Please help. Here is the HTML form. <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <form [formGroup]="signupForm" (ngSubmit)="onSubmit()"> <div id="user-data"> <div class="form-group"> <label for="username">Username</label> <input type="text" id="username" formControlName="username" class="form-control"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" id="email" formControlName="email" class="form-control"> </div> <div class="radio" *ngFor="let gender of genders"> <label> <input type="radio" class="form-control" formControlName="gender" [value]="gender">{{ gender }} </label> </div> </div> <button class="btn btn-primary" type="submit">Submit</button> </form> </div> </div> </div> And this is the TS file. import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { genders = ['male', 'female']; // property to hold the form sigupForm: FormGroup; ngOnInit() { // initialize the form before rendering the template // hence 'OnInit' because this gets executed before the template is rendered// pass js object // {} tells this form doesn't has any 'controls' // 'controls' are key-value pairs to the overall form group this.sigupForm = new FormGroup({ // form controls // arg1 - intial state/value of this control // arg2 - single validator or an array of validators // arg3 - async validators 'username': new FormControl(null), 'email': new FormControl(null), 'gender': new FormControl('male') }); } onSubmit() { console.log(this.sigupForm); } } In the output, I can see Username and Email Field but no Gender field. Would you please help me out with fixing this? I am sure it would be a minor change only but still, I am unable to figure out. A: formGroup expects a FormGroup instance means that you did not create an instance for the FormGroup defined in your template which is signupForm so you have to create an instance for signupForm like this: this.signupForm = new FormGroup({ // form controls // arg1 - intial state/value of this control // arg2 - single validator or an array of validators // arg3 - async validators 'username': new FormControl(null), 'email': new FormControl(null), 'gender': new FormControl('male') }); A: Please double check your component code. What I noticed is that the variable you defined there is different to the one specified in your template. You should change the reference of sigupForm to signupForm instead. A: In my case, I was using Reactive Forms and loading the data for form asynchronously from a service. But, the form template will start getting generated parallelly. And at that time form would be undefined as it would be built only after the data from API call was received. So, first, check if the form is initialized, then only start generating the template. <form class="col-sm-12 form-content" *ngIf="form" [formGroup]="form">
{ "language": "en", "url": "https://stackoverflow.com/questions/48054863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Use item name stored in old for loop, inside a new for loop This program I'm working on is going to search through multiple paths (located in a JSON list) of a URL and find one that's not being used (404 page). The problem = I want to print what the path is when I come across a 404 (when I can find an error div). But I can't figure out a way to do so, since the item name seems unreachable. ### Libraries ### from bs4 import BeautifulSoup import grequests import requests import json import time ### User inputs ### namelist = input('Your namelist: ') print('---------------------------------------') result = input('Output file: ') print('---------------------------------------') ### Scrape ### names = json.loads(open(namelist + '.json').read()) reqs = (grequests.get('https://steamcommunity.com/id/' + name) for name in names) resp=grequests.imap(reqs, grequests.Pool(10)) for r in resp: soup = BeautifulSoup(r.text, 'lxml') findelement = soup.find_all('div', attrs={'class':"error_ctn"}) if (findelement): print(name) else: print('trying') A: I think you can do this by modifying where your for loop is located. I'm not familiar with the libraries you're using so I've left a comment where you might need to modify the code further, but something along these lines should work: names = json.loads(open(namelist + '.json').read()) for name in names: req = grequests.get('https://steamcommunity.com/id/' + name) # May need to modify this line since only passing one req, so are assured of only one response resp=grequests.imap(req, grequests.Pool(10)) # There should only be one response now. soup = BeautifulSoup(resp.text, 'lxml') findelement = soup.find_all('div', attrs={'class':"error_ctn"}) if (findelement): print(name) else: print('trying')
{ "language": "en", "url": "https://stackoverflow.com/questions/63421515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding Coefficients of LFSR I am studying cryptography from Cristof Paar's book. There is a question about LFSR's I have trouble with. I just can't understand one point here. Question is this: We want to perform an attack on another LFSR-based stream cipher. In order to process letters, each of the 26 uppercase letters and the numbers 0, 1, 2, 3, 4, 5 are represented by a 5-bit vector according to the following mapping: A -> 0 = 00000 . . . Z -> 25 = 11001 0 -> 26 = 11010 . . . 5 -> 31= 11111 (binary) We happen to know the following facts about the system: -The degree of the LFSR is m = 6. -Every message starts with the header WPI We observe now on the channel the following message (the fourth letter is a zero): j5a0edj2b *What are the feedback coefficients of the LFSR? (This one!) Solution: I can't understand the matrix in this solution where did these numbers come? A: Using WPI, we have plaintext begins with P=>(10110)(01111)(01000) Using j5a0edj2b we have the ciphertext C=>(01001)(11111)(00000)(11010)(00100)(00011)(01001)............ then by addition of P and C in mod 2, the key stream is S=>(11111)(10000)(01000).... we find the matrix from key stream s0=1,s1=1,s2=1,s3=1,s4=1,s5=1,s6=0,s7=0,s8=0,s9=0,s10=0,s11=1 etc For the matrix first line.... (s0,s1,s2,s3,s4,s5) second line....(s1,s2,s3,s4,s5,s6) third line.....(s2,s3,s4,s5,s6,s7) 4th (s3,s4,s5,s6,s7,s8) 5th (s4,s5,s6,s7,s8,s9) last line (s5,s6,s7,s8,s9,s10) this calulations are given in LFSRs in details
{ "language": "en", "url": "https://stackoverflow.com/questions/27207940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I implement HTML inline styling using variables in VBA? I am using VBA to generate a new Outlook Email. My code works as expected when assigning a hard coded table width, however I would like to assign width: 500px; to a variable and use the variable throughout the body of my email. How can I achieve this? I know we cannot use CSS with VBA as we're limited to a bare bones version of HTML via VBA / Outlook CODE Sub SendEmail 'shortened code Dim tblWidth as double tblWidth = 500 'i would like <td style = 'width:tblWidth px;... With EmailMessage .To = "john.smith@yahoo.com" '...other email properties listed here .HTMLBody = "<table><td style='width:500px; color:#4d4d4d; height=2px;'></td></table>" End With End Sub A: Try this simply .HTMLBody = "<table><td style='width:" & tblWidth & "px; color:#4d4d4d; height=2px;'></td></table>" A: To use a stylesheet instead: Just create one using a string and include it in your HTMLBody Dim sStyleSheet as String sStyleSheet = "<style> td {width:500px;} </style>" or to include your variable sStyleSheet = "<style> td {width:" & tblWidth & "px;} </style>" See how you are just building a string? Then include it in the HTML: sHTML = "<table><tr><td> Hello World </td></tr></table>" sStyleSheet = "<style> td {width:" & tblWidth & "px;} </style>" .HTMLBody = sStyleSheet & sHTML Make sense?
{ "language": "en", "url": "https://stackoverflow.com/questions/61114606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send HTTP error from http-proxy? Is it possible in http-proxy to do not forward requests to the server, but at once return a response with some error code, for example with 401 Unauthorized? I need analyze request body and in some cases do not forward requests to the server. is it possible to do at all? Or http-proxy can only modify request and response, but request always should be forwarded to the server? A: you can try doing it this way: const server = http.createServer((req, res) => { if(/*your auth check*/){ //return the 401 error } //auth check is passed, pass the request to the proxy proxy.web(req, res, { target: 'http://your.target' }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/44410963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }