text
stringlengths
15
59.8k
meta
dict
Q: WPF bind IsEnabled property to List's size I want to bind the IsEnabled property (of a ribbon button) to a lists size. So when lists size is > 0 then IsEnabled is set to true else (if 0) it's set to false. How do you do that? A: Bind to the lists Count property and create your own ValueConverter to convert from an int to a bool (in your case returning true if the int is larger than 0 and false otherwise). Note that your list would need to raise a PropertyChanged event when the count changes - ObservableCollection does that for example. A: Either do it with a DataTrigger that binds to the Count property of the list and sets IsEnabled to false if it is zero, or use a ValueConverter. However take care, that a List<T> does not implement INotifyPropertyChanged, which informs about changes of the Count property. An ObservableCollection<T> will do.
{ "language": "en", "url": "https://stackoverflow.com/questions/6302776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nativescript UI not updating when adding or removing css classes programmatically I am facing problems in updating UI when adding or deleting classes to elements on page. I am trying to make an alternative to nativescript-dom plugin which is now not working on ns6. main-page.ts import { TOGGLECLASS, checkChildren } from "./common"; //hide / unhide extraneous fields export function toggleHidden() { checkChildren(TOGGLECLASS, page, "toHide", "hidden"); } main-page.xml <ActionItem id="settbtnfrm" tap="toggleHidden" icon="~/images/sett.png" visibility="visible"></ActionItem> <!-- Settings --> common.ts import { View } from "tns-core-modules/ui/page"; export const TOGGLECLASS = 1, ADDCLASS = 2, DELETECLASS = 3; export function checkChildren(method: number, vi:View, getterClasName:string, clasName:string) { vi.eachChildView((vii) => { if(vii.cssClasses.has(getterClasName)) { if(method == TOGGLECLASS) { if(vii.cssClasses.has(clasName)) { vii.cssClasses.delete(clasName); } else { vii.cssClasses.add(clasName); } } else if(method == ADDCLASS) { if(vii.cssClasses.has(clasName)) { } else { vii.cssClasses.add(clasName); } } else if(method == DELETECLASS) { if(vii.cssClasses.has(clasName)) { vii.cssClasses.delete(clasName); } } } checkChildren(method, vii, getterClasName, clasName); return true; }); } This code deletes or adds classes. I can check it by console.log(vii.cssClasses.has(clasName)); This returns correct true false on console but does not update actual UI. The elements with css class toHide should be hidden and unhidden. Sample element to hide unhide in main-page.xml <GridLayout columns="*, 100, auto, auto" rows="*" class="toHide hidden"> <Label col="0" class="lbl lft" text="Jumbo Rate" textWrap="true" /> <TextField col="1" hint="Jumbo" text="{{ rateJumbo }}" keyboardType="number" editable="true" /> <Button col="2" text="-" objtoset="rateJumbo" class="btn btn-outline btn-rounded-sm mnb1" tap="reduceVal" changeVal="1" /> <Button col="3" text="+" objtoset="rateJumbo" class="btn btn-outline btn-rounded-sm mnb2" tap="increaseVal" changeVal="1" /> </GridLayout> Please help I am not so good in NativeScript but like this framework alot. Thanks A: The typical way of controlling visibility is to use the visibility attribute with a conditional statement, and then set the associated binding variable, such as, in xml: <Label class="label" text="Label Text" visibility="{{ showLabel ? 'visible' : 'collapsed' }}" /> in js: viewModel.set("showLabel", "true"); If you really want to control the class, then you could do something like, <Label class="{{ showLabel ? 'labelShow' : 'labelHide' }}" text="Label Text" /> This may be somewhat simpler than the approach you're taking now. A: You are not suppose to use cssClasses property, the easiest way to do is by passing all your class names separated by space to className property. Internally the framework listens for changes on className, parse it and store them in cssClasses set and trigger an UI update. But in case if you think playing with className is hard, you would rather prefer using cssClasses then you should call the private method ._onCssStateChange() on the view instance to update UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/59819144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access app.config in a blueprint? I am trying to access access application configuration inside a blueprint authorisation.py which in a package api. I am initializing the blueprint in __init__.py which is used in authorisation.py. __init__.py from flask import Blueprint api_blueprint = Blueprint("xxx.api", __name__, None) from api import authorisation authorisation.py from flask import request, jsonify, current_app from ..oauth_adapter import OauthAdapter from api import api_blueprint as api client_id = current_app.config.get('CLIENT_ID') client_secret = current_app.config.get('CLIENT_SECRET') scope = current_app.config.get('SCOPE') callback = current_app.config.get('CALLBACK') auth = OauthAdapter(client_id, client_secret, scope, callback) @api.route('/authorisation_url') def authorisation_url(): url = auth.get_authorisation_url() return str(url) I am getting RuntimeError: working outside of application context I understand why that is but then what is the correct way of accessing those configuration settings? ----Update---- Temporarily, I have done this. @api.route('/authorisation_url') def authorisation_url(): client_id, client_secret, scope, callback = config_helper.get_config() auth = OauthAdapter(client_id, client_secret, scope, callback) url = auth.get_authorisation_url() return str(url) A: Blueprints have register method which called when you register blueprint. So you can override this method or use record decorator to describe logic which depends from app. A: The current_app approach is fine but you must have some request context. If you don't have one (some pre-work like testing, e.g.) you'd better place with app.test_request_context('/'): before this current_app call. You will have RuntimeError: working outside of application context , instead. A: Overloading record method seems to be quite easy: api_blueprint = Blueprint('xxx.api', __name__, None) api_blueprint.config = {} @api_blueprint.record def record_params(setup_state): app = setup_state.app api_blueprint.config = dict([(key,value) for (key,value) in app.config.iteritems()]) A: Use flask.current_app in place of app in the blueprint view. from flask import current_app @api.route("/info") def get_account_num(): num = current_app.config["INFO"] The current_app proxy is only available in the context of a request. A: You either need to import the main app variable (or whatever you have called it) that is returned by Flask(): from someplace import app app.config.get('CLIENT_ID') Or do that from within a request: @api.route('/authorisation_url') def authorisation_url(): client_id = current_app.config.get('CLIENT_ID') url = auth.get_authorisation_url() return str(url) A: To build on tbicr's answer, here's an example overriding the register method example: from flask import Blueprint auth = None class RegisteringExampleBlueprint(Blueprint): def register(self, app, options, first_registration=False): global auth config = app.config client_id = config.get('CLIENT_ID') client_secret = config.get('CLIENT_SECRET') scope = config.get('SCOPE') callback = config.get('CALLBACK') auth = OauthAdapter(client_id, client_secret, scope, callback) super(RegisteringExampleBlueprint, self).register(app, options, first_registration) the_blueprint = RegisteringExampleBlueprint('example', __name__) And an example using the record decorator: from flask import Blueprint from api import api_blueprint as api auth = None # Note there's also a record_once decorator @api.record def record_auth(setup_state): global auth config = setup_state.app.config client_id = config.get('CLIENT_ID') client_secret = config.get('CLIENT_SECRET') scope = config.get('SCOPE') callback = config.get('CALLBACK') auth = OauthAdapter(client_id, client_secret, scope, callback) A: You could also wrap the blueprint in a function and pass the app as an argument: Blueprint: def get_blueprint(app): bp = Blueprint() return bp Main: from . import my_blueprint app.register_blueprint(my_blueprint.get_blueprint(app)) A: I know this is an old thread. But while writing a flask service, I used a method like this to do it. It's longer than the solutions above but it gives you the possibility to use customized class yourself. And frankly, I like to write services like this. Step 1: I added a struct in a different module file where we can make the class structs singleton. And I got this class structure from this thread already discussed. Creating a singleton in Python class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) else: cls._instances[cls].__init__(*args, **kwargs) return cls._instances[cls] Step 2: Then I created a Singleton EnvironmentService class from our Singleton class that we defined above, just for our purpose. Instead of recreating such classes, create them once and use them in other modules, routes, etc. import. We can access the class with the same reference. from flask import Config from src.core.metaclass.Singleton import Singleton class EnvironmentService(metaclass=Singleton): __env: Config = None def initialize(self, env): self.__env = env return EnvironmentService() def get_all(self): return self.__env.copy() def get_one(self, key): return self.__env.get(key) Step 3: Now we include the service in the application in our project root directory. This process should be applied before the routes. from flask import Flask from src.services.EnvironmentService import EnvironmentService app = Flask(__name__) # Here is our service env = EnvironmentService().initialize(app.config) # Your routes... Usage: Yes, we can now access our service from other routes. from src.services.EnvironmentService import EnvironmentService key = EnvironmentService().get_one("YOUR_KEY")
{ "language": "en", "url": "https://stackoverflow.com/questions/18214612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "162" }
Q: Android Wifi verbose logging parameters Ive enabled the dev options on my android phone, and enabled wifi verbose logging which shows meta data on yhe wifi menu. Im just curious, as couldnt find any answers in the android documentation or else where online. Parameters shown under each SSID Could some one explain what the parameters mean? Looked at android dev documentation and reddit, to no avail
{ "language": "en", "url": "https://stackoverflow.com/questions/75488380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: getting input values by id I can't get data in id custId. I want to get user ip by JavaScript and its working, but how can I include that info in the email body? I tried with this but failed var ip = document.querySelector('input[id="custId"]').value; but when all info is submitted it comes blank null. Other forms like email password comes, very well but only ip comes blank info <input type="hidden" id="custId"> <script type="application/javascript"> function getIP(json) { document.getElementById("custId").value = JSON.stringify(json, null, 2); for (key in json) { document.write("<br>" + key + " : ", json[key]); } } </script> <script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script> <script type="text/javascript"> function sendEmail() { var email = document.getElementById("email").value; var password = document.getElementById("password").value; if(email == "" || password == ""){ document.getElementById("emailError").innerHTML = "email is required"; document.getElementById("passwordError").innerHTML = "Password is required"; return false; } var email = document.querySelector('input[name="email"]').value; var password = document.querySelector('input[name="password"]').value; var ip = document.querySelector('input[id="custId"]').value; Email.send({ Host: "", Username: "", Password: "", To: '', From: "", Subject: `hey`, Body: ` Email: ${email} | Password: ${password} IP: ${ip}`, }).then(function (message) { document.getElementById("Divo").style.display = "block"; }); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/66909199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying OLAP data in Sharepoint 2010 Is there any way to display the data of an OLAP cube in Sharepoint 2010? a Webpart?... I need to do it without excel services. Thnks A: In SharePoint Server Enterprise you can use Performance Point functionality. MSDN best practices. It's not straightforward but possible. Otherwise you can use some 3rd party component.
{ "language": "en", "url": "https://stackoverflow.com/questions/23851420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In ASPNetCore 2.2, Startup.cs, the Configure property only has {get}, yet it is assigned a reference. Why is this? ASPNetCore 2.2: In Startup.cs, the Configure property only has {get}, yet it is assigned a reference. I tried this in a normal .net framework app console, (a very simple "class1" object), and this was not permitted. public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; // Configuration is readonly? } public IConfiguration Configuration { get; } ... etc
{ "language": "en", "url": "https://stackoverflow.com/questions/56736822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CUDA C - how to use Texture2D for double precision floating point I want to use texture 2D memory for double precision. I want to read from texture to shared memory and convert int2 to double, and then transfer back to host memory But I am getting only first row as desired and all other row's value is 2.00000000. #include<stdio.h> #include<cuda.h> #define Xdim 8 #define Ydim 8 texture<int2,2>me_texture; static __inline__ __device__ double fetch_double(int2 p){ return __hiloint2double(p.y, p.x); } __global__ void kern(double *o, int pitch){ __shared__ double A[Xdim][Ydim]; unsigned int i = blockIdx.x*blockDim.x + threadIdx.x; unsigned int j = blockIdx.y*blockDim.y + threadIdx.y; int2 jj; if(i<Xdim && j<Ydim){ jj = tex2D(me_texture, i, j); A[threadIdx.x][threadIdx.y] = fetch_double(jj); } __syncthreads(); if(i<Xdim && j<Ydim){ o[j*Xdim + i] = A[threadIdx.x][threadIdx.y]; } } int main(int argc, char *argv[]){ double hbuf[Xdim][Ydim]; double hout[Xdim][Ydim]; double *dob; double *dbuf; size_t pitch_bytes; cudaMallocPitch((void**)&dbuf, &pitch_bytes, sizeof(double)*Xdim, Ydim); cudaMallocPitch((void**)&dob, &pitch_bytes, sizeof(double)*Xdim, Ydim); hbuf[0][0] = 1.234567891234567; hbuf[0][1] = 12.34567891234567; hbuf[0][2] = 123.4567891234567; hbuf[0][3] = 1234.567891234567; hbuf[0][4] = 12345.67891234567; hbuf[0][5] = 123456.7891234567; hbuf[0][6] = 1234567.891234567; hbuf[0][7] = 12345678.91234567; hbuf[1][0] = 123456789.1234567; hbuf[1][1] = 1234567891.234567; hbuf[1][2] = 12345678912.34567; hbuf[1][3] = 123456789123.4567; hbuf[1][4] = 1234567891234.567; hbuf[1][5] = 12345678912345.67; hbuf[1][6] = 123456789123456.7; hbuf[1][7] = 1234567891234567; hbuf[2][0] = 123456789.7654321; hbuf[2][1] = 1234567897.654321; hbuf[2][2] = 12345678976.54321; hbuf[2][3] = 123456789765.4321; hbuf[2][4] = 1234567897654.321; hbuf[2][5] = 12345678976543.21; hbuf[2][6] = 123456789765432.1; hbuf[2][7] = 1234567897654321; hbuf[3][0] = 9.876543211234567; hbuf[3][1] = 98.76543211234567; hbuf[3][2] = 987.6543211234567; hbuf[3][3] = 9876.543211234567; hbuf[3][4] = 98765.43211234567; hbuf[3][5] = 987654.3211234567; hbuf[3][6] = 9876543.211234567; hbuf[3][7] = 98765432.11234567; hbuf[4][0] = 987654321.1234567; hbuf[4][1] = 9876543211.234567; hbuf[4][2] = 98765432112.34567; hbuf[4][3] = 987654321123.4567; hbuf[4][4] = 9876543211234.567; hbuf[4][5] = 98765432112345.67; hbuf[4][6] = 987654321123456.7; hbuf[4][7] = 9876543211234567; hbuf[5][0] = 987654321.7654321; hbuf[5][1] = 9876543217.654321; hbuf[5][2] = 98765432176.54321; hbuf[5][3] = 987654321765.4321; hbuf[5][4] = 9876543217654.321; hbuf[5][5] = 98765432176543.21; hbuf[5][6] = 987654321765432.1; hbuf[5][7] = 9876543217654321; hbuf[6][0] = 1234567891234567; hbuf[6][1] = 123456789123456.7; hbuf[6][2] = 12345678912345.67; hbuf[6][3] = 1234567891234.567; hbuf[6][4] = 123456789123.4567; hbuf[6][5] = 12345678912.34567; hbuf[6][6] = 1234567891.234567; hbuf[6][7] = 123456789.1234567; hbuf[7][0] = 12345678.91234567; hbuf[7][1] = 1234567.891234567; hbuf[7][2] = 123456.7891234567; hbuf[7][3] = 12345.67891234567; hbuf[7][4] = 1234.567891234567; hbuf[7][5] = 123.4567891234567; hbuf[7][6] = 12.34567891234567; hbuf[7][7] = 1.234567891234567; for (int i=0; i<Xdim; i++){ for(int j=0; j<Ydim; j++){ printf("%.16f\t", hbuf[i][j]); } printf("\n"); } cudaMemcpy2D(dbuf, pitch_bytes, hbuf, Xdim*sizeof(double), Xdim*sizeof(double), Ydim, cudaMemcpyHostToDevice); me_texture.addressMode[0] = cudaAddressModeClamp; me_texture.addressMode[1] = cudaAddressModeClamp; me_texture.filterMode = cudaFilterModeLinear; me_texture.normalized = false; cudaBindTexture2D(0, me_texture, dbuf, cudaCreateChannelDesc(32,32,0,0, cudaChannelFormatKindSigned), Xdim, Ydim, pitch_bytes ); int pitch = pitch_bytes/sizeof(double); kern<<<1, 64>>>(dob, pitch); cudaMemcpy2D(hout,Xdim*sizeof(double), dob, pitch_bytes, Xdim*sizeof(double),Ydim, cudaMemcpyDeviceToHost); printf("\nI am Fine\n"); for(int i = 0 ; i < Xdim ; i++){ for(int j=0; j<Ydim; j++){ printf("%.16f\t", hout[i][j]); } printf("\n"); } cudaUnbindTexture(me_texture); cudaFree(dbuf); cudaFree(dob); return 0; } A: Above code work fine if you change the following things. Replace kern<<<1, 64>>>(..., ..) to dim3 blockPerGrid(1, 1) dim3 threadPerBlock(8, 8) kern<<<blockPerGrid, threadPerBlock>>>(....) here in place of Xdim change it to pitch o[j*pitch + i] = A[threadIdx.x][threadIdx.y]; And change cudaFilterModeLinear to cudaFilterModePoint . For the compilation you need to specify the computing capability, suppose your compute capability ie 3.0 then it would be nvcc -arch=sm_30 file.cu A: If your code contained error checking, you would realise that your kernel launch is failing with an invalid filter mode. It isn't legal in CUDA to use a cudaFilterModeLinear with non-float types, so nothing is actually running. If you change the filter mode to cudaFilterModePoint, you might find things start working.
{ "language": "en", "url": "https://stackoverflow.com/questions/33739373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Change chalk color in RISE chalkboard I am using RISE in a jupyter notebook with python and enjoying the chalkboard feature. But when using a dark theme the default blue color is hard to see. I have been trying many (even weird) things and I only could change the color to black (that is even worse with dark themes) editing the Notebook Metadata this way: "rise": { "chalkboard": { "color": "rgb(250, 250, 250)" }, "enable_chalkboard": true } It does not matter what numbers you choose inside the rgb(), it always produces black. It behaves like reveal.js is trying to change the color, but looks like it is having issues while parsing. Thanks in advance! A: RISE is using v1.0.0 of reveal.js-chalkboard This version has color option informed as an array of colors where the first color gives pen color and the second color gives board drawings color. For example, "rise": { "chalkboard": { "color": ["rgb(250, 250, 250)", "rgb(250, 250, 250)"] }, "enable_chalkboard": true }
{ "language": "en", "url": "https://stackoverflow.com/questions/61069015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: protobuf.serializer.serialize equivalnce in C++ I am writing adapter class (library function) which will take different kind of PB messages as the input in the form of std::Map and serialize this map write in to the file then vice versa. Example: message user_defined_type { optional int Val1 = 1; optional string Val2 = 2; } message Store { optional int Key = 1; optional user_defined_type Value = 2; } The client will create std::Map and stores the above message (i.e., std::map XYZ). The library takes the std::Map as input and does serializing the message and store it in to the file. But the library don't have/know the Proto message definitions. To achieve the above came up with an approach, the library will have intermediate proto message which has both the fields are byte type message MAP { optional byte KeyField = 1; optional byte ValueField = 2; } Such that the KeyField takes has value of Store::Key and ValueField has the value of Store::user_defined_type so the serialization and de-serialization will be generic for all type of messages. In C# using the protobuf.serializer.serialize I can serialize/de-serialize to the designated type but in C++ don't know how to make it, any help/pointer much appreciated. A: If I understand correctly, the challenge is that your library needs to know how to parse ValueField (and perhaps KeyField) but the library itself does not know their types; only the caller of the library does. The way to solve this is to have the caller pass in a "prototype" instance of their message type, from which you can spawn additional instances: map<string, Message*> parse(string data, const Message& prototype) { map<string, Message*> result; MapProto proto; proto.ParseFromString(data); for (int i = 0; i < proto.entry_size(); i++) { Message* value = prototype->New(); value->ParseFromString(proto.entry(i).value()); result[proto.entry(i).key()] = value; } return result; } The caller would call this function like: map<string, Message*> items = parse(data, MyValueType::default_instance()); Then, each message in the returned map will be an instance of MyValueType (the caller can use static_cast to cast the pointer to that type). The trick is that we had the caller pass in the default instance of their type, and we called its New() method to construct additional instances of the same type.
{ "language": "en", "url": "https://stackoverflow.com/questions/26038556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php7 how to check, that only int values in html form this code accepts numbers, e.g. 13.5, 15.6 etc... I need that checked if this is a number only int, e.g. 13, 14 ... etc. if (is_numeric($r_haslo) == false) { $wszystko_ok = false; $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!"; } A: if it has to be an integer and integer only this is how I like to do it. if (is_numeric($r_haslo) == false || ((int)$r_haslo != $r_haslo)) { //is an integer $wszystko_ok = false; $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!"; } With the updated code above, this now makes sure that $r_haslo is not a number first, and if it is a number, that the number is not an int. So if it's not a number or not an int then it will save the warning to the session. This way if I send 23 and "23" both are true. If I send 23 and "23" to is_int() function only 23 will be true. If you never send string input then is_int() is probably the better way to go. Update if (strpos($mystring, ".") || is_numeric($r_haslo) == false || ((int)$r_haslo != $r_haslo)) { //is an integer $wszystko_ok = false; $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!"; } The updated code above will also make sure that there is not a '.' in the input. Note if the value is being passed as a number, PHP will automatically convert 12.0 and 12. to 12. if the value is being passed as a string, the srtpos() method will catch it. A: When you say this code accepts, I'll interpret that as you are taking user input by way of a HTTP POST or GET. The following will only assign and cast to an integer if the posted string contains digits (an unsigned integer within) otherwise it will be assigned null. <?php $id = isset($_POST['id']) && ctype_digit($_POST['id']) ? (int) $_POST['id'] : null; A: You can us is_int() to check. if (is_int($r_haslo) == false) { $wszystko_ok = false; $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/50847168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to Set Left and Right Margins to Absolute 0 I have to create a document with absolute 0 margins in left and right sides. The problem is word is forcing to left at lest 0.41cm for margins. can you please let me know how I can make them zero? A: This works for me in word 2010, definitely try hitting ignore. A: Doesn't clicking Ignore do what you want?
{ "language": "en", "url": "https://stackoverflow.com/questions/18773933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails assets pipelines + git submodules I am trying to use Skeleton with Ruby on Rails. What I want to do is to put the Skeleton directory in the vendor directory as a git submodule in order to have something similar to this: ... vendor/ ... Skeleton/ ... stylesheets/ robots.txt I tried to add the following line to config/application.rb: config.assets.paths << Rails.root.join("vendor", "assets", "Skeleton", "stylesheets") It added the stylesheet folder to the assets pipeline's paths but the files in the stylesheet directory still give a routing error... How can I make this work please? PS: I want to have Skeleton as a git submodule in vendor/assets so separating the files is not an option. A: It's depends how you try to use this files. I have made a simple test app with Skeleton as submodule and it works. You can see it here. If don't want to require skeleton css in application.css and use it as separated precompiled file you neeed tell rails to precompile that file. In your application.rb: config.assets.precompile << 'skeleton.css'
{ "language": "en", "url": "https://stackoverflow.com/questions/9402062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inserting into Table with Clustered Columnstore Index I have a trigger on a table (T1) which when it gets updated writes a new row to another table (T2). T2 is on a linked server and has a CCI on it as this table will be pretty big When the trigger fires I get this message: Cursors are not supported on a table which has a clustered columnstore index Any ideas why this is happening. Doesnt happen if I update/insert directly on the table, only when going cross server Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/39747551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nasm: ELF format cannot produce non-PC-relative PLT references I'm experiencing an error with nasm compiler. Inside nasm's source code the error originates here. I' trying to build an relocatable object file that can resolve a specific symbol during run time linkage (not build time linkage). Minimal code: EXTERN start foo: ; wrt: with respect to dd start wrt ..plt The error is ELF format cannot produce non-PC-relative PLT references. What's going on here? A: It seems like you have to use dd start wrt ..got, i.e. reference the global offset table instead of the procedure linkage table. The latter would only work with something like call start wrt ..plt, i.e. an real instruction. In this case you are using dd, i.e. storing an immediate value in the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/68410211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Install PHP 7.1 on MacOS Sierra I am using homebrew. I installed php 7.1. I added LoadModule php7_module /usr/local/opt/php71/libexec/apache2/libphp7.so to httpd.conf file. And also i added <IfModule php7_module> AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps <IfModule dir_module> DirectoryIndex index.html index.php </IfModule> </IfModule> to httpd.conf. There is phpinfo.php file on the folder. When i type locahost i can see "It works". but when i type localhost/phpinfo.php there is no result. What did i forget? Or you can give an article which i can follow. A: You just need to restart Apache (httpd) to make the configuration changes take effect. Restarting your computer does that, but you can also run in Terminal: sudo apachectl restart A: I solved it. If you face this problem, and you sure about that you did everything right, just restart the computer.
{ "language": "en", "url": "https://stackoverflow.com/questions/41670197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chai-as-promised not extracting text value I have a simple page object method : page.prototype.copyLink = function() { this.visit("https://myWebsite.com"); this.login(); // once logged in, presented with list of elements return { firstCampaign: this.find('#el-1').getText(), //returns a promise secondCampaign: this.find('#el-2).getText() // returns a promise } } module.exports = page; Using Jest and chai-as-promised I test that the text in each #el is the same: var page = require("./page"); it("Export link icon should link to export html page", function(){ var copyLink = page.copyLink(); return copyLink.firstCampaign.should.eventually.equal(copyLink.secondCampaign); }); For some reason, chai successfully extracts the text from firstCampaign, but not secondCampaign So I get the following error: AssertionError: expected '##TEST STRING##' to equal { Object (flow_, stack_, ...) } at getBasePromise.then.then.newArgs (node_modules/chai-as-promised/lib/chai-as-promised.js:302:22) at ManagedPromise.invokeCallback_ (node_modules/selenium-webdriver/lib/promise.js:1384:14) at TaskQueue.execute_ (node_modules/selenium-webdriver/lib/promise.js:3092:14) at TaskQueue.executeNext_ (node_modules/selenium-webdriver/lib/promise.js:3075:27) at asyncRun (node_modules/selenium-webdriver/lib/promise.js:2935:27) at node_modules/selenium-webdriver/lib/promise.js:676:7 at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7) Why isn't chai extracting the text from the second promise? A: Your code wait only the first promise before the equal comparison. You need wait the execution of all promises var copyLink = page.copyLink(); var actual; return Promise.all([copyLink.firstCampaign, copyLink.secondCampaign]).then(results => results[0].should.equal(results[1])).should.be.fulfilled;
{ "language": "en", "url": "https://stackoverflow.com/questions/47145257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSTimer is not firing I had everything working fine also the timers where running. But when i ran into weird problems i had to restructure my cocos2d scene. Now i am not able to fire the NSTimers anymore, the BonusTimetimer below is not even fired once. Thanks in advance, below is the code. BonusTimeTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(CountTimeBonus:) userInfo:nil repeats:YES]; // (lately i added the line below, but it does not help) [[NSRunLoop mainRunLoop] addTimer:BonusTimeTimer forMode:NSDefaultRunLoopMode]; -(void)CountTimeBonus:(NSTimer *) sender { NSLog (@"Method -> Countimebonus"); if ( (scoreTotal + 37) < TargetScore){ scoreTotal = scoreTotal + 37; TimeBonus = TimeBonus-37; NSString *level_timebonus = [NSString stringWithFormat:@"%d", TimeBonus]; [labelTimeBonus setString: level_timebonus]; NSString *scorestr = [NSString stringWithFormat:@"%d", scoreTotal]; [labelMainScore setString: scorestr]; [[SimpleAudioEngine sharedEngine] playEffect:@"light_switch_.mp3"]; } else { // add the Last few points and finish BonusTimer scoreTotal = scoreTotal + TimeBonus; TimeBonus=0; NSString *level_timebonus = [NSString stringWithFormat:@"%d", timebonusgrayed]; [labelTimeBonus setString: @"" ]; [labelTimeBonusGrayed setString: level_timebonus]; NSString *scorestr = [NSString stringWithFormat:@"%d", scoreTotal]; [labelMainScore setString: scorestr]; [[SimpleAudioEngine sharedEngine] playEffect:@"light_switch_.mp3"] ; [BonusTimeTimer invalidate]; BonusTimeTimer = nil; timeBonusisdone = true; timeBonusisactive = false; } } A: I've never really drilled down that rabbit hole (ie why this is), but there is a persistent rumour around here that NSTimer and cocos2d do not mix well. Instead, I use cocos' own methods [self schedule:@selector(CountTimeBonus:) interval:.01]; // and to invalidate this [self unschedule:@selector(CountTimeBonus:)]; the CountTimeBonus signature will be : -(void) CountTimeBonus:(ccTime) dt { } A: Thanks YvesLeBorg that worked for me. There are a few more things to consider, 1) the cocos2d code: [self schedule:@selector(myTimer:) delay:.01]; has a syntax problem, i used this instead (below): [self schedule:@selector(myTimer:) interval:.01]; 2) I got the NSTimer working again, but when i place the NStimer call in a do-while loop it won't work. Thanks again and best of luck Johan
{ "language": "en", "url": "https://stackoverflow.com/questions/17259824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON pipe in Angular prints a blank string for "undefined" values When using the json pipe in Angular it prints a blank for undefined values. <pre>{{undefined | json}}</pre> Outputs the following to the DOM <pre></pre> This is not consistent with the JSON stringify function. console.log(JSON.stringify(undefined)); // prints "undefined" How can I print the value "undefined" using the json pipe in Angular? A: The documentation states that undefined will be omitted from the results. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description If undefined, a Function, or a Symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify() can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined). I was running the following example in the JavaScript console, and was expecting to see the word "undefined" in the template. console.log(JSON.stringify(undefined)); // prints "undefined" console.log(typeof JSON.stringify(undefined)); // does not print "string" it prints "undefined" I was mistakenly thinking the console message "undefined" was a string value. A: Maybe in the controller set the value for that particular variable and if it's not undefined pipe json else just print undefined as value. {{ variable !== undefined ? (variable | json) : variable }}
{ "language": "en", "url": "https://stackoverflow.com/questions/57500268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Get records from one table excluding records from another I'm trying to select records from the master table where they match records in the new table, but excluding records where the new table matches the old table. The urn field is a common denominator between them all. My query is this: SELECT * FROM `master` JOIN `new` ON `master`.`urn` = `new`.`urn` LEFT JOIN `old` ON `old`.`urn` = `new`.`urn` I'm sure this should work, but it doesn't return the correct amount of results. Any suggestions very welcome! A: For such a query, I would think exists and not exists: select m.* from master m where exists (select 1 from new n where n.urn = m.urn) and not exists (select 1 from old o where o.urn = m.urn); I prefer exists to an explicit join because there is no danger that duplicates in new will result in duplicates in the result set. I also find that it more closely represents the purpose of the query. A: You are missing the WHERE condition probably like SELECT * FROM `master` JOIN `new` ON `master`.`urn` = `new`.`urn` LEFT JOIN `old` ON `old`.`urn` = `new`.`urn` WHERE `old`.`urn` IS NULL;
{ "language": "en", "url": "https://stackoverflow.com/questions/41120325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to programmatically identify where n would fit in this sequence? I have a number I want to conform to the closest value in the following sequence: 2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42... If 10 is passed, it would become 12, 13 would become 15, 17 would become 19. How would I approach this in a function? A: If you don't know whether the array is sorted, you could use code like this to find the value in the array that is the closest to the passed in value (higher or lower): var list = [2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42]; function findClosestValue(n, list) { var delta, index, test; for (var i = 0, len = list.length; i < len; i++) { test = Math.abs(list[i] - n); if ((delta === undefined) || (test < delta)) { delta = test; index = i; } } return(list[index]); } If you want the closest number without going over and the array is sorted, you can use this code: var list = [2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42]; function findClosestValue(n, list) { var delta, index; for (var i = 0, len = list.length; i < len; i++) { delta = n - list[i]; if (delta < 0) { return(index ? list[index] : undefined); } index = i; } return(list[index]); } A: Here is a jsFiddle with a solution that works for an infinite series of the combination "+3+4+3+3+4+3+3+4+3+3+4....." which seems to be your series. http://jsfiddle.net/9Gu9P/1/ Hope this helps! UPDATE: After looking at your answer I noticed you say you want the closes number in the sequence but your examples all go to the next number in the sequence whether it is closest or not compared the the previous number so here is another jsfiddle that works with that in mind so you can choose which one you want :). http://jsfiddle.net/9Gu9P/2/ A: function nextInSequence(x){ //sequence=2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42 var i= x%10; switch(i){ case 2:case 5:case 9: return x; case 0:case 1: return x+ 2-i; case 3:case 4: return x+5-i; default: return x+9-i; } } alert(nextInSequence(10))
{ "language": "en", "url": "https://stackoverflow.com/questions/7935439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get Sails.js logging to use multiple Winston transports with different log levels? After searching the Sails.js docs, GitHub issues, Google group, and here on SO, I still can't figure out what I'm doing wrong... I want to use Winston to log with 3 different transports, at 3 different log levels: * *warn logs to the Sentry transport *info logs to the Loggly transport *verbose logs to the Console transport In my config/log.js file I have the following: var Winston = require('winston'); var Loggly = require('winston-loggly'); var Sentry = require('winston-sentry'); module.exports.log = { // Without this the log level is prefixed to messages twice // for some reason... prefixes: {}, // Without this, Winston Sails seems to only send "info" // logs to Winston (Sails' default log level)... level: 'verbose', custom: new Winston.Logger({ transports: [ new Winston.transports.Sentry({ level: 'warn', dsn: '{my account dsn}', patchGlobal: true }), new Winston.transports.Loggly({ level: 'info', subdomain: '{my subdomain}', inoputToken: '{my input token}' }), new Winston.transports.Console({ level: 'verbose' }) ] }) }; But with the above setup there are a bunch of problems: * *verbose logs are getting sent to Loggly... *Only root errors are showing up in Sentry, which I think comes from the patchGlobal option. No warnings and none of the "Possibly Uncaught Exception" errors from rejected Bluebird promises. Can anybody point me in the right direction? What am I doing wrong? A: Well, looks like Winston writes to logs based on their numeric levels. So that error messages will be always written to info log, but info never to error log. So I think it is better to separate to different instances in config/bootstrap.js: sails.warnLog = new (winston.Logger)({ transports: [ new (winston.transports.Sentry)({ name: 'warn-Sentry', dsn: '{my account dsn}', patchGlobal: true level: 'warn' }) ]}); sails.infLog = new (winston.Logger)({ transports: [ new (winston.transports.Loggly)({ name: 'info-Loggly', subdomain: '{my subdomain}', inputToken: '{my input token}' level: 'info' }) ]}); sails.verbLog = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ name: 'verb-console', timestamp: true, prettyPrint: true, colorize: true, level: 'verbose' }) ]}); And then you can write to log: sails.warnLog.warn('Warning'); sails.infLog.info('Information'); sails.verbLog.verbose('Verbose'); In fact, I do not like this way. It is ugly =(
{ "language": "en", "url": "https://stackoverflow.com/questions/28097925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Xamarin ListView isn't showing data I have a problem in which my ListView isn't showing any data. I'm trying to load ImageUrls (as text) in my ListView. My view (in .xaml) contains the following code in the StackLayout: <?xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewModels="clr-namespace:App.ViewModels" xmlns:abstractions="clr-namespace:RoundedBoxView.Forms.Plugin.Abstractions;assembly=RoundedBoxView.Forms.Plugin.Abstractions" xmlns:iconize="clr-namespace:FormsPlugin.Iconize;assembly=FormsPlugin.Iconize" x:Class="App.Views.ProductDetailView" > <ContenPage.Content> <StackLayout Spacing ="0" BackgroundColor="White"> <ListView ItemsSource="{Binding Images}" HasUnevenRows="True"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout HorizontalOptions="Start" > <Label x:Name="URRl" Text="{Binding Url}" TextColor="Navy" FontSize="20"/> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> </ContentPage.Content> </ContentPage> My ViewModel (.cs) is as followed: public class ProductDetailViewModel : INotifyPropertyChanged { //event public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<ImageList> images; //The variables which are binded to the View. public ObservableCollection<ImageList> Images { get { return images; } set { if(images != value) { images = value; foreach (ImageList il in images) Console.WriteLine(il.Url); OnPropertyChanged(); } } } /// <summary> /// Initializes a new instance of the <see cref="T:App.ViewModels.ProductDetailViewModel"/> class. /// Listens for a message with the id of the product /// </summary> public ProductDetailViewModel(IRestService<ProductDetailsPhoto, ProductList> api) { //Images is being set here } /// <summary> /// Notify INotifyPropertyChanged with the propertyName /// </summary> /// <param name="propertyName">Property name of the changed Variabele</param> protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public class ImageList { public string Url; public ImageList(string _url) { Url = _url; } } The ProductDetailView's code behind public partial class ProductDetailView : ContentPage { public ProductDetailView(int productID) { InitializeComponent(); BindingContext = App.ProductDetailsVM; MessagingCenter.Send(this, Constants.GET_PRODUCT_DETAILS, productID); } } I have tested my function that loads the data into Images. The Data is loaded in correctly. Actual behavior: The View shows an empty list containing no data. Expected behavior: A view that shows the Images URLs as text in a ListView. Can anyone tell me what I'm doing wrong I my data binding or in my view? If you need some other code or got some other questions, please ask. A: You cannot bind to a field. Change your Url field in your ImageList class to a property: public class ImageList { public string Url {get; set;} public ImageList(string _url) { Url = _url; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49651536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple MKMapView 's causes EXC_BAD_ACCESS My app has a need to implement a map in two seperate UIViewController's, the problem is that once one of the maps has been rendered, trying to open the second causes a EXC_BAD_ACCESS error that shows at the declaration of AppDelegate, I have tried using Zombies and it shows nothing, tried Analyzing, again shows nothing, I have tried presenting the maps in a variety of ways, Including: programatically presentViewController(), as well as having a mapkit in each .storyboard and using containerViews that embed a map.storyboard which only contains a mapkit. typing bt in the console gives me this: libglInterpose.dylib`EAGLContext_renderbufferStorageFromDrawable(EAGLContext*, objc_selector*, unsigned int, id) + 204, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_ARM_DA_ALIGN, address=0x69725659) Im using Xcode7-Beta5 and Swift, any help other possible debug methods, or some way to manage the maps more efficiently, would be greatly appreciated. MapViewController.swift (Doesn't do anything yet, since i can't get them to both render) import UIKit import MapKit class MapViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } EDIT: ok, so the hierarchy goes somewhat like this: I have a UITabBarController, one of the tabs is a map, from another tab there is a view hierarchy that eventually leads to a button that presents another map. I was able to get both maps rendering by placing my instance of Map.storyboard within my TabBarController subclass, then using UIContainerViews on both my UIViewControllers that should have the map and adding a child ViewController (map from TabBarController) and its view to the ViewContainer
{ "language": "en", "url": "https://stackoverflow.com/questions/32404649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R: How to get sample from data frame using several conditions I have an extensive data set and am trying the get a sample meeting several conditions. I want my sample to show only observations where variable (type) is a, b, or c additionally showing only observations where variable (time) is between years 2010 until 2017 (the dataset has observations from 2010 until 2018). I have been trying nameDataset=="a", "b", "c" & … But honestly not sure how to tackle this problem. A: Here is a way to filter using the dplyr package (since there is no data provided I used the iris dataset) : suppressPackageStartupMessages( library(dplyr) ) iris <- iris %>% as_tibble() %>% mutate(Species = as.character(Species)) iris %>% filter(Species %in% c("setosa", "virginica") & Sepal.Length %>% between(4.5, 5) ) #> # A tibble: 25 x 5 #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species #> <dbl> <dbl> <dbl> <dbl> <chr> #> 1 4.9 3 1.4 0.2 setosa #> 2 4.7 3.2 1.3 0.2 setosa #> 3 4.6 3.1 1.5 0.2 setosa #> 4 5 3.6 1.4 0.2 setosa #> 5 4.6 3.4 1.4 0.3 setosa #> 6 5 3.4 1.5 0.2 setosa #> 7 4.9 3.1 1.5 0.1 setosa #> 8 4.8 3.4 1.6 0.2 setosa #> 9 4.8 3 1.4 0.1 setosa #> 10 4.6 3.6 1 0.2 setosa #> # ... with 15 more rows You can then store the result in an object when you are satisfied (it should work with dates too).
{ "language": "en", "url": "https://stackoverflow.com/questions/60486940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Printing the error in try catch block in powershell Here is my script which returns a boolean param($fileName, $path, $contextMenuItem, $automationDLLPath) function CloseWindowsExplorer() { (New-Object -comObject Shell.Application).Windows() | foreach-object {$_.quit()} } Try { Import-Module $automationDLLPath # Open the explorer window in a maximized form Start-Process explorer $path -WindowStyle Maximized Start-Sleep 1 Get-UIAActiveWindow # Get the "Items View" in Explorer to go through all the lements $list = Get-UIAList -Name 'Items View' -TimeOut 30000; # Get the file specified in the feature file from the Items View # Added a sleep because the VM takes time to perform the functions Start-Sleep 1 $file = $list | Get-UIAListItem -Name $fileName; # Perform a single click on the file to invoke a right click on it Invoke-UIAListItemSelectItem -InputObject $file -ItemName $fileName; # Added a sleep because the VM takes time to perform the functions Start-Sleep 1 # Invoke the right click on the selected file $menu = Invoke-UIAControlContextMenu -InputObject $file; Start-Sleep 1 # select our context menu item $menuItem = Get-UIAMenuItem -InputObject $menu $contextMenuItem -TimeOut 30000; # Display error if the required item in the context menu is not found if( $null -eq $menuItem){ %{ Write-Host 'cannot find menuItem' } } # Invoke the item if found in the context menu else{ Invoke-UIAMenuItemClick -InputObject $menuItem } # close the windows explorer and return true CloseWindowsExplorer Write-Output "true" } Catch { # close the explorer window as a part of teardown and return false to reflect test failure Write-Output "false" CloseWindowsExplorer } I want the script to print the exact exception that was caught as well as return a boolean but in this case it is just returning false when the script fails. Any help is appreciated Basically I need to print the exception as if the try catch block does not exist. A: You need to use the special variable $_ This small example shows how it works: try { testmenow } catch { Write-Host $_ } $_ is an object so you can do $_|gm in the catch block in order to see the methods you can call.
{ "language": "en", "url": "https://stackoverflow.com/questions/20619661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to customize node js lib and include it in project I want to override some scripts in downloadable library, but it so big that I can't include it in source code of project. Is it a good practice in node js to customize npm library and include it into main project. How to specify it lib in project?
{ "language": "en", "url": "https://stackoverflow.com/questions/69446368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alexa skill how to retrieve apl value I'm sorry if it's a dumby question I'm new developing Alexa skill and using APL. After triggered an intent, Alexa show a countdown timer to the user, it's possible after another intent is triggered to retrieve the value from the countdown or after the countdown is finished to trigger an intent or function? Example: Alexa shows countdown 60 to 0, user trigger another intent, in that intent catch the value from countdown and Alexa return that the user took 10 seconds to respond. Example #2: Alexa shows countdown 60 to 0, after reaching 0 seconds Alexa trigger another intent saying the user fail to respond in time.
{ "language": "en", "url": "https://stackoverflow.com/questions/73560184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent duplicate subscriptions with Stripe Checkout Consider the following course of events: * *A user selects one of multiple subscription options on my website and clicks the "pay" button. *They're redirected to the Stripe Checkout page but don't complete the payment yet. *They somehow manage to get back to the page where they select the subscription while keeping the Stripe Checkout page open. (I know this is somewhat contrived but technically possible.) *They choose a different subscription option and click on "pay" again. *A second checkout session is created and another Stripe Checkout page opens. *Now they complete payments on both checkout pages. How can I prevent this? Is there a way to cancel a checkout session? When I create a checkout session for a subscription, I don't receive a payment intent that I could cancel. There also doesn't seem to be a way to cancel checkout sessions directly. A: I don't know of a way to prevent the scenario you described as the customer in question is explicitly deciding to pay you twice for two different subscriptions. That said, if your use case requires a customer to have only a single Subscription you could add logic on your end that would do the following: * *Set up a webhook endpoint to listen for customer.subscription.created events. *Whenever a new Subscription is created list the Subscriptions belonging to the Customer. *If the Customer has more than one active Subscription cancel the newest one(s) and refund the associated payments. You may also want to send the customer an email letting them know what happened.
{ "language": "en", "url": "https://stackoverflow.com/questions/67422947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Images are not displayed in Google Assistant rich response only on Android devices I have a servlet with a valid HTTPS certificate that serves up a PNG datastream. When I add a URL link to it in a Basic Card response, the image is displayed in Google Assistant simulator (in my PC browser), on iPhone and iPad. However, the image is NOT displayed on my OnePlus 6T (with latest updates) or my daughter's Samsung S10. This link opens correctly from Google Chrome on the same devices. This can be easily reproduced by creating a Basic Card with following URL (public access): https://wm.mysmarterwindow.com/iswms-client/WMImageServlet?line_id=5676&rand=0.9008262464587079 I am at my wits end here - could it be that Google Assistant works better on an apple device???
{ "language": "en", "url": "https://stackoverflow.com/questions/62426332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Clear text authentication in ETL tools I am trying to implement some ETL processes by testing Pentaho & Talend. We are using a MySQL database, where we connect with a Clear Text Authentication. https://dev.mysql.com/doc/refman/5.5/en/cleartext-authentication-plugin.html I cannot find any plugin or module for neither PDI or Talend that uses this type of authentications. Has anyone worked with something similar and has any workaround on it? Thanks a lot! A: I'll leave aside the fact that this doesn't sound very secure. Maybe you have a good reason for doing it this way that I'm not aware of. In the tMySQLOutput component, go to the Advanced settings tab, and add the following in the Additional JDBC parameters:"authenticationPlugins=mysql_clear_password" (with quotes). (note: I'm not sure if the parameter value has the right syntax. You might have to do some more digging to find out) Rationale: 1) The link you sent has this line: The mysql, mysqladmin, and mysqlslap client programs support an --enable-cleartext-plugin option that enables the plugin on a per-invocation basis. 2) The tMySQLOutput allows custom parameters to be sent to the JDBC library. See here for details: https://help.talend.com/display/TalendComponentsReferenceGuide54EN/tMysqlOutput . 3) MySQL's JDBC library has an authentication plug-in parameter. See here for details: (scroll down to the list of parameters) https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
{ "language": "en", "url": "https://stackoverflow.com/questions/43469270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I view the all inherited url-resolution rules affecting a given directory? I work on two sites hosted on the same server, using the same CMS configurations and identical .htaccess files in their respective document roots. One site is letting me use the CMS's clean-url mode, and the other isn't. Site #2 functions fine in ?=messy-url mode, but when I turn clean urls on in the admin panel, and request a rewritten URL, I get a 404 error served before the CMS sees the request. I've contacted the server administrator, but he isn't inclined to provide support and the site owners are beholden to this hosting provider. I have shell access to the Linux-based server, and I can verify that mod_php and mod_rewrite are active, but I don't know what more I can do to troubleshoot this issue. Is there any way to identify directives upstream that may be differentiating the way http requests are handled by the two sites? Thanks! A: I found out the cause of this issue: Apache is configured to only listen to .htaccess on specified subdirectories, and Site #2 is not one of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/2596412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HttpServletResponse contained in servlet filter does not perform redirect I am using Spring 4.0.6 in a servlet application. I have an abstract base controller with some general methods for all my controllers to use. One of these methods is a redirect. I want to have a method with signature redirect(String path) To send a redirect, I am using response.sendRedirect(response.encodeRedirectURL(path)); As I would like to keep method signatures short and clean, I need to get access to the response object inside the superclass method. In order to do this, I've followed a suggestion found online, and defined a servlet filter with a ThreadLocal HttpServletResponse. public class ResponseFilter extends OncePerRequestFilter { private static final ThreadLocal<HttpServletResponse> responses = new ThreadLocal<HttpServletResponse>(); public static HttpServletResponse getResponse() { return responses.get(); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { responses.set(response); } finally { try { filterChain.doFilter(request, response); } finally { responses.remove(); } } } } As I am using Spring security with a Java configuration, I'm adding this filter in my WebSecurityConfigurerAdapter subclass: .addFilterAfter(rf, SwitchUserFilter.class) Note that I have also tried adding the filter as first in the filterchain, and that I have tried using an Interceptor instead. All with the same results. I have compared hashcodes on the response objects, and near as I can tell, the hashcodes match, but the redirect seems to be ignored. I have also looked at object ids on breakpoints in Eclipse, and there again, I have a match. The symptom is that the spring DispatcherServlet enters processDispatchResult and seems to think it needs to resolve a view. That view does not exist, as I expect to do a redirect: javax.servlet.ServletException: File &quot;/WEB-INF/views/application/redirecttest.jsp&quot; not found I have noticed that, if I add the response object back in my requestmapping controller method signature, the superclass redirect seems to work (even though I do not use the controller method response object at all). Unfortunately, this behavior is reproducible both on a Mac and on Linux. I use Tomcat 7 as container. A: Your filter should work just fine, but the problem you're facing is another. If you are using views (as you appear to do in the example) you need to return a redirect view from your controller in order to force a redirect; just instructing the response object to redirect won't work because Spring MVC infrastructure will try to do its thing (i.e. view resolution) before the Response is returned to the Servlet container. For instance, if you use the convention to return the view name as a String from your controller method, you need to do the following in your controller: @RequestMapping("/redirectTest") public String redirectTest() { return "redirect:http://www.example.com"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24969135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Rows to Columns in Sql Server 2012 I have a table like this : MNUM EXP_TYP ExpenseLabel AMOUNT 572711 2 Taxes 7080 572711 3 Insurance 3730 572711 4 Electric 7800 572711 5 WaterIncome 6000 572711 7 Trash 2400 572711 8 Gardner 1200 572711 14 AnnOperExp 900 572741 2 Taxes 8400 572741 3 Insurance 1200 572741 5 WaterIncome 4800 572741 7 Trash 1200 572741 8 Gardner 1800 572741 11 RepairMaint 1200 572741 34 Pest 80 I want the result like this : MNUM Taxes Insurance Electric WaterIncome Trash AnnOperExp RepairMaint Pest 572711 7080 3730 7800 6000 2400 900 572741 8400 1200 4800 1200 1200 80 This is what I tried : DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME(ExpenseLabel) from #TempExpensesTab group by MNUM,ExpenseLabel,EXP_TYP,AMOUNT order by EXP_TYP FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = N'SELECT ' + @cols + N' from ( select ExpenseLabel, AMOUNT from #TempExpensesTab ) x pivot ( max(AMOUNT) for ExpenseLabel in (' + @cols + N') ) p ' exec sp_executesql @query; I am getting the following error : "The column 'Taxes ' was specified multiple times for 'p'." Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/28703857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: type transfer int to str Question: Given a string containing uppercase alphabets and integer digits (from 0 to 9), write a function to return the alphabets in the order followed by the sum of digits. My Code: import re class Solution: def rearrange(self, str): # Write your code here if str == "": return str sum = 0 letter = [] for i in range(len(str)): if re.search("([A-Z])", str[i]): letter.append(str[i]) else: sum += int(str[i]) letsort = sorted(letter) letstr = "".join(letsort) result = letstr + str(sum) return result Error: Traceback (most recent call last): File "/code/Main.py", line 20, in ans = solution.rearrange(str) File "/code/Solution.py", line 20, in rearrange result = letstr + str(sum) TypeError: 'str' object is not callable I don't understand the reason. A: str is a reserved word in Python, and you overwrote it by naming rearrange() second parameter str as well. Changing the name of rearrange() second parameter will do the trick. A: You have named your variable str - same name as built-in function for conversion to string. You need to rename it, try this: import re class Solution: def rearrange(self, str_in): # Write your code here if str_in == "": return str_in sum = 0 letter = [] for i in range(len(str_in)): if re.search("([A-Z])", str_in[i]): letter.append(str_in[i]) else: sum += int(str_in[i]) letsort = sorted(letter) letstr = "".join(letsort) result = letstr + str(sum) return result
{ "language": "en", "url": "https://stackoverflow.com/questions/49681941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zooming with VLCJ Is there any way to zoom in a video with VLCJ like VLC has this feature. I think it is called magnify or interactive zoom. It is under Tools >> Effects and filters >> Video >> Geometry >> Magnify I use vlcj with javafx 9, rendering frames to a canvas with an EmbeddedMediaPlayer. I also try to add this magnify filter to MediaPlayerFactory like new MediaPlayerFactory("--video-filter=magnify") but i have no idea, how to navigate this feature or set zoom level since "-zoom 2.0" is not working. I tried cropping, but that havent worked for me, or i tried really badly. Thank you for your help! A: As a bare minimum this should work for zooming: mediaPlayer.video().setScale(float factor); Where factor is like 2.0 for double, 0.5 for half and so on. In my experience, it can be a bit glitchy, and you probably do need to use it in conjunction with crop - and by the way, cropping does work. But if you want an interactive zoom, then you build that yourself invoking setCrop and setScale depending on some UI interactions you control. For the picture-in-picture type of zoom, if you're using VLC itself you do something like this: vlc --video-filter=magnify --avcodec-hw=none your-filename.mp4 It shows a small overlay where you can drag a rectangle and change the zoom setting. In theory, that would have been possible to use in your vlcj application by passing arguments to the MediaPlayerFactory: List<String> vlcArgs = new ArrayList<String>(); vlcArgs.add("--avcodec-hw=none"); vlcArgs.add("--video-filter=magnify"); MediaPlayerFactory factory = new MediaPlayerFactory(args); The problem is that it seems like you need "--avcodec-hw=none" (to disable hardware decoding) for the magnify filter to work - BUT that option is not supported (and does not work) in a LibVLC application. So unfortunately you can't get that native "magnify" working with a vlcj application. A final point - you can actually enable the magnify filter if you use LibVLC's callback rendering API (in vlcj this is the CallbackMediaPlayer) as this does not use hardware decoding. However, what you would see is the video with the magnify overlays painted on top but they are not interactive and your clicks will have no effect. So in short, there's no satisfactory solution for this really. In theory you could build something yourself, but I suspect it would not be easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/60146011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache HTTPClient not processing new line characters I am writing a small app that retrieves some html from a web server based on some variables in the http POST. The HTML data that comes back has a <pre> section in it with some words that are spaced out nicely using newline and tab characters but my app does not receive them. The code is as follows HttpPost post = new HttpPost("REMOVED FOR PRIVACY"); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //REMOVED FOR PRIVACY post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(post, httpContext); String htmlBrief = inputStreamToString(response.getEntity().getContent()).toString(); return htmlBrief; } I think it might be how I am reading the response by putting it through a BufferedReader like so private StringBuilder inputStreamToString(InputStream is) throws IOException { int c; StringBuilder total = new StringBuilder(); // Wrap a BufferedReader around the InputStream BufferedReader rd = new BufferedReader(new InputStreamReader(is)); // Read response until the endIndex while ((c = rd.read()) != -1) { total.append((char)c); } // Return full string return total; } I thought it might be because I was reading in line by line in the buffered reader so I switched to one character at a time but it didn't help the problem. Any help would be greatly appreciated. Thanks, Ben A: Use Charles or Fiddler to inspect what is actually sent in the HTTP request body. Most likely problems: * *Mismatching character sets for client & server; *Failure to decode the URL encoded body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7898863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creating a function reference that has value parameters not references I'm not sure exactly how to describe what I want. I want to define a function with the parameters being a local VALUE not a reference. say I have list of objects I want to create for(i = 0; i < 10; i++){ var div = document.createElement("div"); div.onclick = function(){alert(i);}; document.appendChild(div); } Now I believe in this example no matter what div I click on, it would alert "10"; as that is the last value of the variable i; Is there a way/how do I create a function with the parameters being the value they are at the time I specify the function... if that makes any sense. A: You need to create the function inside another function. For example: div.onclick = (function(innerI) { return function() { alert(innerI); } })(i); This code creates a function that takes a parameter and returns a function that uses the parameter. Since the parameter to the outer function is passed by value, it solves your problem. It is usually clearer to make the outer function a separate, named function, like this: function buildClickHandler(i) { return function() { alert(i); }; } for(i = 0; i < 10; i++){ var div = document.createElement("div"); div.onclick = buildClickHandler(i); document.appendChild(div); } A: You could use an anonymous function: for(i = 0; i < 10; i++){ (function(i){ var div = document.createElement("div"); div.onclick = function(){alert(i);}; document.appendChild(div); })(i) }
{ "language": "en", "url": "https://stackoverflow.com/questions/2451343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What are the types of jquery selectors? I'm having a problem with this question and didn't have any good source, can you please help me ? What are the selectors? A: These are the jquery selectors (as of jQuery 1.10 and jQuery 2.0): * *All Selector ("*") Selects all elements. *:animated Selector Select all elements that are in the progress of an animation at the time the selector is run. *Attribute Contains Prefix Selector [name|="value"] Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-). *Attribute Contains Selector [name*="value"] Selects elements that have the specified attribute with a value containing the a given substring. *Attribute Contains Word Selector [name~="value"] Selects elements that have the specified attribute with a value containing a given word, delimited by spaces. *Attribute Ends With Selector [name$="value"] Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive. *Attribute Equals Selector [name="value"] Selects elements that have the specified attribute with a value exactly equal to a certain value. *Attribute Not Equal Selector [name!="value"] Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value. *Attribute Starts With Selector [name^="value"] Selects elements that have the specified attribute with a value beginning exactly with a given string. *:button Selector Selects all button elements and elements of type button. *:checkbox Selector Selects all elements of type checkbox. *:checked Selector Matches all elements that are checked or selected. *Child Selector ("parent > child") Selects all direct child elements specified by “child” of elements specified by “parent”. *Class Selector (“.class”) Selects all elements with the given class. *:contains() Selector Select all elements that contain the specified text. *Descendant Selector ("ancestor descendant") Selects all elements that are descendants of a given ancestor. *:disabled Selector Selects all elements that are disabled. *Element Selector (“element”) Selects all elements with the given tag name. *:empty Selector Select all elements that have no children (including text nodes). *:enabled Selector Selects all elements that are enabled. *:eq() Selector Select the element at index n within the matched set. *:even Selector Selects even elements, zero-indexed. See also odd. *:file Selector Selects all elements of type file. *:first-child Selector Selects all elements that are the first child of their parent. *:first-of-type Selector Selects all elements that are the first among siblings of the same element name. *:first Selector Selects the first matched element. *:focus Selector Selects element if it is currently focused. *:gt() Selector Select all elements at an index greater than index within the matched set. *Has Attribute Selector [name] Selects elements that have the specified attribute, with any value. *:has() Selector Selects elements which contain at least one element that matches the specified selector. *:header Selector Selects all elements that are headers, like h1, h2, h3 and so on. *:hidden Selector Selects all elements that are hidden. *ID Selector (“#id”) Selects a single element with the given id attribute. *:image Selector Selects all elements of type image. *:input Selector Selects all input, textarea, select and button elements. *:lang() Selector Selects all elements of the specified language. *:last-child Selector Selects all elements that are the last child of their parent. *:last-of-type Selector Selects all elements that are the last among siblings of the same element name. *:last Selector Selects the last matched element. *:lt() Selector Select all elements at an index less than index within the matched set. ***Multiple Attribute Selector [name="value"][name2="value2"] Matches elements that match all of the specified attribute filters. *Multiple Selector (“selector1, selector2, selectorN”) Selects the combined results of all the specified selectors. *Next Adjacent Selector (“prev + next”) Selects all next elements matching “next” that are immediately preceded by a sibling “prev”. *Next Siblings Selector (“prev ~ siblings”) Selects all sibling elements that follow after the “prev” element, have the same parent, and match the filtering “siblings” selector. *:not() Selector Selects all elements that do not match the given selector. *:nth-child() Selector Selects all elements that are the nth-child of their parent. *:nth-last-child() Selector Selects all elements that are the nth-child of their parent, counting from the last element to the first. *:nth-last-of-type() Selector Selects all elements that are the nth-child of their parent, counting from the last element to the first. *:nth-of-type() Selector Selects all elements that are the nth child of their parent in relation to siblings with the same element name. *:odd Selector Selects odd elements, zero-indexed. See also even. *:only-child Selector Selects all elements that are the only child of their parent. *:only-of-type Selector Selects all elements that have no siblings with the same element name. *:parent Selector Select all elements that have at least one child node (either an element or text). *:password Selector Selects all elements of type password. *:radio Selector Selects all elements of type radio. *:reset Selector Selects all elements of type reset. *:root Selector Selects the element that is the root of the document. *:selected Selector Selects all elements that are selected. *:submit Selector Selects all elements of type submit. *:target Selector Selects the target element indicated by the fragment identifier of the document’s URI. *:text Selector Selects all elements of type text. *:visible Selector Selects all elements that are visible. Source: http://api.jquery.com/category/selectors/
{ "language": "en", "url": "https://stackoverflow.com/questions/21081694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: oh-my-posh module is working slowly inside git directories I am using oh-my-posh for PowerShell and it is extremely slow inside git repos. In regular directories, if I press enter, a new line appears instantly. However, if I press enter inside git repos it takes 1-2 seconds for a new line to appear. Here's my profile: { "$schema": "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/schema.json", "blocks": [ { "alignment": "left", "segments": [ { "background": "#91ddff", "foreground": "#100e23", "powerline_symbol": "", "properties": { "folder_icon": "", "folder_separator_icon": "  ", "home_icon": "", "style": "agnoster" }, "style": "powerline", "type": "path" }, { "background": "#95ffa4", "foreground": "#193549", "powerline_symbol": "", "style": "powerline", "type": "git", "properties": { "display_status": true, "display_stash_count": true, "display_upstream_icon": true } }, { "background": "#906cff", "foreground": "#100e23", "powerline_symbol": "", "properties": { "prefix": "  " }, "style": "powerline", "type": "python" }, { "background": "#ff8080", "foreground": "#ffffff", "powerline_symbol": "", "style": "powerline", "type": "exit" } ], "type": "prompt" } ], "final_space": true } I have tried setting display_status, display_stash_count and display_upstream_icon to false as well, but that does practically nothing for the performance. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/68618489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sqlalchemy.exc.NoReferencedTableError I am creating a simple blog in Flask. I have created 2 models for Users and Posts. The code for the main.py file is given below. from flask import Flask from flask import render_template from flask import url_for from forms import RegistrationForm, LoginForm from flask import flash from flask import redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SECRET_KEY'] = 'b91bfa7c7111f5ced35cb6431ae5d341' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpeg') password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True) def __repr__(self): return f"User('{self.username}', '{self.email}', '{self.image_file}')" class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user_id'), nullable=False) def __repr__(self): return f"Post('{self.title}','{self.date_posted}')" @app.route('/') def home_page(): return render_template('home_page.html', posts=posts, title='Home-Page') @app.route('/about') def about_page(): return render_template('about_page.html', title='About-Page') @app.route('/register', methods=['POST', 'GET']) def register(): form = RegistrationForm() if form.validate_on_submit(): flash(f'Account Created for {form.username.data} !', 'success') return redirect(url_for('home_page')) return render_template('register.html', form=form, title='Register') @app.route('/login', methods=['POST', 'GET']) def login(): form = LoginForm() if form.validate_on_submit(): if form.email.data == '[email protected]' and form.password.data =='admin': flash('Login Successful', 'success') return redirect(url_for('home_page')) else: flash('Login unsuccessful, Please check credentials', 'danger') return render_template('login.html', form=form, title='Login') if __name__ == '__main__': app.run(debug=True) then I used the following command from main import db db.create_all() this keeps showing following error sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'post.user_id' could not find table 'user_id' with which to generate a foreign key to target column 'None' A: You need to reference the target table name and column name(s) in the ForeignKey. Therefore, the line: user_id = db.Column(db.Integer, db.ForeignKey('user_id'), nullable=False) should be: user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
{ "language": "en", "url": "https://stackoverflow.com/questions/60592263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python: can't open file '//ML_project.py': [Errno 2] No such file or directory in Docker Here is the content in my Dockerfile. I am trying to containerise a python script (ML_project.py). FROM continuumio/miniconda3:latest COPY ML_Project.py . RUN pip install fxcmpy CMD ["python", "ML_project.py"] My dockerfile and ML_project.py lies within the same folder (fxcm_project) C:\Users\Jack\PycharmProjects\fxcm_project How do I set my current working directory and docker run the file? A: When you docker build, you create a container which embeds all stuffs specified in the Dockerfile. If during the execution a local resource cannot be found, then it is most likely that the ressource is not wothin the container or you passed a wrong location. In your case, you might be looking for the WORKDIR dockerfile command: WORKDIR . NOTE: During the debug phase, feel free to edit your Dockerfile in order to get more (precise) pieces of information. For instance, you could change the last line to print out the current working directory and list all the files it contains. The associated commands are respectively pwd and ls -la.
{ "language": "en", "url": "https://stackoverflow.com/questions/74478598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Components with uppercase function names are rendered multiple times in React Hooks I've been developing with Hooks for a long time, But I met a situation where I was confused. Let me briefly describe this strange problem with a particular case. I created a very simple functional component called Test: // test.js export default function Test () { useEffect(() => { console.log('Test') }, []) return ( <h2> Test Component </h2> ) } It will print something at the first render And the component will be referenced in App // App.js import React, { useEffect, useState } from "react"; import Test from './test'; export default function App() { const [number, updateNumber] = useState(0); const renderComponent = () => { return ( <Test /> ) } const RenderComponent = () => { return ( <Test /> ) } useEffect(() => { updateNumber(1) updateNumber(2) }, []) console.log('every-render') return ( <div className="App"> {renderComponent()} {/* <RenderComponent /> */} <h1>Rerender times: {number}</h1> </div> ); } So something strange happened When I use this way, the Test component will be printed once // Case 1 const renderComponent = () => { return ( <Test /> ) } // ... renderComponent() Something that it prints in Console But when I use this way, the Test component will be printed twice // Case 2 const RenderComponent = () => { return ( <Test /> ) } // ... <RenderComponent /> Something that it prints in Console Of course, I wrote a demo for you to debug: https://codesandbox.io/s/demo-for-hooks-8gkml?file=/src/App.js I am confused why in case 2 the Test component will be remounted each time the Hooks are rerendered. A: Every render cycle the RenderComponent component is recreated, so it is mounted every render, and thus, mounts its children. Consider the following code where you render <Test /> directly, it's output is identical to {renderComponent()}. export default function App() { const [number, updateNumber] = useState(0); const renderComponent = () => { return <Test />; }; const RenderComponent = () => { return <Test />; }; useEffect(() => { updateNumber(1); updateNumber(2); }, []); useEffect(() => { console.log("every-render"); }); return ( <div className="App"> {/* {renderComponent()} */} {/* <RenderComponent /> */} <Test /> // <-- "Mounted Test", "every-render", "every-render" <h1>Rerender times: {number}</h1> </div> ); } The function renderComponent is executed and the return value is <Test />, thus equivalent to just rendering <Test /> directly, whereas RenderComponent is a new component each cycle. A: When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements. Consider 3 cases: {renderComponent()} <RenderComponent /> <Test /> 1) {renderComponent()} Every render just return Test type, algorithm compares and sees that the type has not changed. Result: mount Test component 1 time. 2) <RenderComponent /> Every render return new component type RenderComponent, algorithm compares and sees RenderComponent1 type != RenderComponent2 type, and: Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Result: mount child Test component 2 times. Add console to mount RenderComponent: const RenderComponent = () => { useEffect(() => console.log('RenderComponent mount'), []); return <Test />; }; RenderComponent too mount 2 times. 3) <Test /> Similarly 1 case. Result: mount Test component 1 time.
{ "language": "en", "url": "https://stackoverflow.com/questions/62167440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Array permutations in multidimensional array keeping the keys PHP For two days I've been running crazy trying to accomplish this, maybe you can enlighten me. This is for a horse betting permutation. Every time a user plays, I get a multidimensional array (2 levels). The first level contains the race ID, the the second level contains thee horses selected by the user for that race. It looks like this: $play = array ( '4' => array(7, 32), '8' => array(4), '2' => array(9), '12' => array('5'), '83' => array('10', '11', '12', ''), '9' => array('3'), ); I need to know what are all the possible combinations for that play. Which is easily done with this function: function permutations(array $array) { switch (count($array)) { case 1: return $array[0]; break; case 0: throw new InvalidArgumentException('Requires at least one array'); break; } $a = array_shift($array); $b = permutations($array); $return = array(); foreach ($a as $key => $v) { if(is_numeric($v)) { foreach ($b as $key2 => $v2) { $return[] = array_merge(array($v), (array) $v2); } } } return $return; } This returns an array with all the possible combinations beautifully. So far so good, and the result looks like this: Array ( [0] => Array ( [0] => 7 [1] => 4 [2] => 9 [3] => 5 [4] => 10 [5] => 3 ) [1] => Array ( [0] => 7 [1] => 4 [2] => 9 [3] => 5 [4] => 11 [5] => 3 ) [2] => Array ( [0] => 7 [1] => 4 [2] => 9 [3] => 5 [4] => 12 [5] => 3 ) [3] => Array ( [0] => 32 [1] => 4 [2] => 9 [3] => 5 [4] => 10 [5] => 3 ) [4] => Array ( [0] => 32 [1] => 4 [2] => 9 [3] => 5 [4] => 11 [5] => 3 ) [5] => Array ( [0] => 32 [1] => 4 [2] => 9 [3] => 5 [4] => 12 [5] => 3 ) ) My problem: I need the array "key" for every horse to be the "race ID", not 0,1,2,3. I need the result to be like this: Array ( [0] => Array ( [4] => 7 [8] => 4 [2] => 9 [12] => 5 [83] => 10 [9] => 3 ) [1] => Array ( [4] => 7 [8] => 4 [2] => 9 [12] => 5 [83] => 11 [9] => 3 ) [2] => Array ( [4] => 7 [8] => 4 [2] => 9 [12] => 5 [83] => 12 [9] => 3 ) [3] => Array ( [4] => 32 [8] => 4 [2] => 9 [12] => 5 [83] => 10 [9] => 3 ) [4] => Array ( [4] => 32 [8] => 4 [2] => 9 [12] => 5 [83] => 11 [9] => 3 ) [5] => Array ( [4] => 32 [8] => 4 [2] => 9 [12] => 5 [83] => 12 [9] => 3 ) ) How can I accomplish this? I know its a long post but I needed to graph this. I am having problems to wrap my head around the function recursion and I get totally lost in each loop. A: I've got the same problem and Danny's solution wasn't good for me. I manage thousand of permutation and store them in memory is damn expensive. Here my solution: /** * Calculate permutation of multidimensional array. Without recursion! * Ex. * $array = array( * key => array(value, value), * key => array(value, value, value), * key => array(value, value), * ); * * @copyright Copyright (c) 2011, Matteo Baggio * @param array $anArray Multidimensional array * @param function $isValidCallback User function called to verify the permutation. function($permutationIndex, $permutationArray) * @return mixed Return valid permutation count in save memory configuration, otherwise it return an Array of all permutations */ function permutationOfMultidimensionalArray(array $anArray, $isValidCallback = false) { // Quick exit if (empty($anArray)) return 0; // Amount of possible permutations: count(a[0]) * count(a[1]) * ... * count(a[N]) $permutationCount = 1; // Store informations about every column of matrix: count and cumulativeCount $matrixInfo = array(); $cumulativeCount = 1; foreach($anArray as $aColumn) { $columnCount = count($aColumn); $permutationCount *= $columnCount; // this save a lot of time! $matrixInfo[] = array( 'count' => $columnCount, 'cumulativeCount' => $cumulativeCount ); $cumulativeCount *= $columnCount; } // Save the array keys $arrayKeys = array_keys($anArray); // It needs numeric index to work $matrix = array_values($anArray); // Number of column $columnCount = count($matrix); // Number of valid permutation $validPermutationCount = 0; // Contain all permutations $permutations = array(); // Iterate through all permutation numbers for ($currentPermutation = 0; $currentPermutation < $permutationCount; $currentPermutation++) { for ($currentColumnIndex = 0; $currentColumnIndex < $columnCount; $currentColumnIndex++) { // Here the magic! // I = int(P / (Count(c[K-1]) * ... * Count(c[0]))) % Count(c[K]) // where: // I: the current column index // P: the current permutation number // c[]: array of the current column // K: number of the current column $index = intval($currentPermutation / $matrixInfo[$currentColumnIndex]['cumulativeCount']) % $matrixInfo[$currentColumnIndex]['count']; // Save column into current permutation $permutations[$currentPermutation][$currentColumnIndex] = $matrix[$currentColumnIndex][$index]; } // Restore array keys $permutations[$currentPermutation] = array_combine($arrayKeys, $permutations[$currentPermutation]); // Callback validate if ($isValidCallback !== false) { if ($isValidCallback($currentPermutation, $permutations[$currentPermutation])) $validPermutationCount++; // *** Uncomment this lines if you want that this function return all // permutations //else // unset($permutations[$currentPermutation]); } else { $validPermutationCount++; } // Save memory!! // Use $isValidCallback to check permutation, store into DB, etc.. // *** Comment this line if you want that function return all // permutation. Memory warning!! unset($permutations[$currentPermutation]); } if (!empty($permutations)) return $permutations; else return $validPermutationCount; } // // How to? // $play = array( '4' => array(7, 32), '8' => array(4), '2' => array(9), '12' => array('5'), '83' => array('10', '11', '12', ''), // <-- It accept all values, nested array too '9' => array('3'), ); $start = microtime(true); // Anonymous function work with PHP 5.3.0 $validPermutationsCount = permutationOfMultidimensionalArray($play, function($permutationIndex, $permutationArray){ // Here you can validate the permutation, print it, etc... // Using callback you can save memory and improve performance. // You don't need to cicle over all permutation after generation. printf('<p><strong>%d</strong>: %s</p>', $permutationIndex, implode(', ', $permutationArray)); return true; // in this case always true }); $stop = microtime(true) - $start; printf('<hr /><p><strong>Performance for %d permutations</strong><br /> Execution time: %f sec<br/> Memory usage: %d Kb</p>', $validPermutationsCount, $stop, memory_get_peak_usage(true) / 1024); If someone has a better idea i'm here! A: Here's what you need. I have commented as necessary: function permutations(array $array) { switch (count($array)) { case 1: // Return the array as-is; returning the first item // of the array was confusing and unnecessary return $array; break; case 0: throw new InvalidArgumentException('Requires at least one array'); break; } // We 'll need these, as array_shift destroys them $keys = array_keys($array); $a = array_shift($array); $k = array_shift($keys); // Get the key that $a had $b = permutations($array); $return = array(); foreach ($a as $v) { if(is_numeric($v)) { foreach ($b as $v2) { // array($k => $v) re-associates $v (each item in $a) // with the key that $a originally had // array_combine re-associates each item in $v2 with // the corresponding key it had in the original array // Also, using operator+ instead of array_merge // allows us to not lose the keys once more $return[] = array($k => $v) + array_combine($keys, $v2); } } } return $return; } See it in action. By the way, calculating all the permutations recursively is neat, but you might not want to do it in a production environment. You should definitely consider a sanity check that calculates how many permutations there are and doesn't allow processing to continue if they are over some limit, at the very least. A: I improved Jon's function by merging his algorithm with the one I had initially. What I did, was check if the function was doing a recursion, if so, I use the original array_merge() (which was working), else I use Jon's array_combine() (to keep the arrays keys). I'm marking Jon's answer as correct since he proposed a slick solution to keep the array keys intact. function permutations(array $array, $inb=false) { switch (count($array)) { case 1: // Return the array as-is; returning the first item // of the array was confusing and unnecessary return $array[0]; break; case 0: throw new InvalidArgumentException('Requires at least one array'); break; } // We 'll need these, as array_shift destroys them $keys = array_keys($array); $a = array_shift($array); $k = array_shift($keys); // Get the key that $a had $b = permutations($array, 'recursing'); $return = array(); foreach ($a as $v) { if(is_numeric($v)) { foreach ($b as $v2) { // array($k => $v) re-associates $v (each item in $a) // with the key that $a originally had // array_combine re-associates each item in $v2 with // the corresponding key it had in the original array // Also, using operator+ instead of array_merge // allows us to not lose the keys once more if($inb == 'recursing') $return[] = array_merge(array($v), (array) $v2); else $return[] = array($k => $v) + array_combine($keys, $v2); } } } return $return; } Tested successfully with several array combinations.
{ "language": "en", "url": "https://stackoverflow.com/questions/5967587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SUMIF SQL MS Access SELECT [doc type], [Open Amount], [customer number], COUNT([customer number]) As CountCustomerNumber, SUM(IIF([Open Amount]>'0', [Open Amount], 0)) AS sum_open_amount_pos, SUM(IIF([Open Amount]<'0', [Open Amount], 0)) As sum_open_amount_neg FROM ( SELECT d.[customer number] & d.[membership number] AS CustMemb, d.[customer number], agg.[Open Amount], agg.[doc type], SUM(agg.[TotalSubOpenAmount]) AS SumOpenAmount FROM ( SELECT [doc type], [customer number], SUM([Open Amount]) AS TotalSubOpenAmount FROM data WHERE [doc type] = 'RU' GROUP BY [doc type], [customer number], [Open Amount] ) agg INNER JOIN [data] d ON d.[customer number] = agg.[customer number] GROUP BY d.[customer number] & d.[membership number], d.[customer number], agg.[doc type], agg.[Open Amount] ) AS sub GROUP BY [doc type], [customer number] HAVING COUNT([customer number]) = 1 I am getting a Parameter Input on MS Access - Open Amount. How do I reference the open amount in the from query?
{ "language": "en", "url": "https://stackoverflow.com/questions/67888928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Navigationview Set SelectedItem for sub-menu item in UWP app I trying to set default selected item for navigationview by DashboardMenuItem.IsExpanded = true; Microsoft.UI.Xaml.Controls.NavigationViewItem selectedItem =(Microsoft.UI.Xaml.Controls.NavigationViewItem)DashboardMenuItem.MenuItems[0]; NavView.SelectedItem = selectedItem; Here is my XAML <MUXC:NavigationView.MenuItems> <MUXC:NavigationViewItem x:Name="DashboardMenuItem" Content="{x:Bind DashboardLabel}" Foreground="#FFFFFF" ToolTipService.ToolTip="{x:Bind DashboardLabel}"> <MUXC:NavigationViewItem.Icon> <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE8A9;" /> </MUXC:NavigationViewItem.Icon> <MUXC:NavigationViewItem.MenuItems> <MUXC:NavigationViewItem x:Name="ListofPersonMenuItem" Content="{x:Bind ListofPersonLabel}" Foreground="#FFFFFF" ToolTipService.ToolTip="{x:Bind ListofPersonLabel}" /> <MUXC:NavigationViewItem x:Name="ListofDiedPersonsMenuItem" Content="{x:Bind ListofDiedPersonsLabel}" Foreground="#FFFFFF" ToolTipService.ToolTip="{x:Bind ListofDiedPersonsLabel}" /> </MUXC:NavigationViewItem.MenuItems> </MUXC:NavigationViewItem> But my menu item just have a highlight background only, still don't have the left bar like when we select by clicking. Picture link below (sorry because I cannot post the image yet) https://i.gyazo.com/f2953c8f092534ea26ceb7fef0120de2.png So, do you have any suggestion for this please? Thank in advance A: Navigationview Set SelectedItem for sub-menu item in UWP app During the testing, the problem is expend animation block select animation that make item indicator dismiss. Currently we have a workaround that add a task delay before set SelectedItem. It will do select animation after DashboardMenuItem expend. DashboardMenuItem.IsExpanded = true; Microsoft.UI.Xaml.Controls.NavigationViewItem selectedItem = (Microsoft.UI.Xaml.Controls.NavigationViewItem)DashboardMenuItem.MenuItems[0]; await Task.Delay(100); MainNavigation.SelectedItem = selectedItem;
{ "language": "en", "url": "https://stackoverflow.com/questions/65017337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Background disappears when expanding an element CSS? When I add a new element in (using JavaScript event listener to set display from none to grid) the background of the body behind and around the element (which is set to 80% width) goes solid white. If I remove html tag from the following code it fixes it but then the body background image doesn't fill the entire screen on mobile. Really stuck on a fix if anyone can help? photo below after the code Thank you body css body, html { padding: 0; background: url(/resources/clearday.jpg); background-position: center; background-repeat: no-repeat; background-size: cover; height: 100%; width: 100%; margin: 0 auto; } element css .extraForecast { display: grid; align-items: center; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(4, 4fr) 1fr; width: 80%; margin: 0 auto; padding: 0; font-size: 2.15rem; text-align: center; background-color:white; opacity: 0.7; border-radius: 8px; margin-top: 2rem; padding: 0; } image of the issue A: I've only tested quickly on mobile, but stopping the background image from scrolling with the page seemed to fix it. To do this I added background-attachment: fixed; to the CSS for body, html
{ "language": "en", "url": "https://stackoverflow.com/questions/65400297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrading NC30 M16 C Compiler: va_arg issue In my NC30 M16C compiler version 5, I had the following macros used by previous programmer. We use this macros in the "printf()", "sprintf()" etc functions. typedef unsigned char * va_list; #define va_start( args, first ) args = (va_list) ( (unsigned short) &first + sizeof( first ) ) #define va_arg( args, type ) *( (type *) args )++ #define va_end( args ) When I compile this code with NC30 M16C compiler version 6, then it is giving me the error "Invalid lvalue". Here is the part of the entire error message: clib.c(253) : C2700 (E) invalid lvalue ===> unum = va_arg( args, unsigned int ); clib.c(293) : C2700 (E) invalid lvalue ===> fch = va_arg( args, far char * ); clib.c(299) : C2700 (E) invalid lvalue ===> nch = va_arg( args, char * ); clib.c(305) : C2700 (E) invalid lvalue ===> unum = va_arg( args, unsigned int ); clib.c(323) : C2700 (E) invalid lvalue ===> ulong = va_arg( args, unsigned long ); clib.c(341) : C2700 (E) invalid lvalue ===> llong = va_arg( args, unsigned long long ); clib.c(359) : C2700 (E) invalid lvalue ===> ulong = va_arg( args, unsigned long ); clib.c(377) : C2700 (E) invalid lvalue ===> unum = va_arg( args, unsigned short ); clib.c(382) : C2700 (E) invalid lvalue ===> ft = va_arg( args, float ); clib.c(519) : C2694 (E) unknown variable source ===> *source++ = zeropad ? '0' : ' '; clib.c(527) : C2694 (E) unknown variable source ===> *source++ = '%'; clib.c(532) : C2700 (E) invalid lvalue ===> snum = va_arg( args, signed int ); clib.c(550) : C2694 (E) unknown variable source ===> *source++ = *tempptr; clib.c(556) : C2700 (E) invalid lvalue ===> fch = va_arg( args, far char * ); clib.c(558) : C2694 (E) unknown variable source ===> *source++ = *fch++; clib.c(564) : C2700 (E) invalid lvalue ===> nch = va_arg( args, char * ); clib.c(566) : C2694 (E) unknown variable source ===> *source++ = *nch++; clib.c(572) : C2700 (E) invalid lvalue ===> unum = va_arg( args, unsigned int ); Here is one of the function in which we have used these micros. This function is the same function as "printf" but named it zwPrintf(): int zwPrintf( far char * format, ... ) { zwVAList args; unsigned int unum; unsigned char temp[ FIELD_BUFF_SIZE + 1 ]; /* for formatting numbers (max length for long decimal) */ unsigned char * tempptr; int zeropad, minfield, counter; far char * fch; char * nch; unsigned long ulong; int negative; float ft, mantissa; unsigned long long llong; //unsigned char mychar; //unsigned char *mychar_p; //unsigned int *mytest_p; va_start( args, format ); while( *format ) { if( *format == '%' ) { format++; zeropad = 0; minfield = 0; negative = 0; if( *format == '0' ) zeropad = 1; /* we want zero padding to field width */ while( *format >= '0' && *format <= '9' ) { /* we are specifying field width */ minfield *= 10; minfield += *format - '0'; format++; } if( minfield > FIELD_BUFF_SIZE ) { /* we want a field width greater than our field buffer, pad misc */ for( counter = 0; counter < minfield - FIELD_BUFF_SIZE; counter++ ) zwPutc( (unsigned char) ( zeropad ? '0' : ' ' ) ); minfield = FIELD_BUFF_SIZE; } switch( *format ) { case '%': /* literal % */ zwPutc( '%' ); break; case 'd': /* signed decimal output */ unum = va_arg( args, unsigned int ); /* pull unsigned, and do math ourselves (to avoid confusion) */ //mychar='a'; //mychar_p = &mychar; //mytest_p = ((unsigned int*)mychar_p); //mytest_p++; //unum = *mytest_p; //unum = (*((unsigned int*)args))++; //unum = (*((unsigned int*)args))++; /* convert to decimal (backward) */ if( unum >= 0x8000 ) { /* number is -'ve */ negative = 1; unum = ~unum + 1; /* make number +'ve */ } tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; do { if( unum ) *tempptr-- = ( unum % 10 ) + '0'; else { if( negative && ( zeropad == 0 ) ) { *tempptr-- = '-'; negative = 0; } else *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; } unum /= 10; counter++; } while( unum || counter < minfield ); /* output the string */ if( negative ) zwPutc( '-' ); for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ ) zwPutc( *tempptr ); break; case 's': /* far char * */ fch = va_arg( args, far char * ); while( *fch ) zwPutc( *fch++ ); break; case 'S': /* near char * (extension) */ nch = va_arg( args, char * ); while( *nch ) zwPutc( *nch++ ); break; case 'x': /* hexadecimal */ unum = va_arg( args, unsigned int ); /* convert to hexadecimal (backward) */ tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; do { if( unum ) *tempptr-- = zwHexToAsc( (unsigned char) unum & 0x0F ); else *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; unum >>= 4; counter++; } while( unum || counter < minfield ); /* output the string */ for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ ) zwPutc( *tempptr ); break; case 'i': /* unsigned long int decimal (extension) */ ulong = va_arg( args, unsigned long ); /* convert to decimal (backward) */ tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; do { if( ulong ) *tempptr-- = (unsigned char)( ulong % 10 ) + '0'; else *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; ulong /= 10; counter++; } while( ulong || counter < minfield ); /* output the string */ for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ ) zwPutc( *tempptr ); break; case 'L': /* unsigned long long decimal (extension) */ llong = va_arg( args, unsigned long long ); /* convert to decimal (backward) */ tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; do { if( llong ) *tempptr-- = (unsigned char)( llong % 10 ) + '0'; else *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; llong /= 10; counter++; } while( llong || counter < minfield ); /* output the string */ for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ ) zwPutc( *tempptr ); break; case 'h': /* unsigned long int hexadecimal (extension) */ ulong = va_arg( args, unsigned long ); /* convert to hexadecimal (backward) */ tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; do { if( ulong ) *tempptr-- = zwHexToAsc( ( (unsigned char) ulong ) & 0x0F ); else *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; ulong >>= 4; counter++; } while( ulong || counter < minfield ); /* output the string */ for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ ) zwPutc( *tempptr ); break; case 'c': unum = va_arg( args, unsigned short ); zwPutc( (char) unum ); break; case 'f': ft = va_arg( args, float ); #if 0 /* convert to decimal (backward) */ if( ft < 0 ) { /* number is -'ve */ negative = 1; ft = -ft; } tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; /* split float to integer and mantissa part */ ulong = ft / 1; mantissa = ft - ( float )ulong; /* get integer part */ do { if( ulong ){ *tempptr-- = (unsigned char)( ulong % 10 ) + '0'; } else { *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; } ulong /= 10; counter++; } while( ulong || counter < minfield ); if ( negative ) { temp[ 0 ] = '-'; zwMemcpy( &temp[ 1 ], &temp[ FIELD_BUFF_SIZE - counter ], counter ); //change to right position counter++; } else zwMemcpy( &temp[ 0 ], &temp[ FIELD_BUFF_SIZE - counter ], counter ); temp[ counter++ ] = '.'; /* get mantissa part */ tempptr = &temp[ counter ]; do { unum = ( mantissa * 10 ) / 1; if( unum ){ *tempptr++ = (unsigned char)( unum ) + '0'; } else { *tempptr++ = '0'; } mantissa = ( float ) ( mantissa * 10.0 - ( float )unum ) * 10.0; counter++; } while( mantissa > 0 || counter < minfield ); for( unum = 0; unum < counter; unum++ ) zwPutc( temp[ unum ] ); /* convert to decimal (backward) */ if( ft < 0 ) { /* number is -'ve */ negative = 1; ft = -ft; } tempptr = &temp[ FIELD_BUFF_SIZE ]; counter = 0; do { if( ft >= 1.0 ){ *tempptr-- = ( ft % 10.0 ) + '0'; // *tempptr-- = ( ft * 10 - ( ( ft * 100 ) / 10 ) ) + '0'; } else { if( negative && ( zeropad == 0 ) ) { *tempptr-- = '-'; negative = 0; } else *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' '; } ft /= 10; counter++; } while( ft >= 1.0 || counter < minfield ); /* output the string */ if( negative ) zwPutc( '-' ); for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ ) zwPutc( *tempptr ); #endif break; case 0: /* end of string (malformed string anyway) */ va_end( args ); return -1; /* error */ break; } } else zwPutc( *format ); format++; } va_end( args ); return -1; } Please guide me, what should I do to correct this issue. Thanks in advance. A: Could you try to replace: #define va_arg( args, type ) *( (type *) args )++ with #define va_arg( args, type ) *( (type *) args ), args += sizeof (type) Explanation: You get the compilation error because this expression: ((type *) args )++ is invalid in C: the result of a cast is not a lvalue and the postfix ++ operator requires its operand to be a lvalue. A lot of compilers are lax with this constraint but apparently yours is not (or the new version is stricter). Also note that the proposed workaround should work in you program with simple assignment expressions like: unum = va_arg( args, unsigned int ); because = has higher precedence than the comma operator. EDIT: another (maybe even better) solution: you should be able to bypass the fact the result of a cast is not a lvalue using this solution: #define va_arg( args, type ) *( *(type **) &args )++
{ "language": "en", "url": "https://stackoverflow.com/questions/11786859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Angular 4.3 HttpClient - How to use HttpHeaders and interceptor properly? I need to send headers to my HttpRequest. I already searched here and I have already tried with a few answers I have found, but none of them worked. The headers are not being sent to api and if I inspect the clonedRequest object, it does not show the headers. That is my code: public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Clone the request to add the new header. const clonedRequest = req.clone(); clonedRequest.headers.set("ModuleId", this.dnnContext.moduleId); clonedRequest.headers.set("TabId", this.dnnContext.tabId); // Pass on the cloned request instead of the original request. return next.handle(clonedRequest); } What am I missing? A: Thats because the instances of classes from the new HttpClient module are immutable. So you need to reassign all the properties that you mutate. This translates into the following in your case: public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Clone the request to add the new header. const headers = req.headers.set("ModuleId", this.dnnContext.moduleId).set("TabId", this.dnnContext.tabId); const clonedRequest= red.clone({ headers: headers }); // Pass on the cloned request instead of the original request. return next.handle(clonedRequest); } A: I have faced similar issue & figured out your 2nd(TypeError: CreateListFromArrayLike called on non-object) issue, for some reason if you pass number type(it has type check but if var type is any it allows & it was the case for me) value in header(ModuleId or TabId in your case) it throws this error so you can convert it to string while passing like: const authReq = req.clone({ headers: req.headers.set('ModuleId', this.dnnContext.moduleId.toString()).set('TabId', this.dnnContext.tabId.toString()) }); // Pass on the cloned request instead of the original request. return next.handle(authReq); Also replied on your github issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/45890655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: this between square brackets I'm new to C++ and while learning and documenting about the subject, I stumbled accross something that intrigued me : [this](type argument) { // code } What does [this] stand for in this function ? Here's the whole function in which I found this : void do_accept() { acceptor_.async_accept(socket_, [this](boost::system::error_code ec) { if (!ec) { std::make_shared<chat_session>(std::move(socket_), room_)->start(); } do_accept(); }); } (It's one of the boost.asio's asynchronous server example)
{ "language": "en", "url": "https://stackoverflow.com/questions/25153622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keyboard is moving view little too up I made simple solution, textfield is pressed, open keyboard and move view up. But the problem is, it is moving it a little too hight and covering first textField. I do not want to make scrollView for this. is there any other solutions? Like this I do what I described above: NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0{ self.view.frame.origin.y += keyboardSize.height } } } Here you can see what it does: A: You have some options: for example: * *move the labels differently depending on the texfield tapped (less if the first field, more for the last) *change your Interface so that all your text fields use just the space available when keyboard is up A: There are many third party libraries available like https://github.com/hackiftekhar/IQKeyboardManager or https://github.com/michaeltyson/TPKeyboardAvoiding. You can use any of them, and forgot about keyboard handling by yourself. These cool libraries take care of most of the things.
{ "language": "en", "url": "https://stackoverflow.com/questions/39902485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'ClientFilter' validation failed: client view is too loose . each client should include one project only I am trying to do same operations that I do with perforce GUI using command line. When I tried to do p4 edit on any file, it said Client '<host-name>' unknown - use 'client' command to create it. So, I tried p4 client -o <my-workspace-name> | p4 client -i but this returned: Error in client specification. 'ClientFilter' validation failed: ====================================================== client view is too loose !!! each client should include one project only ====================================================== I have no experience of p4 tool. Please help me explain what it means with client view too loose !!! A: This is a trigger that your admin has set up. Based on the error, I surmise that they want you to set up your client's View to only include one project (they want to keep you from syncing down the entire world when you set up your new client). To create a new client, run: p4 set P4CLIENT=your_workspace_name p4 client and take a look at the form that pops up. The View field defines which part of the depot(s) your client will "see" and operate on. According to the error message, your admin wants you to restrict this to a single "project" -- I don't know what that means in this context (maybe it means just a single depot, or maybe a single folder in a particular depot?) so you might need to talk to your admin about it, or maybe browse around in the GUI and try to glean from context clues (i.e. names of directories) what that message is referring to. Just to use a made-up example, if you have a few different depots your default ("loose") View might look like: //depot_one/... //your_workspace_name/depot_one/... //mumble/... //your_workspace_name/mumble/... //widgets/... //your_workspace_name/widgets/... and if you want to only map the project //mumble/core to your workspace root, you'd change that View to: //mumble/core/... //your_workspace_name/...
{ "language": "en", "url": "https://stackoverflow.com/questions/53680860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the best way to keep adding new points to glBufferData? I am making an experiment with OpenGL to find what's the best/most efficient way to very frequently add new data to glBufferData. To do this, I wrote a small 2D paint program and simply keep adding points when I move the mouse. The whole function looks like this: void addPoint(double x, double y) { glBindBuffer(GL_ARRAY_BUFFER, pointVertBuffObj); if (arrayOfPointCapacity < numOfPoints + 1) { U32 size = (arrayOfPointCapacity + 8) * sizeof(Point2); Point2 *tmp = (Point2*)realloc(arrayOfPoints, size); arrayOfPoints = tmp; arrayOfPointCapacity += 8; } arrayOfPoints[numOfPoints].x = x, arrayOfPoints[numOfPoints].y = y; U32 offset = numOfPoints * sizeof(Point2); glBufferData(GL_ARRAY_BUFFER, numOfPoints * sizeof(Point2), arrayOfPoints, GL_DYNAMIC_DRAW); numOfPoints++; } Having to reset glBufferData with new data each time I add a point seems absolutely crazy. I thought about using glBufferData to allocate a large array of points and setting these points up with glBufferSubData. When the size of the buffer becomes too small, then I call glBufferData again increasing the size of the buffer, and copying back existing points to it. Ideally, I would prefer to avoid storing the point data in the computer memory and keep everything in the GPU memory. But when I would resize the buffer, I would have to copy the data back from the buffer to the CPU, then resize the buffer, and finally copy the data back to the buffer from the CPU. All this, also seems inefficient. Any idea? What's best practice? A: When the size of the buffer becomes too small, then I call glBufferData again increasing the size of the buffer, and copying back existing points to it. Not a bad idea. In fact that's the recommended way of doing these things. But don't make the chunks too small. Ideally, I would prefer to avoid storing the point data in the computer memory and keep everything in the GPU memory. That's not how OpenGL works. The contents of a buffer objects can be freely swapped between CPU and GPU memory as needed. But when I would resize the buffer, I would have to copy the data back from the buffer to the CPU, then resize the buffer, and finally copy the data back to the buffer from the CPU. All this, also seems inefficient. Correct. You want to avoid copies between OpenGL and the host program. That's why there is in OpenGL-3.1 and later the function glCopyBufferSubData to copy data between buffers. When you need to resize a buffer you can as well create a new buffer object and copy from the old to the new one^1. [1]: maybe you can also do resizing copys within the same buffer object name, by exploiting name orphaning; but I'd first have to read the specs if this is actually defined, and then cross fingers that all implementations get this right. A: I made a program for scientific graphing before, that could add new data points in real-time. What I did was create a fairly large fixed size buffer with flag GL_DYNAMIC_DRAW, and added individual points to it with glBufferSubData. Once it filled, I created a new buffer with flag GL_STATIC_DRAW and moved all the data there, then started filling the GL_DYNAMIC_DRAW buffer again from the beginning. So I ended up with a small number of static buffers, one dynamic buffer, and since they were all equal size (with monotonically increasing x coordinates) calculating which buffers to use to draw any given segment of the data was easy. And I never had to resize any of them, just keep track of how much of the dynamic buffer was used and only draw that many vertices from it. I don't think I used glCopyBufferSubData as datenwolf suggests, I kept a copy in CPU memory of the data in the dynamic buffer, until I could flush it to a new static buffer. But GPU->GPU copy would be better. I still would allocate more chunk-sized buffers and avoid resizing.
{ "language": "en", "url": "https://stackoverflow.com/questions/25919618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ERROR TypeError: Cannot read property 'group_status' of undefined in console I am getting this error in console and this error increasing continously, I am using two way binding with ngModel with interface. I have attached the screens of my code. screens: This is the component part where getting basicinfo from server in json format calling service This is Error which I am getting in console HTML part where I am fatching data from interface json This is Interface which i am using A: Issue is coz of this line : [(ngModel)]='basicinfo.website' Either change this to [ngModel]='basicinfo?.website' or Provide initial value before ngModel initialisation for 2 way binding basicinfo = { 'website' : '' }; [(ngModel)]='basicinfo.website'
{ "language": "en", "url": "https://stackoverflow.com/questions/48437922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysqldump - select table if it contains a specific string I have a pretty big local WordPress Multisite installation, and this is mirrored on a live server, so I can develop a site locally and upload it for a client to see (it's sub-domain based). I have written a custom shell script to upload the database from my local machine to the live server, which uses sed to change all instances of the local domain name to the live domain name. It then commits and pushes it by git and the live server automatically pulls it, takes a backup and applies the new file. However, this has become problematic in the last month or so. As I've got more client work, and they have been editing their sites live on the server, and I've been pushing new work to the server for other clients to take a look at, I've been overwriting changes on the live database. What I need is to be able to add a flag or something when I call the shell script file (sh push.sh) that indicates what tables in the database need to be pushed live. Each site in the WordPress Multisite database has a number, e.g network_17_posts. So if I could a table number state when I called my shell script, like sh push.sh --table=17 and it would only upload site 17's data, and not overwrite anything else, that would be awesome. As a bonus, if I could specify multiple numbers, so I could upload multiple sites at a time, that would be amazing! As a reference, here is my current shell script for pushing the database live (it could probably be 10x better, but I'm primarily a front-end/PHP dev, not shell script!): rm -rf db_sync.sql mysqldump -u root -ppassword db_name > db_sync.sql sed 's/localdomain.dev/livedomain.com/g' db_sync.sql > new_db_sync.sql rm -rf db_sync.sql mv new_db_sync.sql db_sync.sql git add db_sync.sql read -p "Enter Commit Message: " commit_message git commit -m "$commit_message" git push -u web master A: See dumpting a table using mysqldump. Assuming you have the table names, or a list of table names, you could either dump them all with one command or loop: : > db_sync.sql for table in tableNames; do mysqldump -u root -ppassword db_name table >> db_sync.sql done To get the table names: number=17 echo "select TABLE_NAME from information_schema.tables where TABLE_NAME like '%\_$number\_%' and TABLE_SCHEMA = 'databasename'" | \ mysql -udbuser -pdbpassword databasename So, if you have multiple numbers, e.g. as command line arguments, you can put this all together: sql="select TABLE_NAME from information_schema.tables where TABLE_NAME like '%\_$number\_%' and TABLE_SCHEMA = 'databasename'" # truncate/create the dump file : > db_sync.sql # loop through the command line arguments for number in $@; do # for each tableName from the sql ... while read tableName; do # append to the dump file mysqldump -u root -ppassword db_name $tableName >> db_sync.sql done < <( echo $sql | mysql -udbuser -pdbpassword databasename | tail -n +2) done This will work if you put the numbers on the command line: ./push.sh 17 18 19 See the getopts tutorial for more information about processing command line arguments if you want to get complicated. Here is a short example of getting multiple arguments in an array: numbers=() while getopts ":t:" opt "$@"; do case "$opt" in t) numbers+=($OPTARG) ;; esac done for number in ${numbers[@]}; do echo $number done For example: $ ./test.sh -t 17 -t 18 -t 19 17 18 19
{ "language": "en", "url": "https://stackoverflow.com/questions/25485571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to do conditional formatting on Chart axis values? I have a chart where I want to format values based on a cell selected type: "Percentage" or "Number". If "Percentage" is selected I want to display chart values like "0.00%", else I want to display values: "# ##0" I found only a way to have only one number format : Also The section Conditionnal Formating is disabled when selecting the chart. Is there a way to make this happend ?
{ "language": "en", "url": "https://stackoverflow.com/questions/69090317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails + Activerecord: How to show records with "ranking ASC" first, then show the rest of the records "name ASC"? I have 2 columns in my awards table: ranking (integer) and name (string). I want to create a scope that shows all the records with the ranking column filled in in ascending order (1, 2, 3...), and then the rest of the records that don't have a ranking to show by name ascending (a, b, c) so it would look like this: * *ranking: 1, name: "zz" *ranking: 2, name: "aaa" *ranking: nil, name: "bbbb" *ranking: nil, name: "ccc" *ranking: nil, name: "ddd" *etc... This doesn't seem to work: scope :book_form_sort_order, -> { order("ranking ASC, name ASC").group(:ranking) } A: scope :book_form_sort_order, -> { order("ranking IS NULL, ranking ASC, name ASC") }
{ "language": "en", "url": "https://stackoverflow.com/questions/22772284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing multiple values for Laravel components from the view resources/views/index.blade.php <x-card title="Products" body="Add or manage products" btn-add-id="addProduct" /> app/view/component/card.php public $title; public $body; public $btn_add_id; public $btn_manage_id; public function __construct($title, $body, $btn_add_id, $btn_manage_id) { $this->title = $title; $this->body = $body; $this->btn_add_id = $btn_add_id; $this->btn_manage_id = $btn_manage_id; } resources/views/components/card.blade.php <div class="card"> <div class="card-body"> <h5 class="py-1">{{ $title }}</h5> <p class="py-1">{{ $body }}</p> <button class="btn btn-primary py-1" id="{{ $btn_add_id }}"> <i class="fas fa-plus-circle"></i> Add </button> </div> </div> My question: I want to make a reusable card component of bootstrap. So I passed several values to the card from the view page but throws me an error saying 'Unresolvable dependency resolving, highly appreciate if somebody can teach me how to pass multiple data to the components and use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/71822239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Highcharts - categorial data values represented by distinct dots? In highcharts, I have a bunch of simple, standartized categorial data. See fiddle here. series: [{ name: 'sample element 1', data: [3, 3, 2] }, { name: 'sample element 2', data: [1, 4, 3] }, { name: 'sample element 3', data: [2, 4, 4] }, { name: 'sample element 4', data: [4, 2, 2] }] Is it possible with highcharts to display a categorial scatter diagram, only without the dot overlap in the categories, in the manner shown below? Each value would have its own dot representative, showing distributions for each variable in that way. Advanced feature: When hovering over a single value dot, the lines between all dots of the corresponding sample element should reappear so that the connections between the values become obvious. Would that take a lot of deep code customization, or am I better off doing that with a different framework like d3.js? Thanks for ideas! A: In case when values are the same, there are printed in the same place. But you can use http://api.highcharts.com/highcharts#plotOptions.series.pointPlacement to move serie. A: I have typically done this by adding a decimal to the x value of the points that need to 'stack', as it were. There isn't a great (easy) way to do it dynamically that I have found, but if your values are going to fall within a fairly controlled range, it works well. Example: * *http://jsfiddle.net/zew9dt8e/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/26340983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using audioplayers to play a single note from a button I am doing an outdated tutorial on the audioplayers package and just trying to play a single note from when the button is pressed. I am not able to get it to work, can someone please help import 'package:flutter/material.dart'; import 'package:audioplayers/audioplayers.dart'; void main() => runApp(XylophoneApp()); class XylophoneApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Center( child: TextButton( onPressed: () { final player = AudioCache(); player.play('note1.wav'); //ERROR THAT 'play' method is not valid }, child: Text('Click Me'), ), ), ), ), ); } } A: In order to play sound from assets, you need a AudioPlayer and set asset to it. onPressed: () async { final player = AudioPlayer(); await player.setAsset('note1.wav'); // make sure to add on pubspec.yaml and provide correct path player.play(); } A: Finally found the fix, the problem all had to do with the new version of audioplayers having all the functions in one class without having to import seperatly audiocache onPressed: () { final player = AudioPlayer(); player.play(AssetSource("note1.wav")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/72914661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IoT project with raspberry-pi3 and Bluemix. Error : TwilioRestClient has been removed from this version of the library I'm doing a Internet of Thing(IoT) project, and I follow a sample from below sources. But I fail at last step when I push to start this app. https://www.ibm.com/blogs/bluemix/2015/04/tutorial-using-a-raspberry-pi-python-iot-twilio-bluemix/ 1. I am using 'cf push to start the app', it works until crash. 2. I am using 'cf logs python-iot-hackathon2 --recent' to see logs, and there are two errors 3. There is a python code that given from tutorial source, i think i should edit the code from line7~12, but I do not know how. If there is another problem, please teach me how to do it. Thanks. ex. There are two error, if you can not see clearly. 1. Err: You must give at least one requirement to install (see "pip help install") 2. Err: Traceback (most recent call last): Err: File "server.py". line12, in Err: twilioClient = TwilioRestClient(twilio Account, twilio Token) ERR: File "/home/vcap/deps/0/python/lib/python2.7/site-packages/twilio/base/obsolete.py", line 20. in new_func Err: .format(func.name) Err: twilio.base.obsolete.obsoleteException: TwilioRestClient has been removed from this version of the library. Please refer to current documentation for guidance. A: For: 1. Err: You must give at least one requirement to install (see "pip help install") You need to run this on the Raspberry PI: sudo pip install twilio If you don't have pip installed then run: sudo apt-get install python3-pip and then again: sudo pip install twilio for 2. Err: Traceback (most recent call last): Err: File "server.py". line12 Basically the twilio client definition needs to be similar to: from twilio.rest import Client client = Client(account_sid, auth_token) so from the trace, line 12 in server.py should be similar to from twilio.rest import Client //this should be also changed twilioClient = Client(account_sid, auth_token) //this is line 12
{ "language": "en", "url": "https://stackoverflow.com/questions/47300110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Weblogic 9.2 support Sun Jdk 1.6? Does anyone have experience running Weblogic 9.2 on JDK 1.6? I am having trouble finding that information on Oracle site. In the Supported Configurations page they just mention Sun 32/64bit JDK but I haven't found any references to specific java version. I would like to upgrade from java 1.5 to 1.6, but we are not quite ready yet to upgrade Weblogic. A: Java 1.5 is the supported version for WebLogic 9.2. It looks like 10.0.3 introduced Java 6 for RH AS 5, 64-bit. Look here for links to info about each version of WebLogic. From there, you have to choose your operating system and architecture to find out what JVMs are supported. A: Weblogc 9.2.1 - 9.2.3 doesnot support JDK 1.6, any patch/revision of JDK 1.5 will get supported .Latest on today's date is patch 22 of JDK 1.5.
{ "language": "en", "url": "https://stackoverflow.com/questions/617597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Developing a "Flash Briefing" on Google Home I publish a flash briefing skill on Amazon's Alexa. It is a brief news update on a specific topic. I provide the information to Alexa via a json file that is updated every 10 minutes. I'd like to publish something similar on Google Home devices. However, when I look at DialogFlow, that API appears to be conversational-based. Is that the right API for this type of app? Is there a Template for flash-briefing-like apps (i.e., easy to launch apps that don't require any additional user input after launching)? A: No, you don't need a conversational Action for what you're doing. Depending on the specifics of how you're providing the content, you may wish to look at either Podcast Actions or News Actions. These methods document what Google is looking for to make structured content available to the Google Assistant.
{ "language": "en", "url": "https://stackoverflow.com/questions/49040001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Load array havng lacs of records on server startup in php When we are starting the PHP server online,if at that time we want to load an array having lot of records in the web application before any users visit the homepage.Because loading a big array will take a lot of time when users visit the site online.So i want to load it on server start,so that when user comes he should get everything ready... How can we load an array having lacs of records in server on starting in PHP. A: I believe you are asking how to load and store a shared list of content, that all users using the application can access. This is so that each time a user loads a page you don't have to load the contents from a database. This can be done easily with Java, as you mentioned, but with PHP you'll have to push shared application data outside of PHP... MemCache is one option. See: How to set a global variable accessible throughout the application
{ "language": "en", "url": "https://stackoverflow.com/questions/22904739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Spotify iOS SDK in India I am creating an streaming app and want to use the Spotify iOS SDK for the streaming purpose. But, the services of Spotify are not available in India. I have the Spotify premium account (based in US). The development will be held in India. My question is, can I use the Spotify iOS SDK in India using a US based premium account without any proxy network? A: Your question is: "Can I use the Spotify iOS SDK in India using a US based premium account without any proxy network?". Based on the fact that you're trying to create a streaming app, I'd think that the question you intended to ask is: "Is it possible to enable users to stream Spotify music in India?" My answer: I've just read (parts) of the Developer terms of the Spotify SDK. One thing I noticed was: Streaming via the Spotify Platform shall only be made available to subscribers to the Premium Spotify Service. So if I'm right, it is only possible to stream Spotify's music if your users have a Premium Spotify account, which currently isn't available in India, all by there self. It is however possible to use the iOS SDK in India, but this will exclude the possibility to stream (preview-)audio for non-premium users. A: As far as I know, it's the account's country and not the location of the user what is used to determine if a user can access Spotify. In other words, with a US Premium account you can use Spotify wherever you are in the world as long as you keep paying for the subscription. Read more on this thread. You should be able to use your account while developing your app. Of course, a user trying to create a Spotify account from India will see a "Spotify is not available in your country" message when trying to sign up, but users accessing from countries where Spotify is available won't have any problem in signing up and logging in to your app. A: Three simple steps: * *Download any VPN app from App Store i.e., VPN 24. *Go to App store account, change your region and country to USA by filling any sample address. *Now search Spotify Music on App Store and Download it! You'll have to keep VPN turned on while using Spotify otherwise it won't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/30500063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Creating a timetable using JavaScript I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code: var p = document.getElementById('paragraph'); var table = document.createElement('table'); var tbody = document.createElement('tbody'); table.appendChild(tbody); for (let i = 0; i < lines; i++){ let tr = document.createElement('tr'); for (let j = 0; j < columns; j++){ let td = document.createElement('td'); } tbody.appendChild(tr); } p.appendChild(table); However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table. Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells? A: I think you need something like this to insert the data. We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function. <!DOCTYPE html> <html> <body> <div class="inputs"> <input type="text" id="input1" placeholder="Enter first col data" > <input type="text" id="input2" placeholder="Enter second col data" > </div> <br> <br> <br> <table id="myTable"> <thead style="background-color: beige;"> <tr> <td>default head row cell 1</td> <td>default head row cell 2</td> </tr> </thead> <tbody></tbody> </table> <br> <button type="button" onclick="myFunction()">add data to body row</button> <script> function myFunction() { var table = document.querySelector("#myTable tbody"); var row = table.insertRow(); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); const val1 = document.getElementById('input1').value; const val2 = document.getElementById('input2').value; cell1.innerHTML = val1; cell2.innerHTML = val2; } </script> </body> </html> A: I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which information that users entered will be stored. This you can also do by using build in function «insertCell()» Next, you access the fields in which the user has entered data Retrieve values ​​using the «value» built-in function Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step You can look at the written code below for better assimilation of information <!DOCTYPE html> <html> <body> <div class="inputs" > <input type="text" id="firstColumn" placeholder="Enter data here" > <input type="text" id="SecondColumn" placeholder="Enter data here" > </div> <table id="Table"> <thead> <tr> <td style="background-color: pink;">Name of first column</td> <hr> <td style="background-color: purple;">Name of second column</td> </tr> </thead> <tbody></tbody> </table> <br> <button style="background-color: yellow;" type="button" id = "btn">Add</button> <script> const button = document.querySelector('#btn'); btn.onclick = function() { var table = document.querySelector("#Table tbody"); var row = table.insertRow(); var Fcell = row.insertCell(0); var Scell = row.insertCell(1); const Fdata = document.getElementById('firstColumn').value; const Sdata = document.getElementById('SecondColumn').value; Fcell.innerHTML = Fdata; Scell.innerHTML = Sdata; } </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/70694503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does this NSMutableArray lose a member when it initializes an NSMutableDictionary? There must be something I don't understand about dictionaries. I have the following code: NSArray *keys=[[NSArray alloc] initWithObjects:@"first person singular", @"second person singular", @"third person singular", @"first person plural", @"second person plural", @"third person singular", nil]; //This array logs a count of 6. NSMutableArray *endingsPossible = [[NSMutableArray alloc] initWithObjects:@"iar", @"iēris", @"iētur", @"iēmur", @"iēminī", @"ientur", nil]; //This array logs a count of 6. NSDictionary *setOfEndings = [[NSDictionary alloc] initWithObjects:endingsPossible forKeys:keys]; //This dictionary logs a count of 5. How is one of the members getting lost? A: "third person singular" key is repeated twice. A: You have duplicate entries for your keys, third person singular. That is why you only get 5 objects. Change it to third person plural for expected output I guess.
{ "language": "en", "url": "https://stackoverflow.com/questions/12974884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sqlite wont save data added I'm making an app, which needs a sqlite database. I can add data and view it, but on each restart of the app, closing, reopening the data get deleted. Why is that? DB Handler: package com.spxc.wakeuptext.sql; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "contactsManager"; // Contacts table name public static final String TABLE_CONTACTS = "contacts"; // Contacts Table Columns names private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_PH_NO = "phone_number"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); // Create tables again onCreate(db); } /** * All CRUD(Create, Read, Update, Delete) Operations */ public // Adding new contact void addContact(WhiteList contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); // Contact Name values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone // Inserting Row db.insert(TABLE_CONTACTS, null, values); db.close(); // Closing database connection } // Getting single contact WhiteList getContact(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PH_NO }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) cursor.moveToFirst(); WhiteList contact = new WhiteList(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2)); // return contact return contact; } // Getting All Contacts public List<WhiteList> getAllContacts() { List<WhiteList> contactList = new ArrayList<WhiteList>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_CONTACTS; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { WhiteList contact = new WhiteList(); contact.setID(Integer.parseInt(cursor.getString(0))); contact.setName(cursor.getString(1)); contact.setPhoneNumber(cursor.getString(2)); // Adding contact to list contactList.add(contact); } while (cursor.moveToNext()); } // return contact list return contactList; } // Updating single contact public int updateContact(WhiteList contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); values.put(KEY_PH_NO, contact.getPhoneNumber()); // updating row return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) }); } // Deleting single contact public void deleteContact(WhiteList contact) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) }); db.close(); } // Getting contacts Count public int getContactsCount() { String countQuery = "SELECT * FROM " + TABLE_CONTACTS; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); cursor.close(); // return count return cursor.getCount(); } } And I have my activity which is adding 1 record on startup just to have something there. My activity / fragment: package com.spxc.wakeuptext.frag; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.Dialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.spxc.wakeuptext.R; import com.spxc.wakeuptext.sql.DatabaseHandler; import com.spxc.wakeuptext.sql.WhiteList; public class Fragment_2 extends SherlockListFragment{ private ArrayList<String> results = new ArrayList<String>(); private String tableName = DatabaseHandler.TABLE_CONTACTS; private SQLiteDatabase newDB; private static final int ADD = 1; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); View v = inflater.inflate(R.layout.fragment_2, null); return v; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); DatabaseHandler db = new DatabaseHandler(getActivity()); db.addContact(new WhiteList("Ravi", "9100000000")); openAndQueryDatabase(); displayResultList(); } private void openAndQueryDatabase() { try { DatabaseHandler dbHelper = new DatabaseHandler(getActivity().getApplicationContext()); newDB = dbHelper.getWritableDatabase(); Cursor c = newDB.rawQuery("SELECT name, phone_number FROM " + tableName, null); if (c != null ) { if (c.moveToFirst()) { do { String firstName = c.getString(c.getColumnIndex("name")); int age = c.getInt(c.getColumnIndex("phone_number")); results.add("Name: " + firstName + ",Pne: " + age); }while (c.moveToNext()); } } } catch (SQLiteException se ) { Log.e(getClass().getSimpleName(), "Could not create or Open the database"); } finally { if (newDB != null) newDB.execSQL("DELETE FROM " + tableName); newDB.close(); } } private void displayResultList() { TextView tView = new TextView(getActivity()); tView.setText("This data is retrieved from the database and only 4 " + "of the results are displayed"); getListView().addHeaderView(tView); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, results)); getListView().setTextFilterEnabled(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); MenuItem search = menu.add(0, ADD, 0, "Refresh"); search.setIcon(android.R.drawable.ic_menu_add); search.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case ADD: addNumber(); return true; default: return super.onOptionsItemSelected(item); } } public void addNumber(){ LayoutInflater factory = LayoutInflater.from(getActivity()); final View textEntryView = factory.inflate(R.layout.text_entry, null); final EditText name = (EditText) textEntryView.findViewById(R.id.editText1); final EditText phone = (EditText) textEntryView.findViewById(R.id.editText2); name.setHint("Name"); phone.setHint("Phone Number"); final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle( "Contact information").setView( textEntryView).setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { DatabaseHandler db = new DatabaseHandler(getActivity()); db.addContact(new WhiteList(name.getText().toString(), phone.getText().toString())); openAndQueryDatabase(); displayResultList(); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* * User clicked cancel so do some stuff */ } }); alert.show(); } } Why isn't my database data getting saved? I'm running the app on a real device. All the data get deleted on reopening the app. Any help is much appreciated! A: This is because you are deleting all records from the table in every openAndQueryDatabase() finally { if (newDB != null) newDB.execSQL("DELETE FROM " + tableName); newDB.close(); } A: I guess your are again recreating the database again ..every time application starts A: Yes, because creating your db code is in onCreate method. public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); }
{ "language": "en", "url": "https://stackoverflow.com/questions/18561630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove products from a JSON-formatted list? (using an ID) here is an example of the JSON generated from values retrieved from my database: { "product": [ { "id": "1", "title": "producta", "size": "50", "weight": "1000", "quantity": "100", "cartID": "1" }, { "id": "2", "title": "productb", "size": "50", "weight": "1000", "quantity": "100", "cartID": "2" }, { "id": "3", "title": "productb", "size": "10", "weight": "9000", "quantity": "100", "cartID": "3" }, { "id": "4", "title": "productd", "size": "100", "weight": "500", "quantity": "100", "cartID": "4" }, { "id": "5", "title": "producta", "size": "45", "weight": "880", "quantity": "120", "cartID": "5" } ] } When the user selects to remove an item from the shopping cart, the variable $remove_cartid is passed to my PHP page. If $remove_cartid = 4, then the product with "cartID": "4" must be removed: { "product": [ { "id": "1", "title": "producta", "size": "50", "weight": "1000", "quantity": "100", "cartID": "1" }, { "id": "2", "title": "productb", "size": "50", "weight": "1000", "quantity": "100", "cartID": "2" }, { "id": "3", "title": "productb", "size": "10", "weight": "9000", "quantity": "100", "cartID": "3" }, { "id": "5", "title": "producta", "size": "45", "weight": "880", "quantity": "120", "cartID": "5" } ] } I have made several attempts using the PHP explode function to try and remove the product from the JSON list, but I feel that there is a better way (one that will actually work) Any advice or help is greatly appreciated A: $list = json_decode($jsonList, true); foreach ($list['product'] as $key => $product) { if ($product['cartID'] == $remove_cartid) { unset($list['product'][$key]); } } $jsonList = json_encode($list);
{ "language": "en", "url": "https://stackoverflow.com/questions/9305932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pandas Similar Function to COUNTIFS Sample Data Please see Sample Data image. I'm trying to replicate the COUNTIFS functionality within Python / Pandas but I'm having troubles finding the correct solution. =COUNTIFS(B:B,"BD*",A:A,A2,C:C,">"&C2) B is the Type column, A is the Reference column, and C is the Doc Condition column. So the count is only greater than zero if the Type is 'BD', the Reference Matches the current row's Reference, and the Doc Condition is greater than the current row's Doc Condition. I hope that makes sense? I've tried coming to a solution using GroupBy but I'm not getting any closer to my desired solution and I think I'm overcomplicating this. A: You should include your input data as text. Screenshots are really hard to work with. You can use numpy broadcasting. However, this will have an n^2 computational complexity since you are comparing every row against every other row: reference, type_, doc_condition = df.to_numpy().T match = ( (type_[:, None] == "BD") & (reference[:, None] == reference) & (doc_condition[:, None] < doc_condition) ) df["COUNTIFS"] = match.sum(axis=1) Within the snippet above, you can read reference[:, None] as "the Reference value of the current row; reference as "the Reference values of all rows". This is what enables the comparison between the current row and all other rows (including itself) by numpy.
{ "language": "en", "url": "https://stackoverflow.com/questions/74620537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is Colorama required for Flask or Click? I'm trying to do the Flask "Hello World" tutorial and when I do the 'flask run' command on terminal I get the following traceback: PS C:\Users\boymeetscode\PycharmProjects\beerRPG> flask run Traceback (most recent call last): File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\Scripts\flask-script.py", line 9, in <module> sys.exit(main()) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 990, in main cli.main(args=sys.argv[1:]) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 596, in main return super().main(*args, **kwargs) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1062, in main rv = self.invoke(ctx) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1668, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 763, in invoke return __callback(*args, **kwargs) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 763, in invoke return __callback(*args, **kwargs) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 844, in run_command show_server_banner(get_env(), debug, info.app_import_path, eager_loading) File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 678, in show_server_banner click.echo(f" * Environment: {env}") File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\utils.py", line 294, in echo file = auto_wrap_for_ansi(file) # type: ignore File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\_compat.py", line 541, in auto_wrap_for_ansi import colorama ModuleNotFoundError: No module named 'colorama' I am on Windows, Python 3.9.7 and did the pip install flask in my venv so if colorama is a dependency I would expect that it would have been installed automatically. Why isn't it? Update: I manually installed colorama and now Flask works. I'm just still confused why if this is a dependency it wasn't installed automatically. My pip install didn't appear to return any errors. A: Can confirm something in conda or click broke recently: colorama is missing after installing click (which was installed for black in my case). I use conda environment files so instead of manually installing I added a more recent version with - conda-forge::click in the .yml file. Then conda update installed click 8.03 and colorama, over click 8.0.1 which I had. Without an env file conda install -c conda-forge click should do the trick. I do not know what exactly fixed it though, it is not in click's release notes: though there was arecent change to always install colorama, that was in version 8.0.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/69421726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling type-bound procedure for an array of derrived types in Fortran Let's assume that I have a derived type Coordinates with its type-bound procedure swap: module myTypes implicit none public :: Coordinates type Coordinates real :: x,y contains procedure :: swap ! Error here end type contains subroutine swap(this) class (Coordinates) :: this this%x = this%x + this%y this%y = -(this%y - this%x) this%x = this%x - this%y end subroutine end module Now, if I have an instance of Coordinates called point_A, and if I want to call the type-bound procedure swap for it, I would just write: call point_A%swap. But if I have an array of instances of Coordinates, like: type(Coordinates), dimension(:), allocatable :: setOfPoints then to call the swap for all the elements of setOfPoints, I would like to write: call setOfPoints(:)%swap In order to achieve that, I change the code of swap procedure to: subroutine swap(these) class (Coordinates), dimension(:) :: these integer :: i do i = 1, size(this) this(i)%x = this(i)%x + this(i)%y this(i)%y = -(this(i)%y - this(i)%x) this(i)%x = this(i)%x - this(i)%y end do end subroutine Unfortunately, gfortran doesn't like my idea. On the line that I marked in the first piece of code it says: Error: Passed-object dummy argument of 'swap' must be scalar. Question: how can I call the type-bound procedure for all the instances of the derived type at once? I don't want to put the call in the loop, but I want to do this as I wrote it before, like what we always do with arrays in Fortran. I read about the ELEMENTAL keyword, but if I want to use it, I need the type-bound procedure to be 'pure', which is not my case. I tried to place a DEFERRED keyword after the word procedure, but then compiler says: Error: Interface must be specified for DEFERRED binding I created an interface for swap, but I couldn't figure out where to place it. I tried many positions and compiler said that 'interface was unexpected there'. Also, I read about SELECT TYPE, but I think it won't help in my case. A: Your specific example is perfectly fine with ELEMENTAL module myTypes implicit none public :: Coordinates type Coordinates real :: x,y contains procedure :: swap ! Error here end type contains elemental subroutine swap(this) class (Coordinates), intent(inout) :: this this%x = this%x + this%y this%y = -(this%y - this%x) this%x = this%x - this%y end subroutine end module use myTypes type(Coordinates) :: arr(10) arr = Coordinates(1.,2.) call arr%swap end Your subroutine is pure. If it cannot be, consider using impure elemental.
{ "language": "en", "url": "https://stackoverflow.com/questions/43592606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: In Python, how to format string while saving in a file Is it possible to format strings while saving in a file, similar when printing to a console? f = open('test.txt', 'w') f.write('{0:10} {1:10}').format('one', 'two') f.close() A: Yes it is. I think that one of your closing parenthesis was not where you meant it to be: with open('test.txt', 'w') as f: f.write('{0:10} {1:10}'.format('one', 'two'))
{ "language": "en", "url": "https://stackoverflow.com/questions/31235217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Cloud Platform, ML Engine, "No module named absl" I am trying to train an object detector using TensorFlow following the following tutorial: https://cloud.google.com/blog/products/gcp/training-an-object-detector-using-cloud-machine-learning-engine The tutorial asks to use object_detection.train, however this has been moved to legacy so I've used object_detection.model_main instead. Line 21 of this python file calls the module absl, however this causes the following error (from the GCP Logs Viewer). Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "main", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/root/.local/lib/python2.7/site-packages/object_detection/model_main.py", line 21, in from absl import flags ImportError: No module named absl I tried to include absl>=0.1 in the required packages section of the setup.py file for the object_detection package but that didn't work. Next I tried to move my absl folder into the models/research/object_detection directory before packaging and starting the job, but that didn't work either. How do I fix this? I'm very new to Tensorflow and the GCP platform so your help will be appreciated. Thanks. A: The package that you should be adding to REQUIRED_PACKAGES list in setup.py is 'absl-py>=0.1.0'. Apart from that, download this package tar.gz file to models/research/dist . Install by running pip install absl-py . Then, when starting the job add dist/avsl-0.4.0.tar.gz to the variables passed to the --packages flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/51703508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: create J2me launcher Hi I have to create J2me launcher in which when I run the emulator then icon is displayed when I click on it, then it will redirect me to the website which I have given. I have researched it on internet but I cannot find any solution Please if anyone can help me please help me and it there are any suggestions then give me. A: Why don't you use something like this: platformRequest("http://ololo.com"); It will call a default browser to open the link. A: public void openBrowser(String URL) { try { mainMIDlet.platformRequest(URL); } catch (ConnectionNotFoundException e) { // error } }
{ "language": "en", "url": "https://stackoverflow.com/questions/11591037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: counting the vowels, without using raw input and the string 's' is defined.My result a infinite loop, whats wrong in it k=0 if (s[-1] == "a" or s[-1] == "e" or s[-1] == "i" or s[-1] == "o" or s[-1] == "u"): k=1 else: K=0 t=len(s)-1 while t>=0: if (s[t-1:t] == "a" or s[t-1:t] == "e" or s[t-1:t] == "i" or s[t-1:t] == "o" or s[t-1:t] == "u"): t=t-1 k=k+1 else: t=t-1 print "Number of vowels:", k A: simply use for loop to iterate every character from the string. Demo: In [28]: s = "qazxswedcvfrgbnhyujmkiopl" In [29]: count = 0 In [30]: for i in s: ....: if i.lower() in ["a", "i", "o", "u", "e"]: ....: count += 1 ....: In [31]: print count 5
{ "language": "en", "url": "https://stackoverflow.com/questions/30986482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: how to synchronize between cuda kernel function? I have two cuda kernel functions like this a<<<BLK_SIZE,THR_SIZE>>>(params,...); b<<<BLK_SIZE,THR_SIZE>>>(params,...); After function a started, I want to wait until a finishes and then start function b. so I inserted cudaThreadSynchronize() between a and b like this, a<<<BLK_SIZE,THR_SIZE>>>(params,...); err=cudaThreadSynchronize(); if( err != cudaSuccess) printf("cudaThreadSynchronize error: %s\n", cudaGetErrorString(err)); b<<<BLK_SIZE,THR_SIZE>>>(params,...); but cudaThreadSynchronize() returns error code: the launch timed out and was terminated cuda error how can I fix it? A simple code explanation: mmap(sequence file); mmap(reference file); cudaMemcpy(seq_cuda, sequence); cudaMemcpy(ref_cuda,reference); kernel<<<>>>(params); //find short sequence in reference cudaThreadSynchronize(); kernel<<<>>>(params); cudaMemcpy(result, result_cuda); report result and in kernel function, there is a big for loop which contains some if-else for the pattern matching algorithm to reduce number of comparisons. A: This launch error means that something went wrong when your first kernel was launched or maybe even something before that. To work your way out of this, try checking the output of all CUDA runtime calls for errors. Also, do a cudaThreadSync followed by error check after all kernel calls. This should help you find the first place where the error occurs. If it is indeed a launch failure, you will need to investigate the execution configuration and the code of the kernel to find the cause of your error. Finally, note that it is highly unlikely that your action of adding in a cudaThreadSynchronize caused this error. I say this because the way you have worded the query points to the cudaThreadSynchronize as the culprit. All this call did was to catch your existing error earlier.
{ "language": "en", "url": "https://stackoverflow.com/questions/9902158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the image from a facebook photo comment? Either API or FQL, I am trying to get the photo submitted as comment in a photo post. To make clearer here is what I am saying * *I post a photo on my page timeline. *people now post comments on the said photo *either text comment or attaching photo in each comment. Now, what I am getting is the comment information only. I want to get the information about the photo used in comment also. Thanks. A: The picture (in the comment) could be fetched with the attachment parameter. By default, you did not get the attachment field in the result, so you have to write this field explicitly. just like this - me/posts?fields=comments.message,comments.id,comments.attachment Demo Ref: Comments A: This is the same for page comments as I just discovered: /{page-post-id}/comments?fields=from,message,id,attachment,created_time,comments.fields(from,message,id,attachment,created_time) this will return all replies (and replies to those replies) for a particular page post. if there is an image on a reply it will be under 'attachment' result is a bit like this: Array ( [data] => Array ( [0] => Array ( [from] => Array ( [name] => *********** [id] => *********** ) [message] => test reply with a picture [id] => *********** [attachment] => Array ( [type] => photo [target] => Array ( [id] => *********** [url] => *********** ) [url] => *********** [media] => Array ( [image] => Array ( [height] => 540 [src] => *********** [width] => 720 ) ) ) [created_time] => 2014-03-29T11:59:53+0000 ) [1] => Array ( [from] => Array ( [name] => *********** [id] => *********** ) [message] => *********** [id] => *********** [created_time] => 2014-03-29T11:55:09+0000 ) [2] => Array ( [from] => Array ( [name] => *********** [id] => *********** ) [message] => *********** [id] => *********** [created_time] => 2014-03-29T11:16:45+0000 [comments] => Array ( [data] => Array ( [0] => Array ( [from] => Array ( [name] => *********** [id] => *********** ) [message] => *********** [id] => *********** [created_time] => 2014-03-29T11:18:07+0000 ) [1] => Array ( [from] => Array ( [name] => *********** [id] => *********** ) [message] => ************ [id] => *********** [created_time] => 2014-03-29T11:18:48+0000 )
{ "language": "en", "url": "https://stackoverflow.com/questions/19156246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access a dynamically created control's value in a gridview in ASP.NET I can't figure out how to access the value of a control in a dynamically-created gridview. Thhe problem is that I don't know the name of the control. If I knew the name of the control I could do just do this : string dropDownListText =((DropDownList).row.FindControl("DropDownList1")).SelectedItem.Value;` I know the type of control and I know the cell it is in. Is there any way using the information about the control I have to be able to access the control's value? A: If you know what cell it is, then you could do something like this; TableCell tc = GridView1.Cells[indexOfCell]; // where GridView1 is the id of your GridView and indexOfCell is your index foreach ( Control c in tc.Controls ){ if ( c is YourControlTypeThatYouKnow ){ YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow)c; } } If you don't know what cell it is exactly, then you can always loop through each cell. I am sure there is a better way in Linq. With Linq (I think this should work) var controls = GridView1.Cells[indexOfCell].Cast<Control>(); YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow) controls.Where( x => x is YourControlTypeThatYouKnow).FirstOrDefault(); A: On ItemDataBound event handler of GridView, access the table-cell as follows. Within the cell, Controls collection provides you access to ASP control embedded in the cell TableCell cell = e.Item.Cells[0]; if (cell.Controls.Count > 0) { cell.Controls[0].Visible = false; } A: I have had the same problem. Add a command name to your field like CommandName="ProjectClick". Then add a rowcommand and in the row command do this: if (e.CommandName.Equals("ProjectClick")) { } or you can use the text: if (e.CommandName.Equals("")) { if (((System.Web.UI.WebControls.LinkButton)(e.CommandSource)).Text.Equals("Projects")) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/10434579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ServiceStack Clients and Ambiguous Routes I have a service stack service we'll call Orders that has the standard GET routes * */orders - Gets All Customers */orders/{Ids} - Gets Specific customers This works all fine and dandy, but I thought I'd add another route * */orders/customers/{CustomerId} -Gets orders with a specific customer id This works find when hitting the routes in the browser, but when I use the ServiceStack Client I get ambiguous routes exception, and it lists the three routes. I'm not quite sure what the best way around this is..is what I'm doing not the correct RESTish way to it? I know I can simply manual enter the routes into the JsonServiceClient like client.Get<List<Orders>>("/orders/customers/7") and that will work, but I would prefer to do it the typed way...i.e client.Get(new OrdersRequest { CustomerId = 7 }); Here's an example RequestDTO i'm using public class OrdersRequest : IReturn<List<Orders>> { public int[] Ids {get; set;} public CustomerId {get; set;} public OrdersRequest(params int[] ids) { this.Ids = ids; } } Do I have to use different Dtos for this or...? any help or pointers to any of the samples that have a way around this, or a better way to create the services would be appreciated. Thanks A: My advise is you're not using REST properly. There is a good answer about how to best structure a ServiceStack REST service. It's a common issue when starting out, I had issues like this too. Understanding your use case: In your specific case if we look at /orders/customers/7 this would work better is you think of it this way: /customers/7/orders The reason you do it this way: * *It resolves your route ambiguity problems *The context is clear. We can see we are working with Customer 7 without navigating a long url *We can see 'with customer 7' we want their orders Think of routing like this: /orders Everybody's Orders /orders/1 Order 1 (without being aware of the customer it belongs to) /customers All Customers /customers/7 Customer 7's details /customers/7/orders All Customer 7's orders /customers/7/orders/3 Customer 7's order number 3 The beauty of doing things like this is operations on data are done consistently. So you want to find all cancelled orders: /orders/cancelled You want to cancel a specific order by it's orderId /orders/4/cancel You want to list a specific customer's open orders /customers/6/orders/open You want to list customer 6's cancelled orders /customers/6/orders/cancelled You want to cancel an order for customer 6 that you are viewing /customers/6/orders/2/cancel Obviously these are just scenarios, your routes will differ. Simplifying action handlers: You will probably want to define your action handlers so they can cope with coming from multiple routes. What I mean is, one action handler would be responsible for Listing Orders /orders /customers/6/orders What I do is this: [Route("/orders","GET")] [Route("/customers/{CustomerId}/orders","GET")] public class ListOrdersRequest : IReturn<List<Order>> { public int? CustomerId { get; set; } } So you can see the two order listing routes come in. If they use /orders then our customerId won't have a value but the other route will. So in our action handler we can simply test for this: public List<Order> Get(ListOrdersRequest request) { // Use `CustomerId` to narrow down your search scope if(request.CustomerId.HasValue){ // Find customer specific orders } else { // Find all orders } return orders; } Client-side concerns: So to address your using 'typed' client concerns. Creating the routes and action handlers using the above method will allow you to do: client.Get(new ListOrdersRequest { CustomerId = 7 }); // To get customer 7's orders client.Get(new ListOrdersRequest()); // All orders Thus giving you 1 clear method for Listing Orders. Final thoughts: Obviously it means you will have to rework what you have which will probably be a pain, but it's the best approach, well worth the effort. I hope this helps you understand the best structure. Update: @stefan2410 requested that I address the issue of Kyle's use of an int[] in a route for a GET request: If you want to use an int[] in a GET request you have to consider changing it during transport in the URL so it can be used RESTfully. So you could do this: class OrdersRequest { public string Ids { get; set; } public OrdersRequest(int[] ids) { Ids = string.Join(",", Array.ConvertAll(ints, item => item.ToString())); } } client.Get(new OrdersRequest(new [] {1,2,3})); Creates the route /orders/1,2,3 and matches /orders/{Ids}. The problem with doing this is in order to use the Ids at the server side you have to convert the string "1,2,3" back to an int[]. The better way to deal with an int[] in a request is to use POST. So you can do: class OrdersRequest { public int[] Ids { get; set; } public OrdersRequest(int[] ids) { Ids = ids; } } client.Post(new OrdersRequest(new[] {1,2,3})); Creates the route /orders and matches the route /orders.
{ "language": "en", "url": "https://stackoverflow.com/questions/20590550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Exception safety in the composite pattern I used the composite pattern to represent devices, which I would like to shut down before killing their power (calling their dtor). I ran into a problem trying to group the devices, especially regarding their state. How would I proceed in the following scenario: class IDevice { public: virtual void shutdown() = 0; virtual void turn_on() = 0; virtual bool is_on() const = 0; } class Router: public IDevice {...}; class Computer: public IDevice {...}; class Monitor: public IDevice {...}; // etc... class WorkStation: public IDevice {...}; The work station might contain several devices, and you'd want to shut all of them down safely before killing the station electricity. (In this metaphor, I'm very cheap). It is also worth noting that I would never want any one of the devices turned on on its own - Everything will always act as one unit. The problem comes when one of the inner devices doesn't want to shut down safely - It will throw an exception (e.g. A computer's program prevents it from shutting down). What should is_on() return in that state? what should consecutive method calls do? Alternatively, what is another design pattern can I use to represent my problem better? A: The main big problem is that you want to throw from the dtor. https://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml has a nice explanation of why this does not play nicely with the language and its idioms. In general, if you expect that a device can fail at shutting down, then you should probably handle this part explicity, because it not something that happens "exceptionally". For example, you could have the destructor try to gracefully shut off the device, and in case of errors (or exceptions), apply a force shut off. then, if the user of your system wants to handle the case of a device that can't shut off, he can still call shutoff directly. Finally, modeling from real world objects is just a first draft of your class design. don't worry to notstick to what the real world object do, if it helps to get a more practical design and a better UX.
{ "language": "en", "url": "https://stackoverflow.com/questions/63945051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print value after enabledelayedexpansion Setting a variable in a "setlocal enabledelayedexpansion" works with set HASGCC=0 for /f "delims=" %%i in (...) do ( setlocal enabledelayedexpansion set HASGCC=1 endlocal ) but sadly a echo after doesn't result in the correct value (always 0). echo Finished %HASGCC% Afterwards if !HASGCC! == 0 >>"%PREFS_F... is evaluated correct. How to print correct value. echo Finished !HASGCC! results in Finished !HASGCC! A: Solved it by removing setlocal enabledelayedexpansion but don't know why. A: setlocal with or without EnableDelayedExpansion creates a new scope for variables. It makes a copy of all variables and then all changes are made to these copies. An endlocal leaves this scope and discard the copy and all changes are dsicarded. For some variable manipulations you have to enable delayed expansion for some it's better to use disabled delayed expansion, but the only way to switch between them is to use setlocal. But in your case it seems, that you don't need it at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/70287216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect to another controller/action in anther application I have to build an ASP.NET MVC 3 application that can redirect to other ASP.NET MVC 3 applications by calling their controller/action. I was thinking of just building the URL. I would have to know the controller/action names and the host. I was thinking of storing the Host strings in a database so if the app is moved I would be able to update the database with this information without making changes to code and recompiling. I'm just not sure if this is the best approach. Any help would really be appreciated. A: In general, 3rd party integration is always easier and more maintainable when it's done in a black box manner. Rather than integrate based on how a 3rd party implements their solutions, you integrate based on their black box facade, so that you don't have to deal with knowing their implementation details. Comparing it to a SQL query - a SQL query typically describes just what you want, rather than how you want the database server to retrieve what you want. A: Yes - you absolutely have to know the controllers and action names unless you share a common routing table. However if you think if the destination application as a service, then this is fine as you have restful urls to the service endpoints, as would be typical in any app that calls a service. I would however store these in a single location - as you mentioned table, config file, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/8514758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ModuleNotFoundError: No module named 'win32crypt' I'm trying to run a Python module for a school project and I am getting this error ModuleNotFoundError: No module named 'win32crypt' at line import win32crypt. I've search the website for solution and encountered a post that states pywin32 is required. So I installed it with pip. I also tried installing pypiwin32. None of these installs worked. Now I've tried Dependency Walker to see if there are any dependencies missing and I see at least 100 DLLs that are. How can I fix the issue? A: win32cryrpt is a part of the Windows Extensions for Python or pywin32. It is a wrapper around the Windows crypto API. It doesn't make sense to try and install it without pywin32 and if your install of that has failed then that is the problem you have to solve. Please try pip install pypiwin32 again, being sure to execute it in the correct folder, which is the Scripts subfolder of the Python environment you want to install it in. You may have more than one Python installation without realizing it, and if you run pip from outside that folder, you may get a different instance of pip. The standard location for Python installations is C:\Program Files\Python3x. If the pip install doesn't complete as expected then edit your question to include the messages from the failed install. Did not work isn't enough to go on.
{ "language": "en", "url": "https://stackoverflow.com/questions/54653817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS code for pinterest layout style My challenge is trying to make the listing grid view looking like pinterest similar layout. I've already made a little code with it... but it's not enough. the rows below don't fit each other. #content .category_grid_view li.featured { position:relative; -moz-border-radius:3px; -webkit-border-radius:3px; } #content .category_grid_view li .featured_img { width:69px; height:72px; position:absolute; left:15px; top:0px; text-indent:-9009px; } #content .category_grid_view li p.timing { margin:0; padding:0; } #content .category_grid_view li p.timing span { color:#000; } #content .category_grid_view li .widget_main_title { height:25px;overflow:hidden; clear:left;} #content .category_grid_view li a.post_img {height:auto;width:100%;padding:1%;} #content .category_grid_view li a.post_img img{height:100%;max-height:100%;width:auto;} #page .category_grid_view { width: auto; padding-left:0px; } #content .category_grid_view li a.post_img { height:auto; max-width:100%; overflow:hidden; } #content .category_grid_view li a.post_img img { margin:0 auto; display:block; height:auto; } #content .category_grid_view { margin:-10 0 20px -15px; padding:0; width:650px; clear:both; } #content .category_grid_view li { background: none repeat scroll 0 0 transparent; float: left; list-style: none outside none; margin: -10 0 20px; padding: 0 0 0 15px; position: relative; width: 200px; } #content .category_grid_view li.hr { display: none; } #content { float: left; overflow: hidden; padding-left: 5px; width: 640px; } #content .category_grid_view li a.post_img { display: block; margin-bottom: 0; padding: 0; background: none repeat scroll 0 0 #FFFFFF; border: 0 solid #E2DFDF; box-shadow: 0 0 0 #DDDDDD; height: auto; width: 100%; overflow: hidden; } #content .category_grid_view li a.post_img img { height: auto; overflow: hidden; width: 100%; } #content .category_grid_view li.featured a.post_img { border: 0 solid #B1D7E0; } #content .category_grid_view li .widget_main_title { padding-top: 7px; clear: left; height: 25px; overflow: hidden; background: none repeat scroll 0 0 #EBEBEB; } #content .category_grid_view li .rating { background: none repeat scroll 0 0 #EBEBEB; display: block; margin: 0px 0; padding-bottom: 7px; padding-top: 7px; } #content .category_grid_view li p.review { background: none repeat scroll 0 0 #EBEBEB; border-bottom: 10px solid #EBEBEB; border-top: 1px solid #EBEBEB; color: #EBEBEB; margin-bottom: 20px; padding: 5px 0; } This is how it looks like: http://images.findout-macau.com/2013/09/grid-view-rows.png Meanwhile, i've made search through the web and only found out the following code... yet i don't know how to implement it. Can someone tip me here? Like where tu insert what?! html, body{ margin:auto; width:100%; background-color:#e6e6e6; } #wrapper { width: 100%; margin: 10px auto; } #columns { -webkit-column-count: 4; -webkit-column-gap: 10px; -webkit-column-fill: auto; -moz-column-count: 4; -moz-column-gap: 10px; -moz-column-fill: auto; column-count: 4; column-gap: 10px; column-fill: auto; } .pin { display: inline-block; background: #FEFEFE; border: 2px solid #FAFAFA; box-shadow: 0 1px 2px rgba(34, 25, 25, 0.4); margin: 0 2px 15px; -webkit-column-break-inside: avoid; -moz-column-break-inside: avoid; column-break-inside: avoid; padding: 15px; padding-bottom: 5px; background: -webkit-linear-gradient(45deg, #FFF, #F9F9F9); opacity: 0.85; -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -o-transition: all .3s ease; transition: all .3s ease; } A: You'll need to use a jQuery plugin of some kind to help close all those gaps you're seeing. As James mentioned, masonry is a very popular option. Another plugin (without as many options/features) is jQuery Waterfall. Both have lots of examples to help get you up and running. A: You should insert the code that you have found in to an .css file, then link to it from your html file and use the classes/id's provided (eg. ".pin" "#columns") on the elemts you want to stylize with the code you found A: This is small library which implements Pinterest layout. Filling the grid goes from left to right. Count of columns can be customized in config for each resolution. Columns adaptive changes on resize. Image can be at up or down of pin. https://github.com/yury-egorenkov/pins-grid
{ "language": "en", "url": "https://stackoverflow.com/questions/18968132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SSIS :: How to implement SCD type 2 in SSIS without using SCD Wizard. When incoming dataset has multiple records for the same Business Key In SSIS, if an incoming dataset has multiple records for the same Business Key, how do I load it to the dimensions table with SCD type 2 without using the SCD Wizard. Sample dataset Customer ID Name Segment Postal Code 1 James Corporate 50026 2 Andrew Consumer 33311 3 Steven Consumer 90025 2 Andrew Consumer 33306 3 Steven Consumer 90032 1 James Corporate 50087 3 Steven Consumer 90000 In my case, if I try Loading the dimension table with other SSIS components (Lookup/Conditional Split) all the record show up a new row in the table because they are all coming in all at the same time. I have ‘CurrentFlag’ as the indicator of the current record. In SSIS, if I have an incoming dataset that has multiple records for the same Business Key, How do I get to recognize these, and set the CurrentFlag as necessary, whether or not a record in the target table has that Business Key already? Thanks. A: OK, this is a massive simplification because SCD's are very challenging to correctly implement. You will need to sit down and think critically about this. My answer below only handles ongoing daily processing - it does not explain how to handle historical files being re-processed, which could potentially result in duplicate records with different EffectiveStart and End Dates. By definition, you will have an existing record source component (i.e., query from the database table) and an incoming data source component (i.e., a *.csv flatfile). You will need to perform a merge join to identify new records versus existing records. For existing records, you will need to determine if any of the columns have changed (do this in a Derived Column transformation). You will need to also include two columns for EffectiveStartDate and EffectiveEndDate. IncomingEffectiveStartDate = FileDate IncomingEffectiveEndDate = 12-31-9999 ExistingEffectiveEndDate = FileDate - 1 Note on 12-31-9999: This is effectively the Y10K bug. But, it allows users to query the database between date ranges without having to consciously add ISNULL(GETDATE()) in the WHERE clause of a query in the event that they are querying between date ranges. This will prevent the dates on the columns from overlapping, which could potentially result in multiple records being returned for a given date. To determine if a record has changed, create a new column called RecordChangedInd of type Bit. (ISNULL(ExistingColumn1, 0) != ISNULL(IncomingColumn1, 0) || ISNULL(ExistingColumn2, 0) != ISNULL(IncomingColumn2, 0) || .... ISNULL(ExistingColumn_N, 0) != ISNULL(IncomingColumn_N, 0) ? 1 : 0) Then, in your split condition you can create two outputs: RecordHasChanged (this will be an INSERT) and RecordHasNotChanged (this will be an UPDATE to deactivate the exiting record and an INSERT). You can conceivably route both inputs to the same INSERT destination. But, you will need to be careful suppress the update record's ExistingEffectiveEndDate value that deactivates the date.
{ "language": "en", "url": "https://stackoverflow.com/questions/56071054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Reindex a dataframe using tickers from another dataframe I read csv files into dataframe using from glob import glob import pandas as pd def read_file(f): df = pd.read_csv(f) df['ticker'] = f.split('.')[0] return df df = pd.concat([read_file(f) for f in glob('*.csv')]) df = df.set_index(['Date','ticker'])[['Close']].unstack() And got the following dataframe: Close ticker AAPL AMD BIDU GOOGL IXIC Date 2011-06-01 12.339643 8.370000 132.470001 263.063049 2769.189941 . . . now I would like to use the 'ticker' to reindex another random dataframe created by data = np.random.random((df.shape[1], 100)) df1 = pd.DataFrame(data) which looks like: 0 1 2 3 4 5 6 \... 0 0.493036 0.114539 0.862388 0.156381 0.030477 0.094902 0.132268 1 0.486184 0.483585 0.090874 0.751288 0.042761 0.150361 0.781567 2 0.318586 0.078662 0.238091 0.963334 0.815566 0.274273 0.320380 3 0.708489 0.354177 0.285239 0.565553 0.212956 0.275228 0.597578 4 0.150210 0.423037 0.785664 0.956781 0.894701 0.707344 0.883821 5 0.005920 0.115123 0.334728 0.874415 0.537229 0.557406 0.338663 6 0.066458 0.189493 0.887536 0.915425 0.513706 0.628737 0.132074 7 0.729326 0.241142 0.574517 0.784602 0.287874 0.402234 0.926567 8 0.284867 0.996575 0.002095 0.325658 0.525330 0.493434 0.701801 9 0.355176 0.365045 0.270155 0.681947 0.153718 0.644909 0.952764 10 0.352828 0.557434 0.919820 0.952302 0.941161 0.246068 0.538714 11 0.465394 0.101752 0.746205 0.897994 0.528437 0.001023 0.979411 I tried df1 = df1.set_index(df.columns.values) but it seems my df only has one level of index since the error says IndexError: Too many levels: Index has only 1 level, not 2 But if I check the index by df.index it gives me the Date, can someone help me solve this problem? A: You can get the column labels of a particular level of the MultiIndex in df by MultiIndex.get_level_values, as follows: df_ticker = df.columns.get_level_values('ticker') Then, if df1 has the same number of columns, you can copy the labels extracted to df1 by: df1.columns = df_ticker
{ "language": "en", "url": "https://stackoverflow.com/questions/68365598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IDEA+Gradle: exclude sources from tree and compilation? In IDEA 2019 I have created a Gradle project and added the following lines to the build.gradle file: plugins { id 'java' } sourceSets { main { java { srcDir "../src" include "com/example/abc/**" exclude "com/example/abc/tst/**" } } } When compiling the project, the compiler apparently does what I expect: starting from the ../src folder, it compiles only the abc package and subpackages except the tst subpackage. However, in the IDEA sources tree on the left-hand side, the whole content of src is displayed. It makes it harder to navigate in the project and to understand what is compiled and what is not. Obviously, IDEA is parsing the .gradle file because it correctly understands the ..\src location of my sources. But for some reason it doesn't respect the include and exclude statements. What should I do to make IDEA display exactly the same content which is being compiled? I know I can hide a folder using the "Mark directory as excluded" context menu. But this is a bad solution because it forces me to make the same thing twice in different places and discredits the concept of having everything in the .gradle file.
{ "language": "en", "url": "https://stackoverflow.com/questions/56776543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add custom scroll bar for textbox and listbox in c# winforms Can some explain thoroughly or share your source code on how to change textbox / listbox scroll bar to custom scroll bar on c# winforms. Cause textbox and listbox doesnt have a scroll attribute like on panel. Thanks! Cant find a source code here to study, all i get is locating the scroll position using the GetScrollInfo API. I want to learn how set values or adapt my scroll bar to the default listbox and textbox. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/46780138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R on MacOS Error: vector memory exhausted (limit reached?) I'm trying to run an R script (in particular, I am using the "getLineages" function from the Bioconductor package, Slingshot. I'm wondering why the error "vector memory exhausted (limit reached?)" is showing up when I use this function, as it doesn't seem to be the most memory-intensive function compared to the other functions in this package (with the data I am analyzing). I do understand that there are other questions like this on Stackoverflow, but they all suggest to switch over to the 64-bit version of R. However, I am already using this version. There seem to be no other answers to this issue so far, I was wondering if anyone might know? The data is only ~120mb in size, which is far less than my computer's 8GB of RAM. A: This can be done through R studio as well. library(usethis) usethis::edit_r_environ() when the tab opens up in R studio, add this to the 1st line: R_MAX_VSIZE=100Gb (or whatever memory you wish to allocate). Re-start R and/or restart computer and run the R command again that gave you the memory error. A: I had the same problem, increasing the "R_MAX_VSIZE" did not help in my case, instead cleaning the variables no longer needed solved the problem. Hope this helps those who are struggling here. rm(large_df, large_list, large_vector, temp_variables) A: For those using Rstudio, I've found that setting Sys.setenv('R_MAX_VSIZE'=32000000000), as has been suggested on multiple StackOverflow posts, only works on the command line, and that setting that parameter while using Rstudio does not prevent this error: Error: vector memory exhausted (limit reached?) After doing some more reading, I found this thread, which clarifies the problem with Rstudio, and identifies a solution, shown below: Step 1: Open terminal, Step 2: cd ~ touch .Renviron open .Renviron Step 3: Save the following as the first line of .Renviron: R_MAX_VSIZE=100Gb Step 4: Close RStudio and reopen Note: This limit includes both physical and virtual memory; so setting _MAX_VSIZE=16Gb on a machine with 16Gb of physical memory may not prevent this error. You may have to play with this parameter, depending on the specs of your machine A: I had this problem when running Rcpp::sourceCpp("my_cpp_file.cpp"), resulting in Error: vector memory exhausted (limit reached?) changing the Makevars file solved it for me. Currently it looks like CC=gcc CXX=g++ CXX11=g++ CXX14=g++ cxx18=g++ cxx1X=g++ LDFLAGS=-L/usr/lib
{ "language": "en", "url": "https://stackoverflow.com/questions/51295402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "103" }
Q: How can I get the path of a file from an OpenFileDialog and pass it to a PDFReader? (C#) OpenFileDialog ofd = new OpenFileDialog(); private void button1_Click(object sender, EventArgs e) { ofd.Filter = "PDF|*.pdf"; if (ofd.ShowDialog() == DialogResult.OK) { richTextBox1.Text = ofd.SafeFileName; } } public static string pdfText(string path) { //this is the error, I cannot get the path of the File I chose from the OpenFileDialog PdfReader reader = new PdfReader(ofd.FileName); string text = string.Empty; for (int page = 1; page <= reader.NumberOfPages; page++) { text = text += PdfTextExtractor.GetTextFromPage(reader, page); } reader.Close(); return text; } I need to get the path of the file chosen by the user from the OpenFileDialog but I cant pass it to the PDFReader A: 1) you cannot use a class variable in a static method so accessing ofd in this line: PdfReader reader = new PdfReader(ofd.FileName); should result in an compiler error message that for the non-static field 'ofd' an object instance is required. 2) It seems that you are not calling your method. You need to call it and pass the filename as parameter into it private void button1_Click(object sender, EventArgs e) { ofd.Filter = "PDF|*.pdf"; if (ofd.ShowDialog() == DialogResult.OK) { richTextBox1..Text = pdfText(ofd.SafeFileName); } } Then you need to use the method parameter inside the method: public static string pdfText(string path) { //this is the error, I cannot get the path of the File I chose from the OpenFileDialog PdfReader reader = new PdfReader(path); // Here use path Now the returned string should appear in your richTextBox1
{ "language": "en", "url": "https://stackoverflow.com/questions/51985221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Match string begins and ends with consonant In order to matches any string that begins and ends with a consonant, while no consonants in between, I know that r'^[b-df-hj-np-tv-z][^b-df-hj-np-tv-z]*[b-df-hj-np-tv-z]$' works. But I would like to know, what is the problem with r'^[^aeiou\s][aeiou]*[^aeiou\s]$'? It seems that it doesn't work. And by the way, what are the difference between '^ string $' and '\b string \b' Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/74001362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which of the different type of mobile apps has the worst access to native APIs ? and WHY? my question is which of the different type of mobile apps has the worst access to native APIs ? and WHY?, the option is:Native Apps\Mobile Web Apps\Hybrid Apps. And please give me a reason, thanks !!! A: Mobile Web Apps. U are relying on plugins to access native API's. Native Apps has the access to the API integrated in the native Language (java for android, objective c for iOS). Hybrid Apps: u can program the device dependant code in native. Mobile WEb, u need a plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/24362542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: is it possible to convert uploadcollection's object into a xstring? Using the sapui5 uploadcollection to upload files in the frontend and then sending them through ajax with a post request... I need to know how to convert te returned object from the uploadcollection control into a xstring, so then I can send that xstring (that contains the file content) To a sap gateway by using ajax post method. Any idea how could I do this? Right now I'm sending files by using the uploadcollection, once I upload an attachment, the control returns an object that represents the file content. I'm trying to make this object a xstring by using filereader: //obtiene archivo var file = files[i]; //Convierte archivo en binario var reader = new FileReader(); reader.onload = function(readerEvt) { var binaryString = readerEvt.target.result; var base64 = btoa(binaryString); var base64file; if(typeof base64file == "undefined" || typeof base64file == null){ base64file = base64; }else{ base64file = base64file +'new'+base64; } }; reader.readAsBinaryString(file); console.log(file) But this work only with files of type image, the others like pdf, .doc etc etc give the following error when I try to send them with ajax. "The Data Services Request could not be understood due to malformed syntax". Any idea how can I send convert these files into a xstring data? A: Take a look at this example. Hope this helps. View <u:FileUploader change="onChange" fileType="pdf" mimeType="pdf" buttonText="Upload" /> Controller convertBinaryToHex: function(buffer) { return Array.prototype.map.call(new Uint8Array(buffer), function(x) { return ("00" + x.toString(16)).slice(-2); }).join(""); }, onChange: function(oEvent){ var that = this; var reader = new FileReader(); var file = oEvent.getParameter("files")[0]; reader.onload = function(e) { var raw = e.target.result; var hexString = that.convertBinaryToHex(raw).toUpperCase(); // DO YOUR THING HERE }; reader.onerror = function() { sap.m.MessageToast.show("Error occured when uploading file"); }; reader.readAsArrayBuffer(file); }, A: I figured it out by filling an array everytime that a file was uploaded through the control, change: function(oEvent) { //Get file content file = oEvent.getParameter("files")[0]; //Prepare data for slug fixname = file.name; filename = fixname.substring(0, fixname.indexOf(".")); extension = fixname.substring(fixname.indexOf(".") + 1); //fill array with uploaded file var fileData = { file: file, filename: filename, extension: extension } fileArray.push(fileData); }, and then I did a loop over that array to post every single file I keept there by using ajax method post. $.each(fileArray, function(j, valor) { //get file file = fileArray[j].file; //get file lenght var numfiles = fileArray.length; //Convert file to binary var reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = function(evt) { fileString = evt.target.result; //get and make slug filename = fileArray[j].filename; extension = fileArray[j].extension; slug = documento + '/' + filename + '/' + extension; //User url service var sUrlUpload = "sap url"; runs++; //Post files jQuery.ajax({}); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/53676404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do we know we reached the last message in the kafka topic using KafkaMessageListenerContainer I am running consumer using KafkaMessageListenerContainer.I need to stop the consumer on the topic's last message.How can i identify particular message is the last message in the topic. A: You can get it with the following shell command (remove --partition parameter to get offsets for all topic's partitions): ./bin/kafka-run-class kafka.tools.GetOffsetShell --broker-list <host>:<port> --topic <topic-name> --partition <partition-number> --time -1 As you can see, this is using the GetOffsetShell [0] object that you may use to get the last message offset and compare it with record's offset. [0] https://github.com/apache/kafka/blob/trunk/core/src/main/scala/kafka/tools/GetOffsetShell.scala
{ "language": "en", "url": "https://stackoverflow.com/questions/65786747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Passing multiple line value from JCL instream to Cobol variable 88 Example: 01 VAR1 PIC 9(05). 88 WS-VAR1 VALUE 1000 1001 1002 1003 1004 1009 2000 2002 3000 4000 4009 5000 5001 6000 7000 8000 2332 8484. How can we pass value from JCL as instream to a Cobol program variable 88. So, that it will be easier to modify the value without changing the program. Two solutions which I found: 1. Using internal indexed table. So that Binary search will do the task fast. 2. Using VSAM file instead of passing data instream. (Less likely) I think Binary search definitely be slower than 88 condition check. I am trying to find something of equivalent efficiency as of 88 condition check. A: It sounds like you want to pass a value from JCL PARM= or from SYSIN to make the COBOL program independent of a hard coded value. This web article has a good explanation of how you can accomplish this. JCL looks like this: //* ******************************************************************* //* Step 2 of 4, Execute the COBOL program with a parameter. //* //PARJ1S02 EXEC PGM=CBLPARC1, // PARM='This is a Parameter from the EXEC and PARM= ...' and in the COBOL program linkage section: ***************************************************************** LINKAGE SECTION. 01 PARM-BUFFER. 05 PARM-LENGTH pic S9(4) comp. 05 PARM-DATA pic X(256). In your case you can validate the data passed in the linkage section based on your criteria. So, once validated, you could move the value from the linkage section after converting it to a numeric value for the test.
{ "language": "en", "url": "https://stackoverflow.com/questions/52088593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to solve NoClassDefFoundError in cucumber test i am using eclipse as a IDE and Selenium web driver. i am trying to run test in cucumber-JVM. when i am run test it show me "NoClassDefFoundError ". can anyone help me to solve my problem. all relevant jar files are build in to project file. A: Add cucumber-jvm-deps-1.0.3.jar file into your build path. You can download cucumber-jvm-deps-1.0.3.jar file from cucumber-jvm-deps-1.0.3 A: If the NoClassDefFoundError is coming from either XmlPullParser or dom4j/element u need to install this Eclipse Plugin/Update: Eclipse -> Help -> Install New Software… http://cucumber.github.com/cucumber-eclipse/update-site
{ "language": "en", "url": "https://stackoverflow.com/questions/18513603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS: Building a slideshow with fullscreen images I want to build a slideshow in which you slide images (displayed in fullscreen modality). I was planning to use UIViews and add gesture recognizers.. but I was wondering if there is something already done I can reuse, or any tip. I would like to have the same effect you have when you slide through open apps on the iPad (you can slide them, and you can slide and you still see part of the first view when the second view comes in. (and in case you are moving back your finger, the first view comes back. thanks A: You can use the Three20 photo viewer. You can look at this tutorial for help on using it. There is also a WWDC video from last year which gives you an idea on how this can be implemented. There are other tools that you can look into. Cocoa Controls has a fairly exhaustive list of tools that you can use for your projects. A: At the most basic level, a UIScrollView with paging enabled will work fine for swiping to get to the next image. You'll probably need to be more specific than that.
{ "language": "en", "url": "https://stackoverflow.com/questions/6372389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS: Adding Qt to an existing Xcode project I want to use some Qt core functionality in an existing iOS 7 Xcode project (similar to this). I do not need Slots or Signals. Is there a way to import the Qt libraries, and use them in the existing Xcode project? Regards. A: Hi have you tried QT for iOS? QT for iOS
{ "language": "en", "url": "https://stackoverflow.com/questions/24636022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show selected options as the bootstrap dropdown menu in Html & JavaScript Is it possible to create a multi-select checkbox dropdown like this in Bootstrap, HTML and JavaScript. I have tried I couldn't able to achieve it. I'm new to JavaScript as well However I'm just exploring the JS and make it to work but this seems really challenging for me. I don't know how to implement JS script for this. For instance: If the user selects the countries in the multiselect checkbox I want it to show it all countries name instead of Choose option. code: <div>Country</div> <div class="row" name="country_checkbox" id="id_row"> <div class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#"> <span id="selected">Choose option</span><span class="caret"></span></a> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="US" placeholder="Select Country" id="id_country_0" onclick="filter_type();"> US</label> </li> <li><label for="id_country_1"><input type="checkbox" name="country" value="India" placeholder="Select Country" id="id_country_1" onclick="filter_type();"> India</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="Japan" placeholder="Select Country" id="id_country_2" onclick="filter_type();"> Japan</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="UK" placeholder="Select Country" id="id_country_3" onclick="filter_type();"> UK</label> </li> </ul> </div> js fiddle here: http://jsfiddle.net/shalman44/92drs7ax/3/ A: Since you are already using bootstrap, you might aswell want to use jQuery. There is a plugin called bootstrap-select for achieving a multi select like in your example, where the syntax is as follows: <select class="selectpicker" multiple> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> $(function () { $('select').selectpicker(); }); You might also want to have a look at this question. A: I just searched google with "bootstrap multiselect" and i found this codepen $(document).ready(function() { $('#multiple-checkboxes').multiselect({ includeSelectAllOption: true, }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css"> <div class=""> <strong>Select Language:</strong> <select id="multiple-checkboxes" multiple="multiple"> <option value="php">PHP</option> <option value="javascript">JavaScript</option> <option value="java">Java</option> <option value="sql">SQL</option> <option value="jquery">Jquery</option> <option value=".net">.Net</option> </select> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/69704667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }